blob: 1b7acabf70f97cba05020ed811d1265b663c551a [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[] = {
168 "/data", "/dev", "/proc", "/sys"
169 };
170 for (size_t i = 0; i < arraysize(kBindMounts); ++i) {
171 std::string trg = StringPrintf("/postinstall%s", kBindMounts[i]);
172 if (mount(kBindMounts[i], trg.c_str(), nullptr, MS_BIND, nullptr) != 0) {
173 PLOG(ERROR) << "Failed to bind-mount " << kBindMounts[i];
174 exit(202);
175 }
176 }
177
Andreas Gampefd12eda2016-07-12 09:47:17 -0700178 // Try to mount the vendor partition. update_engine doesn't do this for us, but we
179 // want it for vendor APKs.
180 // Notes:
181 // 1) We pretty much guess a name here and hope to find the partition by name.
182 // It is just as complicated and brittle to scan /proc/mounts. But this requires
183 // validating the target-slot so as not to try to mount some totally random path.
184 // 2) We're in a mount namespace here, so when we die, this will be cleaned up.
185 // 3) Ignore errors. Printing anything at this stage will open a file descriptor
186 // for logging.
187 if (!ValidateTargetSlotSuffix(arg[2])) {
188 LOG(ERROR) << "Target slot suffix not legal: " << arg[2];
189 exit(207);
190 }
Andreas Gampe54b62c92019-03-21 11:34:19 -0700191 TryExtraMount("vendor", arg[2], "/postinstall/vendor");
Andreas Gampeb87a1c72018-04-13 17:42:23 -0700192
193 // Try to mount the product partition. update_engine doesn't do this for us, but we
194 // want it for product APKs. Same notes as vendor above.
Andreas Gampe54b62c92019-03-21 11:34:19 -0700195 TryExtraMount("product", arg[2], "/postinstall/product");
Andreas Gampefd12eda2016-07-12 09:47:17 -0700196
Alex Light1a4c1da2021-04-15 15:21:17 -0700197 // Try to mount the system_ext partition. update_engine doesn't do this for
198 // us, but we want it for system_ext APKs. Same notes as vendor and product
199 // above.
200 TryExtraMount("system_ext", arg[2], "/postinstall/system_ext");
201
Alex Light2b307a02021-03-03 18:35:47 -0800202 constexpr const char* kPostInstallLinkerconfig = "/postinstall/linkerconfig";
203 // Try to mount /postinstall/linkerconfig. we will set it up after performing the chroot
204 if (mount("tmpfs", kPostInstallLinkerconfig, "tmpfs", 0, nullptr) != 0) {
205 PLOG(ERROR) << "Failed to mount a tmpfs for " << kPostInstallLinkerconfig;
206 exit(215);
207 }
208
Roland Levillainc19c6042018-12-18 12:15:12 +0000209 // Setup APEX mount point and its security context.
210 static constexpr const char* kPostinstallApexDir = "/postinstall/apex";
211 // The following logic is similar to the one in system/core/rootdir/init.rc:
212 //
213 // mount tmpfs tmpfs /apex nodev noexec nosuid
214 // chmod 0755 /apex
215 // chown root root /apex
216 // restorecon /apex
217 //
Roland Levillain8d276812019-01-24 10:51:30 +0000218 // except we perform the `restorecon` step just after mounting the tmpfs
219 // filesystem in /postinstall/apex, so that this directory is correctly
220 // labeled (with type `postinstall_apex_mnt_dir`) and may be manipulated in
221 // following operations (`chmod`, `chown`, etc.) following policies
222 // restricted to `postinstall_apex_mnt_dir`:
223 //
224 // mount tmpfs tmpfs /postinstall/apex nodev noexec nosuid
225 // restorecon /postinstall/apex
226 // chmod 0755 /postinstall/apex
227 // chown root root /postinstall/apex
228 //
Roland Levillainc19c6042018-12-18 12:15:12 +0000229 if (mount("tmpfs", kPostinstallApexDir, "tmpfs", MS_NODEV | MS_NOEXEC | MS_NOSUID, nullptr)
230 != 0) {
231 PLOG(ERROR) << "Failed to mount tmpfs in " << kPostinstallApexDir;
232 exit(209);
233 }
Roland Levillain8d276812019-01-24 10:51:30 +0000234 if (selinux_android_restorecon(kPostinstallApexDir, 0) < 0) {
235 PLOG(ERROR) << "Failed to restorecon " << kPostinstallApexDir;
236 exit(214);
237 }
Roland Levillainc19c6042018-12-18 12:15:12 +0000238 if (chmod(kPostinstallApexDir, 0755) != 0) {
239 PLOG(ERROR) << "Failed to chmod " << kPostinstallApexDir << " to 0755";
240 exit(210);
241 }
242 if (chown(kPostinstallApexDir, 0, 0) != 0) {
243 PLOG(ERROR) << "Failed to chown " << kPostinstallApexDir << " to root:root";
244 exit(211);
245 }
Roland Levillainc19c6042018-12-18 12:15:12 +0000246
Andreas Gampe01ad5982016-03-09 16:27:29 -0800247 // Chdir into /postinstall.
248 if (chdir("/postinstall") != 0) {
249 PLOG(ERROR) << "Unable to chdir into /postinstall.";
250 exit(203);
251 }
252
253 // Make /postinstall the root in our mount namespace.
254 if (chroot(".") != 0) {
255 PLOG(ERROR) << "Failed to chroot";
256 exit(204);
257 }
258
259 if (chdir("/") != 0) {
260 PLOG(ERROR) << "Unable to chdir into /.";
261 exit(205);
262 }
263
Nikita Ioffe2a42aee2021-04-07 16:25:49 +0100264 // Call apexd --unmount-all to free up loop and dm block devices, so that we can re-use
265 // them during the next invocation. Since otapreopt_chroot calls exit in case something goes
266 // wrong we need to register our own atexit handler.
267 // We want to register this handler before actually activating apex packages. This is mostly
268 // due to the fact that if fail to unmount apexes, then on the next run of otapreopt_chroot
269 // we will ask for new loop devices instead of re-using existing ones, and we really don't want
270 // to do that. :)
271 if (atexit(DeactivateApexPackages) != 0) {
272 LOG(ERROR) << "Failed to register atexit hander";
273 exit(206);
274 }
275
Roland Levillainc19c6042018-12-18 12:15:12 +0000276 // Try to mount APEX packages in "/apex" in the chroot dir. We need at least
Martin Stjernholmf4caaa02019-07-17 22:14:14 +0100277 // the ART APEX, as it is required by otapreopt to run dex2oat.
Alex Light53e94382021-03-09 16:39:55 -0800278 ActivateApexPackages();
Roland Levillainc19c6042018-12-18 12:15:12 +0000279
Nikita Ioffe2a42aee2021-04-07 16:25:49 +0100280 auto cleanup = android::base::make_scope_guard([](){
281 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--unmount-all"};
282 std::string apexd_error_msg;
283 bool exec_result = Exec(apexd_cmd, &apexd_error_msg);
284 if (!exec_result) {
285 PLOG(ERROR) << "Running /system/bin/apexd --unmount-all failed: " << apexd_error_msg;
286 }
287 });
Martin Stjernholmf4caaa02019-07-17 22:14:14 +0100288 // Check that an ART APEX has been activated; clean up and exit
Roland Levillain8a8ca152019-07-11 18:48:05 +0100289 // early otherwise.
Alex Light2b307a02021-03-03 18:35:47 -0800290 static constexpr const std::string_view kRequiredApexs[] = {
291 "com.android.art",
292 "com.android.runtime",
Alex Lightfbdc7262021-04-26 16:48:18 -0700293 "com.android.sdkext", // For derive_classpath
Alex Light2b307a02021-03-03 18:35:47 -0800294 };
Alex Light53e94382021-03-09 16:39:55 -0800295 std::array<bool, arraysize(kRequiredApexs)> found_apexs{ false, false };
296 DIR* apex_dir = opendir("/apex");
297 if (apex_dir == nullptr) {
298 PLOG(ERROR) << "unable to open /apex";
299 exit(220);
300 }
301 for (dirent* entry = readdir(apex_dir); entry != nullptr; entry = readdir(apex_dir)) {
302 for (int i = 0; i < found_apexs.size(); i++) {
303 if (kRequiredApexs[i] == std::string_view(entry->d_name)) {
304 found_apexs[i] = true;
305 break;
306 }
Alex Light2b307a02021-03-03 18:35:47 -0800307 }
308 }
Alex Light53e94382021-03-09 16:39:55 -0800309 closedir(apex_dir);
310 auto it = std::find(found_apexs.cbegin(), found_apexs.cend(), false);
311 if (it != found_apexs.cend()) {
312 LOG(ERROR) << "No activated " << kRequiredApexs[std::distance(found_apexs.cbegin(), it)]
313 << " package!";
314 exit(221);
315 }
Alex Light2b307a02021-03-03 18:35:47 -0800316
317 // Setup /linkerconfig. Doing it after the chroot means it doesn't need its own category
318 if (selinux_android_restorecon("/linkerconfig", 0) < 0) {
319 PLOG(ERROR) << "Failed to restorecon /linkerconfig";
320 exit(219);
321 }
322 std::vector<std::string> linkerconfig_cmd{"/apex/com.android.runtime/bin/linkerconfig",
323 "--target", "/linkerconfig"};
324 std::string linkerconfig_error_msg;
325 bool linkerconfig_exec_result = Exec(linkerconfig_cmd, &linkerconfig_error_msg);
326 if (!linkerconfig_exec_result) {
327 LOG(ERROR) << "Running linkerconfig failed: " << linkerconfig_error_msg;
328 exit(218);
Roland Levillain8a8ca152019-07-11 18:48:05 +0100329 }
330
Nikita Ioffe32e49e22021-07-06 17:05:16 +0000331 // Now go on and run otapreopt.
332
333 // Incoming: cmd + status-fd + target-slot + cmd... | Incoming | = argc
334 // Outgoing: cmd + target-slot + cmd... | Outgoing | = argc - 1
335 std::vector<std::string> cmd;
336 cmd.reserve(argc);
337 cmd.push_back("/system/bin/otapreopt");
338
339 // The first parameter is the status file descriptor, skip.
340 for (size_t i = 2; i < static_cast<size_t>(argc); ++i) {
341 cmd.push_back(arg[i]);
Nikita Ioffe97f013c2021-06-29 03:42:56 +0100342 }
343
Nikita Ioffe32e49e22021-07-06 17:05:16 +0000344 // Fork and execute otapreopt in its own process.
345 std::string error_msg;
346 bool exec_result = Exec(cmd, &error_msg);
347 if (!exec_result) {
348 LOG(ERROR) << "Running otapreopt failed: " << error_msg;
349 }
Andreas Gampe01ad5982016-03-09 16:27:29 -0800350
Nikita Ioffe32e49e22021-07-06 17:05:16 +0000351 if (!exec_result) {
352 exit(213);
Roland Levillain94b41802019-01-18 11:56:50 +0000353 }
354
355 return 0;
Andreas Gampe01ad5982016-03-09 16:27:29 -0800356}
357
358} // namespace installd
359} // namespace android
360
361int main(const int argc, char *argv[]) {
362 return android::installd::otapreopt_chroot(argc, argv);
363}