• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <sys/mount.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
22 #include <unistd.h>
23 
24 #include <algorithm>
25 #include <array>
26 #include <fstream>
27 #include <iostream>
28 #include <sstream>
29 
30 #include <android-base/file.h>
31 #include <android-base/logging.h>
32 #include <android-base/macros.h>
33 #include <android-base/scopeguard.h>
34 #include <android-base/stringprintf.h>
35 #include <android-base/strings.h>
36 #include <android-base/unique_fd.h>
37 #include <libdm/dm.h>
38 #include <selinux/android.h>
39 
40 #include "installd_constants.h"
41 #include "otapreopt_utils.h"
42 
43 #ifndef LOG_TAG
44 #define LOG_TAG "otapreopt_chroot"
45 #endif
46 
47 using android::base::StringPrintf;
48 
49 namespace android {
50 namespace installd {
51 
52 // We don't know the filesystem types of the partitions in the update package,
53 // so just try the possibilities one by one.
54 static constexpr std::array kTryMountFsTypes = {"ext4", "erofs"};
55 
CloseDescriptor(const char * descriptor_string)56 static void CloseDescriptor(const char* descriptor_string) {
57     int fd = -1;
58     std::istringstream stream(descriptor_string);
59     stream >> fd;
60     if (!stream.fail()) {
61         if (fd >= 0) {
62             if (close(fd) < 0) {
63                 PLOG(ERROR) << "Failed to close " << fd;
64             }
65         }
66     }
67 }
68 
SetCloseOnExec(int fd)69 static void SetCloseOnExec(int fd) {
70     if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
71         PLOG(ERROR) << "Failed to set FD_CLOEXEC on " << fd;
72     }
73 }
74 
ActivateApexPackages()75 static void ActivateApexPackages() {
76     std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--otachroot-bootstrap"};
77     std::string apexd_error_msg;
78 
79     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);
83     }
84 }
85 
DeactivateApexPackages()86 static 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 
TryMountWithFstypes(const char * block_device,const char * target)95 static 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 
TryExtraMount(const char * name,const char * slot,const char * target)116 static void TryExtraMount(const char* name, const char* slot, const char* target) {
117     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)) {
125                 if (TryMountWithFstypes(path.c_str(), target)) {
126                     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());
134     (void)TryMountWithFstypes(block_device.c_str(), target);
135 }
136 
137 // Entry for otapreopt_chroot. Expected parameters are:
138 //
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.
otapreopt_chroot(const int argc,char ** arg)149 static int otapreopt_chroot(const int argc, char **arg) {
150     // Validate arguments
151     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;
159         exit(208);
160     }
161     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);
171 
172     // 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[] = {
189             "/data", "/dev", "/proc", "/sys",
190             "/sys/fs/selinux" /* Required for apexd which includes libselinux */
191     };
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 
200     // 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.
209     if (!ValidateTargetSlotSuffix(slot_suffix)) {
210         LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
211         exit(207);
212     }
213     TryExtraMount("vendor", slot_suffix, "/postinstall/vendor");
214 
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.
217     TryExtraMount("product", slot_suffix, "/postinstall/product");
218 
219     // 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.
222     TryExtraMount("system_ext", slot_suffix, "/postinstall/system_ext");
223 
224     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 
231     // 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     //
240     // 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     //
251     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     }
256     if (selinux_android_restorecon(kPostinstallApexDir, 0) < 0) {
257         PLOG(ERROR) << "Failed to restorecon " << kPostinstallApexDir;
258         exit(214);
259     }
260     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     }
268 
269     // 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 
286     // 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 
298     // Try to mount APEX packages in "/apex" in the chroot dir. We need at least
299     // the ART APEX, as it is required by otapreopt to run dex2oat.
300     ActivateApexPackages();
301 
302     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     });
310     // Check that an ART APEX has been activated; clean up and exit
311     // early otherwise.
312     static constexpr const std::string_view kRequiredApexs[] = {
313       "com.android.art",
314       "com.android.runtime",
315       "com.android.sdkext",  // For derive_classpath
316     };
317     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             }
329         }
330     }
331     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     }
338 
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);
351     }
352 
353     // Now go on and read dexopt lines from stdin and pass them on to otapreopt.
354 
355     int count = 1;
356     for (std::array<char, 1000> linebuf;
357          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);
360 
361         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;
381     }
382 
383     LOG(INFO) << "No more dexopt commands";
384     return 0;
385 }
386 
387 }  // namespace installd
388 }  // namespace android
389 
main(const int argc,char * argv[])390 int main(const int argc, char *argv[]) {
391     return android::installd::otapreopt_chroot(argc, argv);
392 }
393