1 /*
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
17 #include <fcntl.h>
18 #include <linux/unistd.h>
19 #include <sched.h>
20 #include <sys/mount.h>
21 #include <sys/stat.h>
22 #include <sys/wait.h>
23 #include <unistd.h>
24
25 #include <algorithm>
26 #include <array>
27 #include <fstream>
28 #include <iostream>
29 #include <sstream>
30
31 #include <android-base/file.h>
32 #include <android-base/logging.h>
33 #include <android-base/macros.h>
34 #include <android-base/scopeguard.h>
35 #include <android-base/stringprintf.h>
36 #include <android-base/strings.h>
37 #include <android-base/unique_fd.h>
38 #include <libdm/dm.h>
39 #include <selinux/android.h>
40
41 #include "installd_constants.h"
42 #include "otapreopt_utils.h"
43
44 #ifndef LOG_TAG
45 #define LOG_TAG "otapreopt_chroot"
46 #endif
47
48 using android::base::StringPrintf;
49
50 namespace android {
51 namespace installd {
52
53 // We don't know the filesystem types of the partitions in the update package,
54 // so just try the possibilities one by one.
55 static constexpr std::array kTryMountFsTypes = {"ext4", "erofs"};
56
CloseDescriptor(const char * descriptor_string)57 static void CloseDescriptor(const char* descriptor_string) {
58 int fd = -1;
59 std::istringstream stream(descriptor_string);
60 stream >> fd;
61 if (!stream.fail()) {
62 if (fd >= 0) {
63 if (close(fd) < 0) {
64 PLOG(ERROR) << "Failed to close " << fd;
65 }
66 }
67 }
68 }
69
SetCloseOnExec(int fd)70 static void SetCloseOnExec(int fd) {
71 if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
72 PLOG(ERROR) << "Failed to set FD_CLOEXEC on " << fd;
73 }
74 }
75
ActivateApexPackages()76 static void ActivateApexPackages() {
77 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--otachroot-bootstrap"};
78 std::string apexd_error_msg;
79
80 bool exec_result = Exec(apexd_cmd, &apexd_error_msg);
81 if (!exec_result) {
82 PLOG(ERROR) << "Running otapreopt failed: " << apexd_error_msg;
83 exit(220);
84 }
85 }
86
DeactivateApexPackages()87 static void DeactivateApexPackages() {
88 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--unmount-all"};
89 std::string apexd_error_msg;
90 bool exec_result = Exec(apexd_cmd, &apexd_error_msg);
91 if (!exec_result) {
92 PLOG(ERROR) << "Running /system/bin/apexd --unmount-all failed: " << apexd_error_msg;
93 }
94 }
95
TryMountWithFstypes(const char * block_device,const char * target)96 static bool TryMountWithFstypes(const char* block_device, const char* target) {
97 for (int i = 0; i < kTryMountFsTypes.size(); ++i) {
98 const char* fstype = kTryMountFsTypes[i];
99 int mount_result = mount(block_device, target, fstype, MS_RDONLY, /* data */ nullptr);
100 if (mount_result == 0) {
101 return true;
102 }
103 if (errno == EINVAL && i < kTryMountFsTypes.size() - 1) {
104 // Only try the next fstype if mounting failed due to the current one
105 // being invalid.
106 LOG(WARNING) << "Failed to mount " << block_device << " on " << target << " with "
107 << fstype << " - trying " << kTryMountFsTypes[i + 1];
108 } else {
109 PLOG(ERROR) << "Failed to mount " << block_device << " on " << target << " with "
110 << fstype;
111 return false;
112 }
113 }
114 __builtin_unreachable();
115 }
116
TryExtraMount(const char * name,const char * slot,const char * target)117 static void TryExtraMount(const char* name, const char* slot, const char* target) {
118 std::string partition_name = StringPrintf("%s%s", name, slot);
119
120 // See whether update_engine mounted a logical partition.
121 {
122 auto& dm = dm::DeviceMapper::Instance();
123 if (dm.GetState(partition_name) != dm::DmDeviceState::INVALID) {
124 std::string path;
125 if (dm.GetDmDevicePathByName(partition_name, &path)) {
126 if (TryMountWithFstypes(path.c_str(), target)) {
127 return;
128 }
129 }
130 }
131 }
132
133 // Fall back and attempt a direct mount.
134 std::string block_device = StringPrintf("/dev/block/by-name/%s", partition_name.c_str());
135 (void)TryMountWithFstypes(block_device.c_str(), target);
136 }
137
138 // Entry for otapreopt_chroot. Expected parameters are:
139 //
140 // [cmd] [status-fd] [target-slot-suffix]
141 //
142 // The file descriptor denoted by status-fd will be closed. Dexopt commands on
143 // the form
144 //
145 // "dexopt" [dexopt-params]
146 //
147 // are then read from stdin until EOF and passed on to /system/bin/otapreopt one
148 // by one. After each call a line with the current command count is written to
149 // stdout and flushed.
otapreopt_chroot(const int argc,char ** arg)150 static int otapreopt_chroot(const int argc, char **arg) {
151 // Validate arguments
152 if (argc == 2 && std::string_view(arg[1]) == "--version") {
153 // Accept a single --version flag, to allow the script to tell this binary
154 // from the earlier one.
155 std::cout << "2" << std::endl;
156 return 0;
157 }
158 if (argc != 3) {
159 LOG(ERROR) << "Wrong number of arguments: " << argc;
160 exit(208);
161 }
162 const char* status_fd = arg[1];
163 const char* slot_suffix = arg[2];
164
165 // Set O_CLOEXEC on standard fds. They are coming from the caller, we do not
166 // want to pass them on across our fork/exec into a different domain.
167 SetCloseOnExec(STDIN_FILENO);
168 SetCloseOnExec(STDOUT_FILENO);
169 SetCloseOnExec(STDERR_FILENO);
170 // Close the status channel.
171 CloseDescriptor(status_fd);
172
173 // We need to run the otapreopt tool from the postinstall partition. As such, set up a
174 // mount namespace and change root.
175
176 // Create our own mount namespace.
177 if (unshare(CLONE_NEWNS) != 0) {
178 PLOG(ERROR) << "Failed to unshare() for otapreopt.";
179 exit(200);
180 }
181
182 // Make postinstall private, so that our changes don't propagate.
183 if (mount("", "/postinstall", nullptr, MS_PRIVATE, nullptr) != 0) {
184 PLOG(ERROR) << "Failed to mount private.";
185 exit(201);
186 }
187
188 // Bind mount necessary directories.
189 constexpr const char* kBindMounts[] = {
190 "/data", "/dev", "/proc", "/sys",
191 "/sys/fs/selinux" /* Required for apexd which includes libselinux */
192 };
193 for (size_t i = 0; i < arraysize(kBindMounts); ++i) {
194 std::string trg = StringPrintf("/postinstall%s", kBindMounts[i]);
195 if (mount(kBindMounts[i], trg.c_str(), nullptr, MS_BIND, nullptr) != 0) {
196 PLOG(ERROR) << "Failed to bind-mount " << kBindMounts[i];
197 exit(202);
198 }
199 }
200
201 // Try to mount the vendor partition. update_engine doesn't do this for us, but we
202 // want it for vendor APKs.
203 // Notes:
204 // 1) We pretty much guess a name here and hope to find the partition by name.
205 // It is just as complicated and brittle to scan /proc/mounts. But this requires
206 // validating the target-slot so as not to try to mount some totally random path.
207 // 2) We're in a mount namespace here, so when we die, this will be cleaned up.
208 // 3) Ignore errors. Printing anything at this stage will open a file descriptor
209 // for logging.
210 if (!ValidateTargetSlotSuffix(slot_suffix)) {
211 LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
212 exit(207);
213 }
214 TryExtraMount("vendor", slot_suffix, "/postinstall/vendor");
215
216 // Try to mount the product partition. update_engine doesn't do this for us, but we
217 // want it for product APKs. Same notes as vendor above.
218 TryExtraMount("product", slot_suffix, "/postinstall/product");
219
220 // Try to mount the system_ext partition. update_engine doesn't do this for
221 // us, but we want it for system_ext APKs. Same notes as vendor and product
222 // above.
223 TryExtraMount("system_ext", slot_suffix, "/postinstall/system_ext");
224
225 constexpr const char* kPostInstallLinkerconfig = "/postinstall/linkerconfig";
226 // Try to mount /postinstall/linkerconfig. we will set it up after performing the chroot
227 if (mount("tmpfs", kPostInstallLinkerconfig, "tmpfs", 0, nullptr) != 0) {
228 PLOG(ERROR) << "Failed to mount a tmpfs for " << kPostInstallLinkerconfig;
229 exit(215);
230 }
231
232 // Setup APEX mount point and its security context.
233 static constexpr const char* kPostinstallApexDir = "/postinstall/apex";
234 // The following logic is similar to the one in system/core/rootdir/init.rc:
235 //
236 // mount tmpfs tmpfs /apex nodev noexec nosuid
237 // chmod 0755 /apex
238 // chown root root /apex
239 // restorecon /apex
240 //
241 // except we perform the `restorecon` step just after mounting the tmpfs
242 // filesystem in /postinstall/apex, so that this directory is correctly
243 // labeled (with type `postinstall_apex_mnt_dir`) and may be manipulated in
244 // following operations (`chmod`, `chown`, etc.) following policies
245 // restricted to `postinstall_apex_mnt_dir`:
246 //
247 // mount tmpfs tmpfs /postinstall/apex nodev noexec nosuid
248 // restorecon /postinstall/apex
249 // chmod 0755 /postinstall/apex
250 // chown root root /postinstall/apex
251 //
252 if (mount("tmpfs", kPostinstallApexDir, "tmpfs", MS_NODEV | MS_NOEXEC | MS_NOSUID, nullptr)
253 != 0) {
254 PLOG(ERROR) << "Failed to mount tmpfs in " << kPostinstallApexDir;
255 exit(209);
256 }
257 if (selinux_android_restorecon(kPostinstallApexDir, 0) < 0) {
258 PLOG(ERROR) << "Failed to restorecon " << kPostinstallApexDir;
259 exit(214);
260 }
261 if (chmod(kPostinstallApexDir, 0755) != 0) {
262 PLOG(ERROR) << "Failed to chmod " << kPostinstallApexDir << " to 0755";
263 exit(210);
264 }
265 if (chown(kPostinstallApexDir, 0, 0) != 0) {
266 PLOG(ERROR) << "Failed to chown " << kPostinstallApexDir << " to root:root";
267 exit(211);
268 }
269
270 // Chdir into /postinstall.
271 if (chdir("/postinstall") != 0) {
272 PLOG(ERROR) << "Unable to chdir into /postinstall.";
273 exit(203);
274 }
275
276 // Make /postinstall the root in our mount namespace.
277 if (chroot(".") != 0) {
278 PLOG(ERROR) << "Failed to chroot";
279 exit(204);
280 }
281
282 if (chdir("/") != 0) {
283 PLOG(ERROR) << "Unable to chdir into /.";
284 exit(205);
285 }
286
287 // Call apexd --unmount-all to free up loop and dm block devices, so that we can re-use
288 // them during the next invocation. Since otapreopt_chroot calls exit in case something goes
289 // wrong we need to register our own atexit handler.
290 // We want to register this handler before actually activating apex packages. This is mostly
291 // due to the fact that if fail to unmount apexes, then on the next run of otapreopt_chroot
292 // we will ask for new loop devices instead of re-using existing ones, and we really don't want
293 // to do that. :)
294 if (atexit(DeactivateApexPackages) != 0) {
295 LOG(ERROR) << "Failed to register atexit hander";
296 exit(206);
297 }
298
299 // Try to mount APEX packages in "/apex" in the chroot dir. We need at least
300 // the ART APEX, as it is required by otapreopt to run dex2oat.
301 ActivateApexPackages();
302
303 auto cleanup = android::base::make_scope_guard([](){
304 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--unmount-all"};
305 std::string apexd_error_msg;
306 bool exec_result = Exec(apexd_cmd, &apexd_error_msg);
307 if (!exec_result) {
308 PLOG(ERROR) << "Running /system/bin/apexd --unmount-all failed: " << apexd_error_msg;
309 }
310 });
311 // Check that an ART APEX has been activated; clean up and exit
312 // early otherwise.
313 static constexpr const std::string_view kRequiredApexs[] = {
314 "com.android.art",
315 "com.android.runtime",
316 "com.android.sdkext", // For derive_classpath
317 };
318 std::array<bool, arraysize(kRequiredApexs)> found_apexs{ false, false };
319 DIR* apex_dir = opendir("/apex");
320 if (apex_dir == nullptr) {
321 PLOG(ERROR) << "unable to open /apex";
322 exit(220);
323 }
324 for (dirent* entry = readdir(apex_dir); entry != nullptr; entry = readdir(apex_dir)) {
325 for (int i = 0; i < found_apexs.size(); i++) {
326 if (kRequiredApexs[i] == std::string_view(entry->d_name)) {
327 found_apexs[i] = true;
328 break;
329 }
330 }
331 }
332 closedir(apex_dir);
333 auto it = std::find(found_apexs.cbegin(), found_apexs.cend(), false);
334 if (it != found_apexs.cend()) {
335 LOG(ERROR) << "No activated " << kRequiredApexs[std::distance(found_apexs.cbegin(), it)]
336 << " package!";
337 exit(221);
338 }
339
340 // Setup /linkerconfig. Doing it after the chroot means it doesn't need its own category
341 if (selinux_android_restorecon("/linkerconfig", 0) < 0) {
342 PLOG(ERROR) << "Failed to restorecon /linkerconfig";
343 exit(219);
344 }
345 std::vector<std::string> linkerconfig_cmd{"/apex/com.android.runtime/bin/linkerconfig",
346 "--target", "/linkerconfig"};
347 std::string linkerconfig_error_msg;
348 bool linkerconfig_exec_result = Exec(linkerconfig_cmd, &linkerconfig_error_msg);
349 if (!linkerconfig_exec_result) {
350 LOG(ERROR) << "Running linkerconfig failed: " << linkerconfig_error_msg;
351 exit(218);
352 }
353
354 // Now go on and read dexopt lines from stdin and pass them on to otapreopt.
355
356 int count = 1;
357 for (std::array<char, 10000> linebuf;
358 std::cin.clear(), std::cin.getline(&linebuf[0], linebuf.size()); ++count) {
359 // Subtract one from gcount() since getline() counts the newline.
360 std::string line(&linebuf[0], std::cin.gcount() - 1);
361
362 if (std::cin.fail()) {
363 LOG(ERROR) << "Command exceeds max length " << linebuf.size() << " - skipped: " << line;
364 continue;
365 }
366
367 std::vector<std::string> tokenized_line = android::base::Tokenize(line, " ");
368 std::vector<std::string> cmd{"/system/bin/otapreopt", slot_suffix};
369 std::move(tokenized_line.begin(), tokenized_line.end(), std::back_inserter(cmd));
370
371 LOG(INFO) << "Command " << count << ": " << android::base::Join(cmd, " ");
372
373 // Fork and execute otapreopt in its own process.
374 std::string error_msg;
375 bool exec_result = Exec(cmd, &error_msg);
376 if (!exec_result) {
377 LOG(ERROR) << "Running otapreopt failed: " << error_msg;
378 }
379
380 // Print the count to stdout and flush to indicate progress.
381 std::cout << count << std::endl;
382 }
383
384 LOG(INFO) << "No more dexopt commands";
385 return 0;
386 }
387
388 } // namespace installd
389 } // namespace android
390
main(const int argc,char * argv[])391 int main(const int argc, char *argv[]) {
392 return android::installd::otapreopt_chroot(argc, argv);
393 }
394