blob: 3a8777616275fd7c9cb76f710df40a54420f5485 [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
Andreas Gamped089ca12016-06-27 14:25:30 -070048static void CloseDescriptor(int fd) {
49 if (fd >= 0) {
50 int result = close(fd);
51 UNUSED(result); // Ignore result. Printing to logcat will open a new descriptor
52 // that we do *not* want.
53 }
54}
55
56static void CloseDescriptor(const char* descriptor_string) {
57 int fd = -1;
58 std::istringstream stream(descriptor_string);
59 stream >> fd;
60 if (!stream.fail()) {
61 CloseDescriptor(fd);
62 }
63}
64
Alex Light53e94382021-03-09 16:39:55 -080065static void ActivateApexPackages() {
66 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--otachroot-bootstrap"};
67 std::string apexd_error_msg;
Roland Levillain6520cca2019-02-01 13:15:58 +000068
Alex Light53e94382021-03-09 16:39:55 -080069 bool exec_result = Exec(apexd_cmd, &apexd_error_msg);
70 if (!exec_result) {
71 PLOG(ERROR) << "Running otapreopt failed: " << apexd_error_msg;
72 exit(220);
Roland Levillain6520cca2019-02-01 13:15:58 +000073 }
74}
75
Nikita Ioffe2a42aee2021-04-07 16:25:49 +010076static void DeactivateApexPackages() {
77 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--unmount-all"};
78 std::string apexd_error_msg;
79 bool exec_result = Exec(apexd_cmd, &apexd_error_msg);
80 if (!exec_result) {
81 PLOG(ERROR) << "Running /system/bin/apexd --unmount-all failed: " << apexd_error_msg;
82 }
83}
84
Andreas Gampe54b62c92019-03-21 11:34:19 -070085static void TryExtraMount(const char* name, const char* slot, const char* target) {
Andreas Gampee90127d2019-03-22 11:21:34 -070086 std::string partition_name = StringPrintf("%s%s", name, slot);
87
88 // See whether update_engine mounted a logical partition.
89 {
90 auto& dm = dm::DeviceMapper::Instance();
91 if (dm.GetState(partition_name) != dm::DmDeviceState::INVALID) {
92 std::string path;
93 if (dm.GetDmDevicePathByName(partition_name, &path)) {
94 int mount_result = mount(path.c_str(),
95 target,
96 "ext4",
97 MS_RDONLY,
98 /* data */ nullptr);
99 if (mount_result == 0) {
100 return;
101 }
102 }
103 }
104 }
105
106 // Fall back and attempt a direct mount.
107 std::string block_device = StringPrintf("/dev/block/by-name/%s", partition_name.c_str());
Andreas Gampe54b62c92019-03-21 11:34:19 -0700108 int mount_result = mount(block_device.c_str(),
109 target,
110 "ext4",
111 MS_RDONLY,
112 /* data */ nullptr);
113 UNUSED(mount_result);
114}
115
Andreas Gamped089ca12016-06-27 14:25:30 -0700116// Entry for otapreopt_chroot. Expected parameters are:
117// [cmd] [status-fd] [target-slot] "dexopt" [dexopt-params]
118// The file descriptor denoted by status-fd will be closed. The rest of the parameters will
119// be passed on to otapreopt in the chroot.
Andreas Gampe01ad5982016-03-09 16:27:29 -0800120static int otapreopt_chroot(const int argc, char **arg) {
Zach Riggle318853a2018-01-18 18:34:04 -0600121 // Validate arguments
122 // We need the command, status channel and target slot, at a minimum.
123 if(argc < 3) {
124 PLOG(ERROR) << "Not enough arguments.";
125 exit(208);
126 }
Andreas Gamped089ca12016-06-27 14:25:30 -0700127 // Close all file descriptors. They are coming from the caller, we do not want to pass them
128 // on across our fork/exec into a different domain.
129 // 1) Default descriptors.
130 CloseDescriptor(STDIN_FILENO);
131 CloseDescriptor(STDOUT_FILENO);
132 CloseDescriptor(STDERR_FILENO);
133 // 2) The status channel.
134 CloseDescriptor(arg[1]);
135
Andreas Gampe01ad5982016-03-09 16:27:29 -0800136 // We need to run the otapreopt tool from the postinstall partition. As such, set up a
137 // mount namespace and change root.
138
139 // Create our own mount namespace.
140 if (unshare(CLONE_NEWNS) != 0) {
141 PLOG(ERROR) << "Failed to unshare() for otapreopt.";
142 exit(200);
143 }
144
145 // Make postinstall private, so that our changes don't propagate.
146 if (mount("", "/postinstall", nullptr, MS_PRIVATE, nullptr) != 0) {
147 PLOG(ERROR) << "Failed to mount private.";
148 exit(201);
149 }
150
151 // Bind mount necessary directories.
152 constexpr const char* kBindMounts[] = {
153 "/data", "/dev", "/proc", "/sys"
154 };
155 for (size_t i = 0; i < arraysize(kBindMounts); ++i) {
156 std::string trg = StringPrintf("/postinstall%s", kBindMounts[i]);
157 if (mount(kBindMounts[i], trg.c_str(), nullptr, MS_BIND, nullptr) != 0) {
158 PLOG(ERROR) << "Failed to bind-mount " << kBindMounts[i];
159 exit(202);
160 }
161 }
162
Andreas Gampefd12eda2016-07-12 09:47:17 -0700163 // Try to mount the vendor partition. update_engine doesn't do this for us, but we
164 // want it for vendor APKs.
165 // Notes:
166 // 1) We pretty much guess a name here and hope to find the partition by name.
167 // It is just as complicated and brittle to scan /proc/mounts. But this requires
168 // validating the target-slot so as not to try to mount some totally random path.
169 // 2) We're in a mount namespace here, so when we die, this will be cleaned up.
170 // 3) Ignore errors. Printing anything at this stage will open a file descriptor
171 // for logging.
172 if (!ValidateTargetSlotSuffix(arg[2])) {
173 LOG(ERROR) << "Target slot suffix not legal: " << arg[2];
174 exit(207);
175 }
Andreas Gampe54b62c92019-03-21 11:34:19 -0700176 TryExtraMount("vendor", arg[2], "/postinstall/vendor");
Andreas Gampeb87a1c72018-04-13 17:42:23 -0700177
178 // Try to mount the product partition. update_engine doesn't do this for us, but we
179 // want it for product APKs. Same notes as vendor above.
Andreas Gampe54b62c92019-03-21 11:34:19 -0700180 TryExtraMount("product", arg[2], "/postinstall/product");
Andreas Gampefd12eda2016-07-12 09:47:17 -0700181
Alex Light2b307a02021-03-03 18:35:47 -0800182 constexpr const char* kPostInstallLinkerconfig = "/postinstall/linkerconfig";
183 // Try to mount /postinstall/linkerconfig. we will set it up after performing the chroot
184 if (mount("tmpfs", kPostInstallLinkerconfig, "tmpfs", 0, nullptr) != 0) {
185 PLOG(ERROR) << "Failed to mount a tmpfs for " << kPostInstallLinkerconfig;
186 exit(215);
187 }
188
Roland Levillainc19c6042018-12-18 12:15:12 +0000189 // Setup APEX mount point and its security context.
190 static constexpr const char* kPostinstallApexDir = "/postinstall/apex";
191 // The following logic is similar to the one in system/core/rootdir/init.rc:
192 //
193 // mount tmpfs tmpfs /apex nodev noexec nosuid
194 // chmod 0755 /apex
195 // chown root root /apex
196 // restorecon /apex
197 //
Roland Levillain8d276812019-01-24 10:51:30 +0000198 // except we perform the `restorecon` step just after mounting the tmpfs
199 // filesystem in /postinstall/apex, so that this directory is correctly
200 // labeled (with type `postinstall_apex_mnt_dir`) and may be manipulated in
201 // following operations (`chmod`, `chown`, etc.) following policies
202 // restricted to `postinstall_apex_mnt_dir`:
203 //
204 // mount tmpfs tmpfs /postinstall/apex nodev noexec nosuid
205 // restorecon /postinstall/apex
206 // chmod 0755 /postinstall/apex
207 // chown root root /postinstall/apex
208 //
Roland Levillainc19c6042018-12-18 12:15:12 +0000209 if (mount("tmpfs", kPostinstallApexDir, "tmpfs", MS_NODEV | MS_NOEXEC | MS_NOSUID, nullptr)
210 != 0) {
211 PLOG(ERROR) << "Failed to mount tmpfs in " << kPostinstallApexDir;
212 exit(209);
213 }
Roland Levillain8d276812019-01-24 10:51:30 +0000214 if (selinux_android_restorecon(kPostinstallApexDir, 0) < 0) {
215 PLOG(ERROR) << "Failed to restorecon " << kPostinstallApexDir;
216 exit(214);
217 }
Roland Levillainc19c6042018-12-18 12:15:12 +0000218 if (chmod(kPostinstallApexDir, 0755) != 0) {
219 PLOG(ERROR) << "Failed to chmod " << kPostinstallApexDir << " to 0755";
220 exit(210);
221 }
222 if (chown(kPostinstallApexDir, 0, 0) != 0) {
223 PLOG(ERROR) << "Failed to chown " << kPostinstallApexDir << " to root:root";
224 exit(211);
225 }
Roland Levillainc19c6042018-12-18 12:15:12 +0000226
Andreas Gampe01ad5982016-03-09 16:27:29 -0800227 // Chdir into /postinstall.
228 if (chdir("/postinstall") != 0) {
229 PLOG(ERROR) << "Unable to chdir into /postinstall.";
230 exit(203);
231 }
232
233 // Make /postinstall the root in our mount namespace.
234 if (chroot(".") != 0) {
235 PLOG(ERROR) << "Failed to chroot";
236 exit(204);
237 }
238
239 if (chdir("/") != 0) {
240 PLOG(ERROR) << "Unable to chdir into /.";
241 exit(205);
242 }
243
Nikita Ioffe2a42aee2021-04-07 16:25:49 +0100244 // Call apexd --unmount-all to free up loop and dm block devices, so that we can re-use
245 // them during the next invocation. Since otapreopt_chroot calls exit in case something goes
246 // wrong we need to register our own atexit handler.
247 // We want to register this handler before actually activating apex packages. This is mostly
248 // due to the fact that if fail to unmount apexes, then on the next run of otapreopt_chroot
249 // we will ask for new loop devices instead of re-using existing ones, and we really don't want
250 // to do that. :)
251 if (atexit(DeactivateApexPackages) != 0) {
252 LOG(ERROR) << "Failed to register atexit hander";
253 exit(206);
254 }
255
Roland Levillainc19c6042018-12-18 12:15:12 +0000256 // Try to mount APEX packages in "/apex" in the chroot dir. We need at least
Martin Stjernholmf4caaa02019-07-17 22:14:14 +0100257 // the ART APEX, as it is required by otapreopt to run dex2oat.
Alex Light53e94382021-03-09 16:39:55 -0800258 ActivateApexPackages();
Roland Levillainc19c6042018-12-18 12:15:12 +0000259
Nikita Ioffe2a42aee2021-04-07 16:25:49 +0100260 auto cleanup = android::base::make_scope_guard([](){
261 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--unmount-all"};
262 std::string apexd_error_msg;
263 bool exec_result = Exec(apexd_cmd, &apexd_error_msg);
264 if (!exec_result) {
265 PLOG(ERROR) << "Running /system/bin/apexd --unmount-all failed: " << apexd_error_msg;
266 }
267 });
Martin Stjernholmf4caaa02019-07-17 22:14:14 +0100268 // Check that an ART APEX has been activated; clean up and exit
Roland Levillain8a8ca152019-07-11 18:48:05 +0100269 // early otherwise.
Alex Light2b307a02021-03-03 18:35:47 -0800270 static constexpr const std::string_view kRequiredApexs[] = {
271 "com.android.art",
272 "com.android.runtime",
273 };
Alex Light53e94382021-03-09 16:39:55 -0800274 std::array<bool, arraysize(kRequiredApexs)> found_apexs{ false, false };
275 DIR* apex_dir = opendir("/apex");
276 if (apex_dir == nullptr) {
277 PLOG(ERROR) << "unable to open /apex";
278 exit(220);
279 }
280 for (dirent* entry = readdir(apex_dir); entry != nullptr; entry = readdir(apex_dir)) {
281 for (int i = 0; i < found_apexs.size(); i++) {
282 if (kRequiredApexs[i] == std::string_view(entry->d_name)) {
283 found_apexs[i] = true;
284 break;
285 }
Alex Light2b307a02021-03-03 18:35:47 -0800286 }
287 }
Alex Light53e94382021-03-09 16:39:55 -0800288 closedir(apex_dir);
289 auto it = std::find(found_apexs.cbegin(), found_apexs.cend(), false);
290 if (it != found_apexs.cend()) {
291 LOG(ERROR) << "No activated " << kRequiredApexs[std::distance(found_apexs.cbegin(), it)]
292 << " package!";
293 exit(221);
294 }
Alex Light2b307a02021-03-03 18:35:47 -0800295
296 // Setup /linkerconfig. Doing it after the chroot means it doesn't need its own category
297 if (selinux_android_restorecon("/linkerconfig", 0) < 0) {
298 PLOG(ERROR) << "Failed to restorecon /linkerconfig";
299 exit(219);
300 }
301 std::vector<std::string> linkerconfig_cmd{"/apex/com.android.runtime/bin/linkerconfig",
302 "--target", "/linkerconfig"};
303 std::string linkerconfig_error_msg;
304 bool linkerconfig_exec_result = Exec(linkerconfig_cmd, &linkerconfig_error_msg);
305 if (!linkerconfig_exec_result) {
306 LOG(ERROR) << "Running linkerconfig failed: " << linkerconfig_error_msg;
307 exit(218);
Roland Levillain8a8ca152019-07-11 18:48:05 +0100308 }
309
Andreas Gampe01ad5982016-03-09 16:27:29 -0800310 // Now go on and run otapreopt.
311
Roland Levillain94b41802019-01-18 11:56:50 +0000312 // Incoming: cmd + status-fd + target-slot + cmd... | Incoming | = argc
313 // Outgoing: cmd + target-slot + cmd... | Outgoing | = argc - 1
314 std::vector<std::string> cmd;
315 cmd.reserve(argc);
316 cmd.push_back("/system/bin/otapreopt");
Andreas Gamped089ca12016-06-27 14:25:30 -0700317
318 // The first parameter is the status file descriptor, skip.
Roland Levillain94b41802019-01-18 11:56:50 +0000319 for (size_t i = 2; i < static_cast<size_t>(argc); ++i) {
320 cmd.push_back(arg[i]);
Andreas Gamped089ca12016-06-27 14:25:30 -0700321 }
Andreas Gampe01ad5982016-03-09 16:27:29 -0800322
Roland Levillain94b41802019-01-18 11:56:50 +0000323 // Fork and execute otapreopt in its own process.
324 std::string error_msg;
325 bool exec_result = Exec(cmd, &error_msg);
326 if (!exec_result) {
327 LOG(ERROR) << "Running otapreopt failed: " << error_msg;
328 }
329
Roland Levillain94b41802019-01-18 11:56:50 +0000330 if (!exec_result) {
331 exit(213);
332 }
333
334 return 0;
Andreas Gampe01ad5982016-03-09 16:27:29 -0800335}
336
337} // namespace installd
338} // namespace android
339
340int main(const int argc, char *argv[]) {
341 return android::installd::otapreopt_chroot(argc, argv);
342}