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 
23 #include <sstream>
24 
25 #include <android-base/logging.h>
26 #include <android-base/macros.h>
27 #include <android-base/stringprintf.h>
28 #include <libdm/dm.h>
29 #include <selinux/android.h>
30 
31 #include <apexd.h>
32 
33 #include "installd_constants.h"
34 #include "otapreopt_utils.h"
35 
36 #ifndef LOG_TAG
37 #define LOG_TAG "otapreopt"
38 #endif
39 
40 using android::base::StringPrintf;
41 
42 namespace android {
43 namespace installd {
44 
CloseDescriptor(int fd)45 static void CloseDescriptor(int fd) {
46     if (fd >= 0) {
47         int result = close(fd);
48         UNUSED(result);  // Ignore result. Printing to logcat will open a new descriptor
49                          // that we do *not* want.
50     }
51 }
52 
CloseDescriptor(const char * descriptor_string)53 static void CloseDescriptor(const char* descriptor_string) {
54     int fd = -1;
55     std::istringstream stream(descriptor_string);
56     stream >> fd;
57     if (!stream.fail()) {
58         CloseDescriptor(fd);
59     }
60 }
61 
ActivateApexPackages()62 static std::vector<apex::ApexFile> ActivateApexPackages() {
63     // The logic here is (partially) copied and adapted from
64     // system/apex/apexd/apexd.cpp.
65     //
66     // Only scan the APEX directory under /system, /system_ext and /vendor (within the chroot dir).
67     std::vector<const char*> apex_dirs{apex::kApexPackageSystemDir, apex::kApexPackageSystemExtDir,
68                                        apex::kApexPackageVendorDir};
69     for (const auto& dir : apex_dirs) {
70         // Cast call to void to suppress warn_unused_result.
71         static_cast<void>(apex::scanPackagesDirAndActivate(dir));
72     }
73     return apex::getActivePackages();
74 }
75 
DeactivateApexPackages(const std::vector<apex::ApexFile> & active_packages)76 static void DeactivateApexPackages(const std::vector<apex::ApexFile>& active_packages) {
77     for (const apex::ApexFile& apex_file : active_packages) {
78         const std::string& package_path = apex_file.GetPath();
79         base::Result<void> status = apex::deactivatePackage(package_path);
80         if (!status.ok()) {
81             LOG(ERROR) << "Failed to deactivate " << package_path << ": "
82                        << status.error();
83         }
84     }
85 }
86 
TryExtraMount(const char * name,const char * slot,const char * target)87 static void TryExtraMount(const char* name, const char* slot, const char* target) {
88     std::string partition_name = StringPrintf("%s%s", name, slot);
89 
90     // See whether update_engine mounted a logical partition.
91     {
92         auto& dm = dm::DeviceMapper::Instance();
93         if (dm.GetState(partition_name) != dm::DmDeviceState::INVALID) {
94             std::string path;
95             if (dm.GetDmDevicePathByName(partition_name, &path)) {
96                 int mount_result = mount(path.c_str(),
97                                          target,
98                                          "ext4",
99                                          MS_RDONLY,
100                                          /* data */ nullptr);
101                 if (mount_result == 0) {
102                     return;
103                 }
104             }
105         }
106     }
107 
108     // Fall back and attempt a direct mount.
109     std::string block_device = StringPrintf("/dev/block/by-name/%s", partition_name.c_str());
110     int mount_result = mount(block_device.c_str(),
111                              target,
112                              "ext4",
113                              MS_RDONLY,
114                              /* data */ nullptr);
115     UNUSED(mount_result);
116 }
117 
118 // Entry for otapreopt_chroot. Expected parameters are:
119 //   [cmd] [status-fd] [target-slot] "dexopt" [dexopt-params]
120 // The file descriptor denoted by status-fd will be closed. The rest of the parameters will
121 // be passed on to otapreopt in the chroot.
otapreopt_chroot(const int argc,char ** arg)122 static int otapreopt_chroot(const int argc, char **arg) {
123     // Validate arguments
124     // We need the command, status channel and target slot, at a minimum.
125     if(argc < 3) {
126         PLOG(ERROR) << "Not enough arguments.";
127         exit(208);
128     }
129     // Close all file descriptors. They are coming from the caller, we do not want to pass them
130     // on across our fork/exec into a different domain.
131     // 1) Default descriptors.
132     CloseDescriptor(STDIN_FILENO);
133     CloseDescriptor(STDOUT_FILENO);
134     CloseDescriptor(STDERR_FILENO);
135     // 2) The status channel.
136     CloseDescriptor(arg[1]);
137 
138     // We need to run the otapreopt tool from the postinstall partition. As such, set up a
139     // mount namespace and change root.
140 
141     // Create our own mount namespace.
142     if (unshare(CLONE_NEWNS) != 0) {
143         PLOG(ERROR) << "Failed to unshare() for otapreopt.";
144         exit(200);
145     }
146 
147     // Make postinstall private, so that our changes don't propagate.
148     if (mount("", "/postinstall", nullptr, MS_PRIVATE, nullptr) != 0) {
149         PLOG(ERROR) << "Failed to mount private.";
150         exit(201);
151     }
152 
153     // Bind mount necessary directories.
154     constexpr const char* kBindMounts[] = {
155             "/data", "/dev", "/proc", "/sys"
156     };
157     for (size_t i = 0; i < arraysize(kBindMounts); ++i) {
158         std::string trg = StringPrintf("/postinstall%s", kBindMounts[i]);
159         if (mount(kBindMounts[i], trg.c_str(), nullptr, MS_BIND, nullptr) != 0) {
160             PLOG(ERROR) << "Failed to bind-mount " << kBindMounts[i];
161             exit(202);
162         }
163     }
164 
165     // Try to mount the vendor partition. update_engine doesn't do this for us, but we
166     // want it for vendor APKs.
167     // Notes:
168     //  1) We pretty much guess a name here and hope to find the partition by name.
169     //     It is just as complicated and brittle to scan /proc/mounts. But this requires
170     //     validating the target-slot so as not to try to mount some totally random path.
171     //  2) We're in a mount namespace here, so when we die, this will be cleaned up.
172     //  3) Ignore errors. Printing anything at this stage will open a file descriptor
173     //     for logging.
174     if (!ValidateTargetSlotSuffix(arg[2])) {
175         LOG(ERROR) << "Target slot suffix not legal: " << arg[2];
176         exit(207);
177     }
178     TryExtraMount("vendor", arg[2], "/postinstall/vendor");
179 
180     // Try to mount the product partition. update_engine doesn't do this for us, but we
181     // want it for product APKs. Same notes as vendor above.
182     TryExtraMount("product", arg[2], "/postinstall/product");
183 
184     // Setup APEX mount point and its security context.
185     static constexpr const char* kPostinstallApexDir = "/postinstall/apex";
186     // The following logic is similar to the one in system/core/rootdir/init.rc:
187     //
188     //   mount tmpfs tmpfs /apex nodev noexec nosuid
189     //   chmod 0755 /apex
190     //   chown root root /apex
191     //   restorecon /apex
192     //
193     // except we perform the `restorecon` step just after mounting the tmpfs
194     // filesystem in /postinstall/apex, so that this directory is correctly
195     // labeled (with type `postinstall_apex_mnt_dir`) and may be manipulated in
196     // following operations (`chmod`, `chown`, etc.) following policies
197     // restricted to `postinstall_apex_mnt_dir`:
198     //
199     //   mount tmpfs tmpfs /postinstall/apex nodev noexec nosuid
200     //   restorecon /postinstall/apex
201     //   chmod 0755 /postinstall/apex
202     //   chown root root /postinstall/apex
203     //
204     if (mount("tmpfs", kPostinstallApexDir, "tmpfs", MS_NODEV | MS_NOEXEC | MS_NOSUID, nullptr)
205         != 0) {
206         PLOG(ERROR) << "Failed to mount tmpfs in " << kPostinstallApexDir;
207         exit(209);
208     }
209     if (selinux_android_restorecon(kPostinstallApexDir, 0) < 0) {
210         PLOG(ERROR) << "Failed to restorecon " << kPostinstallApexDir;
211         exit(214);
212     }
213     if (chmod(kPostinstallApexDir, 0755) != 0) {
214         PLOG(ERROR) << "Failed to chmod " << kPostinstallApexDir << " to 0755";
215         exit(210);
216     }
217     if (chown(kPostinstallApexDir, 0, 0) != 0) {
218         PLOG(ERROR) << "Failed to chown " << kPostinstallApexDir << " to root:root";
219         exit(211);
220     }
221 
222     // Chdir into /postinstall.
223     if (chdir("/postinstall") != 0) {
224         PLOG(ERROR) << "Unable to chdir into /postinstall.";
225         exit(203);
226     }
227 
228     // Make /postinstall the root in our mount namespace.
229     if (chroot(".")  != 0) {
230         PLOG(ERROR) << "Failed to chroot";
231         exit(204);
232     }
233 
234     if (chdir("/") != 0) {
235         PLOG(ERROR) << "Unable to chdir into /.";
236         exit(205);
237     }
238 
239     // Try to mount APEX packages in "/apex" in the chroot dir. We need at least
240     // the ART APEX, as it is required by otapreopt to run dex2oat.
241     std::vector<apex::ApexFile> active_packages = ActivateApexPackages();
242 
243     // Check that an ART APEX has been activated; clean up and exit
244     // early otherwise.
245     if (std::none_of(active_packages.begin(),
246                      active_packages.end(),
247                      [](const apex::ApexFile& package){
248                          return package.GetManifest().name() == "com.android.art";
249                      })) {
250         LOG(FATAL_WITHOUT_ABORT) << "No activated com.android.art APEX package.";
251         DeactivateApexPackages(active_packages);
252         exit(217);
253     }
254 
255     // Now go on and run otapreopt.
256 
257     // Incoming:  cmd + status-fd + target-slot + cmd...      | Incoming | = argc
258     // Outgoing:  cmd             + target-slot + cmd...      | Outgoing | = argc - 1
259     std::vector<std::string> cmd;
260     cmd.reserve(argc);
261     cmd.push_back("/system/bin/otapreopt");
262 
263     // The first parameter is the status file descriptor, skip.
264     for (size_t i = 2; i < static_cast<size_t>(argc); ++i) {
265         cmd.push_back(arg[i]);
266     }
267 
268     // Fork and execute otapreopt in its own process.
269     std::string error_msg;
270     bool exec_result = Exec(cmd, &error_msg);
271     if (!exec_result) {
272         LOG(ERROR) << "Running otapreopt failed: " << error_msg;
273     }
274 
275     // Tear down the work down by the apexd logic. (i.e. deactivate packages).
276     DeactivateApexPackages(active_packages);
277 
278     if (!exec_result) {
279         exit(213);
280     }
281 
282     return 0;
283 }
284 
285 }  // namespace installd
286 }  // namespace android
287 
main(const int argc,char * argv[])288 int main(const int argc, char *argv[]) {
289     return android::installd::otapreopt_chroot(argc, argv);
290 }
291