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 <array>
24 #include <fstream>
25 #include <sstream>
26
27 #include <android-base/file.h>
28 #include <android-base/logging.h>
29 #include <android-base/macros.h>
30 #include <android-base/scopeguard.h>
31 #include <android-base/stringprintf.h>
32 #include <android-base/unique_fd.h>
33 #include <libdm/dm.h>
34 #include <selinux/android.h>
35
36 #include "installd_constants.h"
37 #include "otapreopt_utils.h"
38
39 #ifndef LOG_TAG
40 #define LOG_TAG "otapreopt"
41 #endif
42
43 using android::base::StringPrintf;
44
45 namespace android {
46 namespace installd {
47
CloseDescriptor(int fd)48 static 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
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 CloseDescriptor(fd);
62 }
63 }
64
ActivateApexPackages()65 static void ActivateApexPackages() {
66 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--otachroot-bootstrap"};
67 std::string apexd_error_msg;
68
69 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);
73 }
74 }
75
DeactivateApexPackages()76 static 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
TryExtraMount(const char * name,const char * slot,const char * target)85 static void TryExtraMount(const char* name, const char* slot, const char* target) {
86 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());
108 int mount_result = mount(block_device.c_str(),
109 target,
110 "ext4",
111 MS_RDONLY,
112 /* data */ nullptr);
113 UNUSED(mount_result);
114 }
115
116 // 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.
otapreopt_chroot(const int argc,char ** arg)120 static int otapreopt_chroot(const int argc, char **arg) {
121 // 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 }
127 // 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
136 // 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
163 // 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 }
176 TryExtraMount("vendor", arg[2], "/postinstall/vendor");
177
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.
180 TryExtraMount("product", arg[2], "/postinstall/product");
181
182 // Try to mount the system_ext partition. update_engine doesn't do this for
183 // us, but we want it for system_ext APKs. Same notes as vendor and product
184 // above.
185 TryExtraMount("system_ext", arg[2], "/postinstall/system_ext");
186
187 constexpr const char* kPostInstallLinkerconfig = "/postinstall/linkerconfig";
188 // Try to mount /postinstall/linkerconfig. we will set it up after performing the chroot
189 if (mount("tmpfs", kPostInstallLinkerconfig, "tmpfs", 0, nullptr) != 0) {
190 PLOG(ERROR) << "Failed to mount a tmpfs for " << kPostInstallLinkerconfig;
191 exit(215);
192 }
193
194 // Setup APEX mount point and its security context.
195 static constexpr const char* kPostinstallApexDir = "/postinstall/apex";
196 // The following logic is similar to the one in system/core/rootdir/init.rc:
197 //
198 // mount tmpfs tmpfs /apex nodev noexec nosuid
199 // chmod 0755 /apex
200 // chown root root /apex
201 // restorecon /apex
202 //
203 // except we perform the `restorecon` step just after mounting the tmpfs
204 // filesystem in /postinstall/apex, so that this directory is correctly
205 // labeled (with type `postinstall_apex_mnt_dir`) and may be manipulated in
206 // following operations (`chmod`, `chown`, etc.) following policies
207 // restricted to `postinstall_apex_mnt_dir`:
208 //
209 // mount tmpfs tmpfs /postinstall/apex nodev noexec nosuid
210 // restorecon /postinstall/apex
211 // chmod 0755 /postinstall/apex
212 // chown root root /postinstall/apex
213 //
214 if (mount("tmpfs", kPostinstallApexDir, "tmpfs", MS_NODEV | MS_NOEXEC | MS_NOSUID, nullptr)
215 != 0) {
216 PLOG(ERROR) << "Failed to mount tmpfs in " << kPostinstallApexDir;
217 exit(209);
218 }
219 if (selinux_android_restorecon(kPostinstallApexDir, 0) < 0) {
220 PLOG(ERROR) << "Failed to restorecon " << kPostinstallApexDir;
221 exit(214);
222 }
223 if (chmod(kPostinstallApexDir, 0755) != 0) {
224 PLOG(ERROR) << "Failed to chmod " << kPostinstallApexDir << " to 0755";
225 exit(210);
226 }
227 if (chown(kPostinstallApexDir, 0, 0) != 0) {
228 PLOG(ERROR) << "Failed to chown " << kPostinstallApexDir << " to root:root";
229 exit(211);
230 }
231
232 // Chdir into /postinstall.
233 if (chdir("/postinstall") != 0) {
234 PLOG(ERROR) << "Unable to chdir into /postinstall.";
235 exit(203);
236 }
237
238 // Make /postinstall the root in our mount namespace.
239 if (chroot(".") != 0) {
240 PLOG(ERROR) << "Failed to chroot";
241 exit(204);
242 }
243
244 if (chdir("/") != 0) {
245 PLOG(ERROR) << "Unable to chdir into /.";
246 exit(205);
247 }
248
249 // Call apexd --unmount-all to free up loop and dm block devices, so that we can re-use
250 // them during the next invocation. Since otapreopt_chroot calls exit in case something goes
251 // wrong we need to register our own atexit handler.
252 // We want to register this handler before actually activating apex packages. This is mostly
253 // due to the fact that if fail to unmount apexes, then on the next run of otapreopt_chroot
254 // we will ask for new loop devices instead of re-using existing ones, and we really don't want
255 // to do that. :)
256 if (atexit(DeactivateApexPackages) != 0) {
257 LOG(ERROR) << "Failed to register atexit hander";
258 exit(206);
259 }
260
261 // Try to mount APEX packages in "/apex" in the chroot dir. We need at least
262 // the ART APEX, as it is required by otapreopt to run dex2oat.
263 ActivateApexPackages();
264
265 auto cleanup = android::base::make_scope_guard([](){
266 std::vector<std::string> apexd_cmd{"/system/bin/apexd", "--unmount-all"};
267 std::string apexd_error_msg;
268 bool exec_result = Exec(apexd_cmd, &apexd_error_msg);
269 if (!exec_result) {
270 PLOG(ERROR) << "Running /system/bin/apexd --unmount-all failed: " << apexd_error_msg;
271 }
272 });
273 // Check that an ART APEX has been activated; clean up and exit
274 // early otherwise.
275 static constexpr const std::string_view kRequiredApexs[] = {
276 "com.android.art",
277 "com.android.runtime",
278 "com.android.sdkext", // For derive_classpath
279 };
280 std::array<bool, arraysize(kRequiredApexs)> found_apexs{ false, false };
281 DIR* apex_dir = opendir("/apex");
282 if (apex_dir == nullptr) {
283 PLOG(ERROR) << "unable to open /apex";
284 exit(220);
285 }
286 for (dirent* entry = readdir(apex_dir); entry != nullptr; entry = readdir(apex_dir)) {
287 for (int i = 0; i < found_apexs.size(); i++) {
288 if (kRequiredApexs[i] == std::string_view(entry->d_name)) {
289 found_apexs[i] = true;
290 break;
291 }
292 }
293 }
294 closedir(apex_dir);
295 auto it = std::find(found_apexs.cbegin(), found_apexs.cend(), false);
296 if (it != found_apexs.cend()) {
297 LOG(ERROR) << "No activated " << kRequiredApexs[std::distance(found_apexs.cbegin(), it)]
298 << " package!";
299 exit(221);
300 }
301
302 // Setup /linkerconfig. Doing it after the chroot means it doesn't need its own category
303 if (selinux_android_restorecon("/linkerconfig", 0) < 0) {
304 PLOG(ERROR) << "Failed to restorecon /linkerconfig";
305 exit(219);
306 }
307 std::vector<std::string> linkerconfig_cmd{"/apex/com.android.runtime/bin/linkerconfig",
308 "--target", "/linkerconfig"};
309 std::string linkerconfig_error_msg;
310 bool linkerconfig_exec_result = Exec(linkerconfig_cmd, &linkerconfig_error_msg);
311 if (!linkerconfig_exec_result) {
312 LOG(ERROR) << "Running linkerconfig failed: " << linkerconfig_error_msg;
313 exit(218);
314 }
315
316 // Now go on and run otapreopt.
317
318 // Incoming: cmd + status-fd + target-slot + cmd... | Incoming | = argc
319 // Outgoing: cmd + target-slot + cmd... | Outgoing | = argc - 1
320 std::vector<std::string> cmd;
321 cmd.reserve(argc);
322 cmd.push_back("/system/bin/otapreopt");
323
324 // The first parameter is the status file descriptor, skip.
325 for (size_t i = 2; i < static_cast<size_t>(argc); ++i) {
326 cmd.push_back(arg[i]);
327 }
328
329 // Fork and execute otapreopt in its own process.
330 std::string error_msg;
331 bool exec_result = Exec(cmd, &error_msg);
332 if (!exec_result) {
333 LOG(ERROR) << "Running otapreopt failed: " << error_msg;
334 }
335
336 if (!exec_result) {
337 exit(213);
338 }
339
340 return 0;
341 }
342
343 } // namespace installd
344 } // namespace android
345
main(const int argc,char * argv[])346 int main(const int argc, char *argv[]) {
347 return android::installd::otapreopt_chroot(argc, argv);
348 }
349