1 /*
2 * Copyright (C) 2008 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 "builtins.h"
18
19 #include <android/api-level.h>
20 #include <dirent.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <fts.h>
24 #include <glob.h>
25 #include <linux/loop.h>
26 #include <linux/module.h>
27 #include <mntent.h>
28 #include <net/if.h>
29 #include <sched.h>
30 #include <signal.h>
31 #include <stdint.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <sys/mount.h>
36 #include <sys/resource.h>
37 #include <sys/socket.h>
38 #include <sys/stat.h>
39 #include <sys/syscall.h>
40 #include <sys/system_properties.h>
41 #include <sys/time.h>
42 #include <sys/types.h>
43 #include <sys/wait.h>
44 #include <unistd.h>
45
46 #include <map>
47 #include <memory>
48
49 #include <InitProperties.sysprop.h>
50 #include <android-base/chrono_utils.h>
51 #include <android-base/file.h>
52 #include <android-base/logging.h>
53 #include <android-base/parsedouble.h>
54 #include <android-base/parseint.h>
55 #include <android-base/properties.h>
56 #include <android-base/stringprintf.h>
57 #include <android-base/strings.h>
58 #include <android-base/unique_fd.h>
59 #include <bootloader_message/bootloader_message.h>
60 #include <cutils/android_reboot.h>
61 #include <fs_mgr.h>
62 #include <fscrypt/fscrypt.h>
63 #include <libgsi/libgsi.h>
64 #include <logwrap/logwrap.h>
65 #include <private/android_filesystem_config.h>
66 #include <selinux/android.h>
67 #include <selinux/label.h>
68 #include <selinux/selinux.h>
69 #include <system/thread_defs.h>
70
71 #include "action_manager.h"
72 #include "apex_init_util.h"
73 #include "bootchart.h"
74 #include "builtin_arguments.h"
75 #include "fscrypt_init_extensions.h"
76 #include "init.h"
77 #include "mount_namespace.h"
78 #include "parser.h"
79 #include "property_service.h"
80 #include "reboot.h"
81 #include "rlimit_parser.h"
82 #include "selabel.h"
83 #include "selinux.h"
84 #include "service.h"
85 #include "service_list.h"
86 #include "subcontext.h"
87 #include "util.h"
88
89 using namespace std::literals::string_literals;
90
91 using android::base::Basename;
92 using android::base::ResultError;
93 using android::base::SetProperty;
94 using android::base::Split;
95 using android::base::StartsWith;
96 using android::base::StringPrintf;
97 using android::base::unique_fd;
98 using android::fs_mgr::Fstab;
99 using android::fs_mgr::ReadFstabFromFile;
100
101 #define chmod DO_NOT_USE_CHMOD_USE_FCHMODAT_SYMLINK_NOFOLLOW
102
103 namespace android {
104 namespace init {
105
106 // There are many legacy paths in rootdir/init.rc that will virtually never exist on a new
107 // device, such as '/sys/class/leds/jogball-backlight/brightness'. As of this writing, there
108 // are 81 such failures on cuttlefish. Instead of spamming the log reporting them, we do not
109 // report such failures unless we're running at the DEBUG log level.
110 class ErrorIgnoreEnoent {
111 public:
ErrorIgnoreEnoent()112 ErrorIgnoreEnoent()
113 : ignore_error_(errno == ENOENT &&
114 android::base::GetMinimumLogSeverity() > android::base::DEBUG) {}
ErrorIgnoreEnoent(int errno_to_append)115 explicit ErrorIgnoreEnoent(int errno_to_append)
116 : error_(errno_to_append),
117 ignore_error_(errno_to_append == ENOENT &&
118 android::base::GetMinimumLogSeverity() > android::base::DEBUG) {}
119
120 template <typename T>
operator android::base::expected<T,ResultError<android::base::Errno>>()121 operator android::base::expected<T, ResultError<android::base::Errno>>() {
122 if (ignore_error_) {
123 return {};
124 }
125 return error_;
126 }
127
128 template <typename T>
operator <<(T && t)129 ErrorIgnoreEnoent& operator<<(T&& t) {
130 error_ << t;
131 return *this;
132 }
133
134 private:
135 Error<> error_;
136 bool ignore_error_;
137 };
138
ErrnoErrorIgnoreEnoent()139 inline ErrorIgnoreEnoent ErrnoErrorIgnoreEnoent() {
140 return ErrorIgnoreEnoent(errno);
141 }
142
143 std::vector<std::string> late_import_paths;
144
145 static constexpr std::chrono::nanoseconds kCommandRetryTimeout = 5s;
146
reboot_into_recovery(const std::vector<std::string> & options)147 static Result<void> reboot_into_recovery(const std::vector<std::string>& options) {
148 LOG(ERROR) << "Rebooting into recovery";
149 std::string err;
150 if (!write_bootloader_message(options, &err)) {
151 return Error() << "Failed to set bootloader message: " << err;
152 }
153 trigger_shutdown("reboot,recovery");
154 return {};
155 }
156
157 template <typename F>
ForEachServiceInClass(const std::string & classname,F function)158 static void ForEachServiceInClass(const std::string& classname, F function) {
159 for (const auto& service : ServiceList::GetInstance()) {
160 if (service->classnames().count(classname)) std::invoke(function, service);
161 }
162 }
163
do_class_start(const BuiltinArguments & args)164 static Result<void> do_class_start(const BuiltinArguments& args) {
165 // Do not start a class if it has a property persist.dont_start_class.CLASS set to 1.
166 if (android::base::GetBoolProperty("persist.init.dont_start_class." + args[1], false))
167 return {};
168 // Starting a class does not start services which are explicitly disabled.
169 // They must be started individually.
170 for (const auto& service : ServiceList::GetInstance()) {
171 if (service->classnames().count(args[1])) {
172 if (auto result = service->StartIfNotDisabled(); !result.ok()) {
173 LOG(ERROR) << "Could not start service '" << service->name()
174 << "' as part of class '" << args[1] << "': " << result.error();
175 }
176 }
177 }
178 return {};
179 }
180
do_class_stop(const BuiltinArguments & args)181 static Result<void> do_class_stop(const BuiltinArguments& args) {
182 ForEachServiceInClass(args[1], &Service::Stop);
183 return {};
184 }
185
do_class_reset(const BuiltinArguments & args)186 static Result<void> do_class_reset(const BuiltinArguments& args) {
187 ForEachServiceInClass(args[1], &Service::Reset);
188 return {};
189 }
190
do_class_restart(const BuiltinArguments & args)191 static Result<void> do_class_restart(const BuiltinArguments& args) {
192 // Do not restart a class if it has a property persist.dont_start_class.CLASS set to 1.
193 if (android::base::GetBoolProperty("persist.init.dont_start_class." + args[1], false))
194 return {};
195
196 std::string classname;
197
198 CHECK(args.size() == 2 || args.size() == 3);
199
200 bool only_enabled = false;
201 if (args.size() == 3) {
202 if (args[1] != "--only-enabled") {
203 return Error() << "Unexpected argument: " << args[1];
204 }
205 only_enabled = true;
206 classname = args[2];
207 } else if (args.size() == 2) {
208 classname = args[1];
209 }
210
211 for (const auto& service : ServiceList::GetInstance()) {
212 if (!service->classnames().count(classname)) {
213 continue;
214 }
215 if (only_enabled && !service->IsEnabled()) {
216 continue;
217 }
218 service->Restart();
219 }
220 return {};
221 }
222
do_domainname(const BuiltinArguments & args)223 static Result<void> do_domainname(const BuiltinArguments& args) {
224 if (auto result = WriteFile("/proc/sys/kernel/domainname", args[1]); !result.ok()) {
225 return Error() << "Unable to write to /proc/sys/kernel/domainname: " << result.error();
226 }
227 return {};
228 }
229
do_enable(const BuiltinArguments & args)230 static Result<void> do_enable(const BuiltinArguments& args) {
231 Service* svc = ServiceList::GetInstance().FindService(args[1]);
232 if (!svc) return Error() << "Could not find service";
233
234 if (auto result = svc->Enable(); !result.ok()) {
235 return Error() << "Could not enable service: " << result.error();
236 }
237
238 return {};
239 }
240
do_exec(const BuiltinArguments & args)241 static Result<void> do_exec(const BuiltinArguments& args) {
242 auto service = Service::MakeTemporaryOneshotService(args.args);
243 if (!service.ok()) {
244 return Error() << "Could not create exec service: " << service.error();
245 }
246 if (auto result = (*service)->ExecStart(); !result.ok()) {
247 return Error() << "Could not start exec service: " << result.error();
248 }
249
250 ServiceList::GetInstance().AddService(std::move(*service));
251 return {};
252 }
253
do_exec_background(const BuiltinArguments & args)254 static Result<void> do_exec_background(const BuiltinArguments& args) {
255 auto service = Service::MakeTemporaryOneshotService(args.args);
256 if (!service.ok()) {
257 return Error() << "Could not create exec background service: " << service.error();
258 }
259 if (auto result = (*service)->Start(); !result.ok()) {
260 return Error() << "Could not start exec background service: " << result.error();
261 }
262
263 ServiceList::GetInstance().AddService(std::move(*service));
264 return {};
265 }
266
do_exec_start(const BuiltinArguments & args)267 static Result<void> do_exec_start(const BuiltinArguments& args) {
268 Service* service = ServiceList::GetInstance().FindService(args[1]);
269 if (!service) {
270 return Error() << "Service not found";
271 }
272
273 if (auto result = service->ExecStart(); !result.ok()) {
274 return Error() << "Could not start exec service: " << result.error();
275 }
276
277 return {};
278 }
279
do_export(const BuiltinArguments & args)280 static Result<void> do_export(const BuiltinArguments& args) {
281 if (setenv(args[1].c_str(), args[2].c_str(), 1) == -1) {
282 return ErrnoError() << "setenv() failed";
283 }
284 return {};
285 }
286
do_load_exports(const BuiltinArguments & args)287 static Result<void> do_load_exports(const BuiltinArguments& args) {
288 auto file_contents = ReadFile(args[1]);
289 if (!file_contents.ok()) {
290 return Error() << "Could not read input file '" << args[1]
291 << "': " << file_contents.error();
292 }
293
294 auto lines = Split(*file_contents, "\n");
295 for (const auto& line : lines) {
296 if (line.empty()) {
297 continue;
298 }
299
300 auto env = Split(line, " ");
301
302 if (env.size() != 3) {
303 return ErrnoError() << "Expected a line as `export <name> <value>`, found: `" << line
304 << "`";
305 }
306
307 if (env[0] != "export") {
308 return ErrnoError() << "Unknown action: '" << env[0] << "', expected 'export'";
309 }
310
311 if (setenv(env[1].c_str(), env[2].c_str(), 1) == -1) {
312 return ErrnoError() << "Failed to export '" << line << "' from " << args[1];
313 }
314 }
315
316 return {};
317 }
318
do_hostname(const BuiltinArguments & args)319 static Result<void> do_hostname(const BuiltinArguments& args) {
320 if (auto result = WriteFile("/proc/sys/kernel/hostname", args[1]); !result.ok()) {
321 return Error() << "Unable to write to /proc/sys/kernel/hostname: " << result.error();
322 }
323 return {};
324 }
325
do_ifup(const BuiltinArguments & args)326 static Result<void> do_ifup(const BuiltinArguments& args) {
327 struct ifreq ifr;
328
329 strlcpy(ifr.ifr_name, args[1].c_str(), IFNAMSIZ);
330
331 unique_fd s(TEMP_FAILURE_RETRY(socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0)));
332 if (s < 0) return ErrnoError() << "opening socket failed";
333
334 if (ioctl(s.get(), SIOCGIFFLAGS, &ifr) < 0) {
335 return ErrnoError() << "ioctl(..., SIOCGIFFLAGS, ...) failed";
336 }
337
338 ifr.ifr_flags |= IFF_UP;
339
340 if (ioctl(s.get(), SIOCSIFFLAGS, &ifr) < 0) {
341 return ErrnoError() << "ioctl(..., SIOCSIFFLAGS, ...) failed";
342 }
343
344 return {};
345 }
346
do_insmod(const BuiltinArguments & args)347 static Result<void> do_insmod(const BuiltinArguments& args) {
348 int flags = 0;
349 auto it = args.begin() + 1;
350
351 if (!(*it).compare("-f")) {
352 flags = MODULE_INIT_IGNORE_VERMAGIC | MODULE_INIT_IGNORE_MODVERSIONS;
353 it++;
354 }
355
356 std::string filename = *it++;
357 std::string options = android::base::Join(std::vector<std::string>(it, args.end()), ' ');
358
359 unique_fd fd(TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
360 if (fd == -1) return ErrnoError() << "open(\"" << filename << "\") failed";
361
362 int rc = syscall(__NR_finit_module, fd.get(), options.c_str(), flags);
363 if (rc == -1) return ErrnoError() << "finit_module for \"" << filename << "\" failed";
364
365 return {};
366 }
367
do_interface_restart(const BuiltinArguments & args)368 static Result<void> do_interface_restart(const BuiltinArguments& args) {
369 Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
370 if (!svc) return Error() << "interface " << args[1] << " not found";
371 svc->Restart();
372 return {};
373 }
374
do_interface_start(const BuiltinArguments & args)375 static Result<void> do_interface_start(const BuiltinArguments& args) {
376 Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
377 if (!svc) return Error() << "interface " << args[1] << " not found";
378 if (auto result = svc->Start(); !result.ok()) {
379 return Error() << "Could not start interface: " << result.error();
380 }
381 return {};
382 }
383
do_interface_stop(const BuiltinArguments & args)384 static Result<void> do_interface_stop(const BuiltinArguments& args) {
385 Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
386 if (!svc) return Error() << "interface " << args[1] << " not found";
387 svc->Stop();
388 return {};
389 }
390
make_dir_with_options(const MkdirOptions & options)391 static Result<void> make_dir_with_options(const MkdirOptions& options) {
392 std::string ref_basename;
393 if (options.ref_option == "ref") {
394 ref_basename = fscrypt_key_ref;
395 } else if (options.ref_option == "per_boot_ref") {
396 ref_basename = fscrypt_key_per_boot_ref;
397 } else {
398 return Error() << "Unknown key option: '" << options.ref_option << "'";
399 }
400
401 struct stat mstat;
402 if (lstat(options.target.c_str(), &mstat) != 0) {
403 if (errno != ENOENT) {
404 return ErrnoError() << "lstat() failed on " << options.target;
405 }
406 if (!make_dir(options.target, options.mode)) {
407 return ErrnoErrorIgnoreEnoent() << "mkdir() failed on " << options.target;
408 }
409 if (lstat(options.target.c_str(), &mstat) != 0) {
410 return ErrnoError() << "lstat() failed on new " << options.target;
411 }
412 }
413 if (!S_ISDIR(mstat.st_mode)) {
414 return Error() << "Not a directory on " << options.target;
415 }
416 bool needs_chmod = (mstat.st_mode & ~S_IFMT) != options.mode;
417 if ((options.uid != static_cast<uid_t>(-1) && options.uid != mstat.st_uid) ||
418 (options.gid != static_cast<gid_t>(-1) && options.gid != mstat.st_gid)) {
419 if (lchown(options.target.c_str(), options.uid, options.gid) == -1) {
420 return ErrnoError() << "lchown failed on " << options.target;
421 }
422 // chown may have cleared S_ISUID and S_ISGID, chmod again
423 needs_chmod = true;
424 }
425 if (needs_chmod) {
426 if (fchmodat(AT_FDCWD, options.target.c_str(), options.mode, AT_SYMLINK_NOFOLLOW) == -1) {
427 return ErrnoError() << "fchmodat() failed on " << options.target;
428 }
429 }
430 if (IsFbeEnabled()) {
431 if (!FscryptSetDirectoryPolicy(ref_basename, options.fscrypt_action, options.target)) {
432 return reboot_into_recovery(
433 {"--prompt_and_wipe_data", "--reason=set_policy_failed:"s + options.target});
434 }
435 }
436 return {};
437 }
438
439 // mkdir <path> [mode] [owner] [group] [<option> ...]
do_mkdir(const BuiltinArguments & args)440 static Result<void> do_mkdir(const BuiltinArguments& args) {
441 auto options = ParseMkdir(args.args);
442 if (!options.ok()) return options.error();
443 return make_dir_with_options(*options);
444 }
445
446 /* umount <path> */
do_umount(const BuiltinArguments & args)447 static Result<void> do_umount(const BuiltinArguments& args) {
448 if (umount(args[1].c_str()) < 0) {
449 return ErrnoError() << "umount() failed";
450 }
451 return {};
452 }
453
454 static struct {
455 const char *name;
456 unsigned flag;
457 } mount_flags[] = {
458 { "noatime", MS_NOATIME },
459 { "noexec", MS_NOEXEC },
460 { "nosuid", MS_NOSUID },
461 { "nodev", MS_NODEV },
462 { "nodiratime", MS_NODIRATIME },
463 { "ro", MS_RDONLY },
464 { "rw", 0 },
465 { "remount", MS_REMOUNT },
466 { "bind", MS_BIND },
467 { "rec", MS_REC },
468 { "unbindable", MS_UNBINDABLE },
469 { "private", MS_PRIVATE },
470 { "slave", MS_SLAVE },
471 { "shared", MS_SHARED },
472 { "defaults", 0 },
473 { 0, 0 },
474 };
475
476 #define DATA_MNT_POINT "/data"
477
478 /* mount <type> <device> <path> <flags ...> <options> */
do_mount(const BuiltinArguments & args)479 static Result<void> do_mount(const BuiltinArguments& args) {
480 const char* options = nullptr;
481 unsigned flags = 0;
482 bool wait = false;
483
484 for (size_t na = 4; na < args.size(); na++) {
485 size_t i;
486 for (i = 0; mount_flags[i].name; i++) {
487 if (!args[na].compare(mount_flags[i].name)) {
488 flags |= mount_flags[i].flag;
489 break;
490 }
491 }
492
493 if (!mount_flags[i].name) {
494 if (!args[na].compare("wait")) {
495 wait = true;
496 // If our last argument isn't a flag, wolf it up as an option string.
497 } else if (na + 1 == args.size()) {
498 options = args[na].c_str();
499 }
500 }
501 }
502
503 const char* system = args[1].c_str();
504 const char* source = args[2].c_str();
505 const char* target = args[3].c_str();
506
507 if (android::base::StartsWith(source, "loop@")) {
508 int mode = (flags & MS_RDONLY) ? O_RDONLY : O_RDWR;
509 unique_fd fd(TEMP_FAILURE_RETRY(open(source + 5, mode | O_CLOEXEC)));
510 if (fd < 0) return ErrnoError() << "open(" << source + 5 << ", " << mode << ") failed";
511
512 for (size_t n = 0;; n++) {
513 std::string tmp = android::base::StringPrintf("/dev/block/loop%zu", n);
514 unique_fd loop(TEMP_FAILURE_RETRY(open(tmp.c_str(), mode | O_CLOEXEC)));
515 if (loop < 0) return ErrnoError() << "open(" << tmp << ", " << mode << ") failed";
516
517 loop_info info;
518 /* if it is a blank loop device */
519 if (ioctl(loop.get(), LOOP_GET_STATUS, &info) < 0 && errno == ENXIO) {
520 /* if it becomes our loop device */
521 if (ioctl(loop.get(), LOOP_SET_FD, fd.get()) >= 0) {
522 if (mount(tmp.c_str(), target, system, flags, options) < 0) {
523 ioctl(loop.get(), LOOP_CLR_FD, 0);
524 return ErrnoError() << "mount() failed";
525 }
526 return {};
527 }
528 }
529 }
530
531 return Error() << "out of loopback devices";
532 } else {
533 if (wait)
534 wait_for_file(source, kCommandRetryTimeout);
535 if (mount(source, target, system, flags, options) < 0) {
536 return ErrnoErrorIgnoreEnoent() << "mount() failed";
537 }
538
539 }
540
541 return {};
542 }
543
544 /* Imports .rc files from the specified paths. Default ones are applied if none is given.
545 *
546 * rc_paths: list of paths to rc files to import
547 */
import_late(const std::vector<std::string> & rc_paths)548 static void import_late(const std::vector<std::string>& rc_paths) {
549 auto& action_manager = ActionManager::GetInstance();
550 auto& service_list = ServiceList::GetInstance();
551 Parser parser = CreateParser(action_manager, service_list);
552 if (rc_paths.empty()) {
553 // Fallbacks for partitions on which early mount isn't enabled.
554 for (const auto& path : late_import_paths) {
555 parser.ParseConfig(path);
556 }
557 late_import_paths.clear();
558 } else {
559 for (const auto& rc_path : rc_paths) {
560 parser.ParseConfig(rc_path);
561 }
562 }
563
564 // Turning this on and letting the INFO logging be discarded adds 0.2s to
565 // Nexus 9 boot time, so it's disabled by default.
566 if (false) DumpState();
567 }
568
569 /* Queue event based on fs_mgr return code.
570 *
571 * code: return code of fs_mgr_mount_all
572 *
573 * This function might request a reboot, in which case it will
574 * not return.
575 *
576 * return code is processed based on input code
577 */
queue_fs_event(int code,bool userdata_remount)578 static Result<void> queue_fs_event(int code, bool userdata_remount) {
579 if (code == FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
580 SetProperty("ro.crypto.state", "unsupported");
581 ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
582 return {};
583 } else if (code == FS_MGR_MNTALL_DEV_NEEDS_RECOVERY) {
584 /* Setup a wipe via recovery, and reboot into recovery */
585 if (android::gsi::IsGsiRunning()) {
586 return Error() << "cannot wipe within GSI";
587 }
588 PLOG(ERROR) << "fs_mgr_mount_all suggested recovery, so wiping data via recovery.";
589 const std::vector<std::string> options = {"--wipe_data", "--reason=fs_mgr_mount_all" };
590 return reboot_into_recovery(options);
591 /* If reboot worked, there is no return. */
592 } else if (code == FS_MGR_MNTALL_DEV_FILE_ENCRYPTED) {
593 if (!FscryptInstallKeyring()) {
594 return Error() << "FscryptInstallKeyring() failed";
595 }
596 SetProperty("ro.crypto.state", "encrypted");
597
598 // Although encrypted, we have device key, so we do not need to
599 // do anything different from the nonencrypted case.
600 ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
601 return {};
602 } else if (code == FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED) {
603 if (!FscryptInstallKeyring()) {
604 return Error() << "FscryptInstallKeyring() failed";
605 }
606 SetProperty("ro.crypto.state", "encrypted");
607
608 // Although encrypted, vold has already set the device up, so we do not need to
609 // do anything different from the nonencrypted case.
610 ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
611 return {};
612 } else if (code == FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION) {
613 if (!FscryptInstallKeyring()) {
614 return Error() << "FscryptInstallKeyring() failed";
615 }
616 SetProperty("ro.crypto.state", "encrypted");
617
618 // Although encrypted, vold has already set the device up, so we do not need to
619 // do anything different from the nonencrypted case.
620 ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
621 return {};
622 } else if (code > 0) {
623 Error() << "fs_mgr_mount_all() returned unexpected error " << code;
624 }
625 /* else ... < 0: error */
626
627 return Error() << "Invalid code: " << code;
628 }
629
630 static int initial_mount_fstab_return_code = -1;
631
632 /* <= Q: mount_all <fstab> [ <path> ]* [--<options>]*
633 * >= R: mount_all [ <fstab> ] [--<options>]*
634 *
635 * This function might request a reboot, in which case it will
636 * not return.
637 */
do_mount_all(const BuiltinArguments & args)638 static Result<void> do_mount_all(const BuiltinArguments& args) {
639 auto mount_all = ParseMountAll(args.args);
640 if (!mount_all.ok()) return mount_all.error();
641
642 const char* prop_post_fix = "default";
643 bool queue_event = true;
644 if (mount_all->mode == MOUNT_MODE_EARLY) {
645 prop_post_fix = "early";
646 queue_event = false;
647 } else if (mount_all->mode == MOUNT_MODE_LATE) {
648 prop_post_fix = "late";
649 }
650
651 std::string prop_name = "ro.boottime.init.mount_all."s + prop_post_fix;
652 android::base::Timer t;
653
654 Fstab fstab;
655 if (mount_all->fstab_path.empty()) {
656 if (!ReadDefaultFstab(&fstab)) {
657 return Error() << "Could not read default fstab";
658 }
659 } else {
660 if (!ReadFstabFromFile(mount_all->fstab_path, &fstab)) {
661 return Error() << "Could not read fstab";
662 }
663 }
664
665 auto mount_fstab_result = fs_mgr_mount_all(&fstab, mount_all->mode);
666 SetProperty(prop_name, std::to_string(t.duration().count()));
667
668 if (mount_all->import_rc) {
669 import_late(mount_all->rc_paths);
670 }
671
672 if (mount_fstab_result.userdata_mounted) {
673 // This call to fs_mgr_mount_all mounted userdata. Keep the result in
674 // order for userspace reboot to correctly remount userdata.
675 LOG(INFO) << "Userdata mounted using "
676 << (mount_all->fstab_path.empty() ? "(default fstab)" : mount_all->fstab_path)
677 << " result : " << mount_fstab_result.code;
678 initial_mount_fstab_return_code = mount_fstab_result.code;
679 }
680
681 if (queue_event) {
682 /* queue_fs_event will queue event based on mount_fstab return code
683 * and return processed return code*/
684 auto queue_fs_result = queue_fs_event(mount_fstab_result.code, false);
685 if (!queue_fs_result.ok()) {
686 return Error() << "queue_fs_event() failed: " << queue_fs_result.error();
687 }
688 }
689
690 return {};
691 }
692
693 /* umount_all [ <fstab> ] */
do_umount_all(const BuiltinArguments & args)694 static Result<void> do_umount_all(const BuiltinArguments& args) {
695 auto umount_all = ParseUmountAll(args.args);
696 if (!umount_all.ok()) return umount_all.error();
697
698 Fstab fstab;
699 if (umount_all->empty()) {
700 if (!ReadDefaultFstab(&fstab)) {
701 return Error() << "Could not read default fstab";
702 }
703 } else {
704 if (!ReadFstabFromFile(*umount_all, &fstab)) {
705 return Error() << "Could not read fstab";
706 }
707 }
708
709 if (auto result = fs_mgr_umount_all(&fstab); result != 0) {
710 return Error() << "umount_fstab() failed " << result;
711 }
712 return {};
713 }
714
715 /* swapon_all [ <fstab> ] */
do_swapon_all(const BuiltinArguments & args)716 static Result<void> do_swapon_all(const BuiltinArguments& args) {
717 auto swapon_all = ParseSwaponAll(args.args);
718 if (!swapon_all.ok()) return swapon_all.error();
719
720 Fstab fstab;
721 if (swapon_all->empty()) {
722 if (!ReadDefaultFstab(&fstab)) {
723 return Error() << "Could not read default fstab";
724 }
725 } else {
726 if (!ReadFstabFromFile(*swapon_all, &fstab)) {
727 return Error() << "Could not read fstab '" << *swapon_all << "'";
728 }
729 }
730
731 if (!fs_mgr_swapon_all(fstab)) {
732 return Error() << "fs_mgr_swapon_all() failed";
733 }
734
735 return {};
736 }
737
do_setprop(const BuiltinArguments & args)738 static Result<void> do_setprop(const BuiltinArguments& args) {
739 if (StartsWith(args[1], "ctl.")) {
740 return Error()
741 << "Cannot set ctl. properties from init; call the Service functions directly";
742 }
743 if (args[1] == kRestoreconProperty) {
744 return Error() << "Cannot set '" << kRestoreconProperty
745 << "' from init; use the restorecon builtin directly";
746 }
747
748 SetProperty(args[1], args[2]);
749 return {};
750 }
751
do_setrlimit(const BuiltinArguments & args)752 static Result<void> do_setrlimit(const BuiltinArguments& args) {
753 auto rlimit = ParseRlimit(args.args);
754 if (!rlimit.ok()) return rlimit.error();
755
756 if (setrlimit(rlimit->first, &rlimit->second) == -1) {
757 return ErrnoError() << "setrlimit failed";
758 }
759 return {};
760 }
761
do_start(const BuiltinArguments & args)762 static Result<void> do_start(const BuiltinArguments& args) {
763 Service* svc = ServiceList::GetInstance().FindService(args[1]);
764 if (!svc) return Error() << "service " << args[1] << " not found";
765 if (auto result = svc->Start(); !result.ok()) {
766 return ErrorIgnoreEnoent() << "Could not start service: " << result.error();
767 }
768 return {};
769 }
770
do_stop(const BuiltinArguments & args)771 static Result<void> do_stop(const BuiltinArguments& args) {
772 Service* svc = ServiceList::GetInstance().FindService(args[1]);
773 if (!svc) return Error() << "service " << args[1] << " not found";
774 svc->Stop();
775 return {};
776 }
777
do_restart(const BuiltinArguments & args)778 static Result<void> do_restart(const BuiltinArguments& args) {
779 bool only_if_running = false;
780 if (args.size() == 3) {
781 if (args[1] == "--only-if-running") {
782 only_if_running = true;
783 } else {
784 return Error() << "Unknown argument to restart: " << args[1];
785 }
786 }
787
788 const auto& classname = args[args.size() - 1];
789 Service* svc = ServiceList::GetInstance().FindService(classname);
790 if (!svc) return Error() << "service " << classname << " not found";
791 if (only_if_running && !svc->IsRunning()) {
792 return {};
793 }
794 svc->Restart();
795 return {};
796 }
797
do_trigger(const BuiltinArguments & args)798 static Result<void> do_trigger(const BuiltinArguments& args) {
799 ActionManager::GetInstance().QueueEventTrigger(args[1]);
800 return {};
801 }
802
MakeSymlink(const std::string & target,const std::string & linkpath)803 static int MakeSymlink(const std::string& target, const std::string& linkpath) {
804 std::string secontext;
805 // Passing 0 for mode should work.
806 if (SelabelLookupFileContext(linkpath, 0, &secontext) && !secontext.empty()) {
807 setfscreatecon(secontext.c_str());
808 }
809
810 int rc = symlink(target.c_str(), linkpath.c_str());
811
812 if (!secontext.empty()) {
813 int save_errno = errno;
814 setfscreatecon(nullptr);
815 errno = save_errno;
816 }
817
818 return rc;
819 }
820
do_symlink(const BuiltinArguments & args)821 static Result<void> do_symlink(const BuiltinArguments& args) {
822 if (MakeSymlink(args[1], args[2]) < 0) {
823 // The symlink builtin is often used to create symlinks for older devices to be backwards
824 // compatible with new paths, therefore we skip reporting this error.
825 return ErrnoErrorIgnoreEnoent() << "symlink() failed";
826 }
827 return {};
828 }
829
do_rm(const BuiltinArguments & args)830 static Result<void> do_rm(const BuiltinArguments& args) {
831 if (unlink(args[1].c_str()) < 0) {
832 return ErrnoError() << "unlink() failed";
833 }
834 return {};
835 }
836
do_rmdir(const BuiltinArguments & args)837 static Result<void> do_rmdir(const BuiltinArguments& args) {
838 if (rmdir(args[1].c_str()) < 0) {
839 return ErrnoError() << "rmdir() failed";
840 }
841 return {};
842 }
843
do_sysclktz(const BuiltinArguments & args)844 static Result<void> do_sysclktz(const BuiltinArguments& args) {
845 struct timezone tz = {};
846 if (!android::base::ParseInt(args[1], &tz.tz_minuteswest)) {
847 return Error() << "Unable to parse mins_west_of_gmt";
848 }
849
850 if (settimeofday(nullptr, &tz) == -1) {
851 return ErrnoError() << "settimeofday() failed";
852 }
853 return {};
854 }
855
do_verity_update_state(const BuiltinArguments & args)856 static Result<void> do_verity_update_state(const BuiltinArguments& args) {
857 int mode;
858 if (!fs_mgr_load_verity_state(&mode)) {
859 return Error() << "fs_mgr_load_verity_state() failed";
860 }
861
862 Fstab fstab;
863 if (!ReadDefaultFstab(&fstab)) {
864 return Error() << "Failed to read default fstab";
865 }
866
867 for (const auto& entry : fstab) {
868 if (!fs_mgr_is_verity_enabled(entry)) {
869 continue;
870 }
871
872 // To be consistent in vboot 1.0 and vboot 2.0 (AVB), use "system" for the partition even
873 // for system as root, so it has property [partition.system.verified].
874 std::string partition = entry.mount_point == "/" ? "system" : Basename(entry.mount_point);
875 SetProperty("partition." + partition + ".verified", std::to_string(mode));
876
877 auto hashtree_info = fs_mgr_get_hashtree_info(entry);
878 if (hashtree_info) {
879 SetProperty("partition." + partition + ".verified.hash_alg", hashtree_info->algorithm);
880 SetProperty("partition." + partition + ".verified.root_digest",
881 hashtree_info->root_digest);
882 SetProperty("partition." + partition + ".verified.check_at_most_once",
883 hashtree_info->check_at_most_once ? "1" : "0");
884 }
885 }
886
887 return {};
888 }
889
do_write(const BuiltinArguments & args)890 static Result<void> do_write(const BuiltinArguments& args) {
891 if (auto result = WriteFile(args[1], args[2]); !result.ok()) {
892 return ErrorIgnoreEnoent()
893 << "Unable to write to file '" << args[1] << "': " << result.error();
894 }
895
896 return {};
897 }
898
readahead_file(const std::string & filename,bool fully)899 static Result<void> readahead_file(const std::string& filename, bool fully) {
900 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY | O_CLOEXEC)));
901 if (fd == -1) {
902 return ErrnoError() << "Error opening file";
903 }
904 if (posix_fadvise(fd.get(), 0, 0, POSIX_FADV_WILLNEED)) {
905 return ErrnoError() << "Error posix_fadvise file";
906 }
907 if (readahead(fd.get(), 0, std::numeric_limits<size_t>::max())) {
908 return ErrnoError() << "Error readahead file";
909 }
910 if (fully) {
911 char buf[BUFSIZ];
912 ssize_t n;
913 while ((n = TEMP_FAILURE_RETRY(read(fd.get(), &buf[0], sizeof(buf)))) > 0) {
914 }
915 if (n != 0) {
916 return ErrnoError() << "Error reading file";
917 }
918 }
919 return {};
920 }
921
do_readahead(const BuiltinArguments & args)922 static Result<void> do_readahead(const BuiltinArguments& args) {
923 struct stat sb;
924
925 if (stat(args[1].c_str(), &sb)) {
926 return ErrnoError() << "Error opening " << args[1];
927 }
928
929 bool readfully = false;
930 if (args.size() == 3 && args[2] == "--fully") {
931 readfully = true;
932 }
933 // We will do readahead in a forked process in order not to block init
934 // since it may block while it reads the
935 // filesystem metadata needed to locate the requested blocks. This
936 // occurs frequently with ext[234] on large files using indirect blocks
937 // instead of extents, giving the appearance that the call blocks until
938 // the requested data has been read.
939 pid_t pid = fork();
940 if (pid == 0) {
941 if (setpriority(PRIO_PROCESS, 0, static_cast<int>(ANDROID_PRIORITY_LOWEST)) != 0) {
942 PLOG(WARNING) << "setpriority failed";
943 }
944 if (android_set_ioprio(0, IoSchedClass_IDLE, 7)) {
945 PLOG(WARNING) << "ioprio_get failed";
946 }
947 android::base::Timer t;
948 if (S_ISREG(sb.st_mode)) {
949 if (auto result = readahead_file(args[1], readfully); !result.ok()) {
950 LOG(WARNING) << "Unable to readahead '" << args[1] << "': " << result.error();
951 _exit(EXIT_FAILURE);
952 }
953 } else if (S_ISDIR(sb.st_mode)) {
954 char* paths[] = {const_cast<char*>(args[1].data()), nullptr};
955 std::unique_ptr<FTS, decltype(&fts_close)> fts(
956 fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr), fts_close);
957 if (!fts) {
958 PLOG(ERROR) << "Error opening directory: " << args[1];
959 _exit(EXIT_FAILURE);
960 }
961 // Traverse the entire hierarchy and do readahead
962 for (FTSENT* ftsent = fts_read(fts.get()); ftsent != nullptr;
963 ftsent = fts_read(fts.get())) {
964 if (ftsent->fts_info & FTS_F) {
965 const std::string filename = ftsent->fts_accpath;
966 if (auto result = readahead_file(filename, readfully); !result.ok()) {
967 LOG(WARNING)
968 << "Unable to readahead '" << filename << "': " << result.error();
969 }
970 }
971 }
972 }
973 LOG(INFO) << "Readahead " << args[1] << " took " << t << " asynchronously";
974 _exit(0);
975 } else if (pid < 0) {
976 return ErrnoError() << "Fork failed";
977 }
978 return {};
979 }
980
do_copy(const BuiltinArguments & args)981 static Result<void> do_copy(const BuiltinArguments& args) {
982 auto file_contents = ReadFile(args[1]);
983 if (!file_contents.ok()) {
984 return Error() << "Could not read input file '" << args[1] << "': " << file_contents.error();
985 }
986 if (auto result = WriteFile(args[2], *file_contents); !result.ok()) {
987 return Error() << "Could not write to output file '" << args[2] << "': " << result.error();
988 }
989
990 return {};
991 }
992
do_copy_per_line(const BuiltinArguments & args)993 static Result<void> do_copy_per_line(const BuiltinArguments& args) {
994 std::string file_contents;
995 if (!android::base::ReadFileToString(args[1], &file_contents, true)) {
996 return Error() << "Could not read input file '" << args[1] << "'";
997 }
998 auto lines = Split(file_contents, "\n");
999 for (const auto& line : lines) {
1000 auto result = WriteFile(args[2], line);
1001 if (!result.ok()) {
1002 LOG(VERBOSE) << "Could not write to output file '" << args[2] << "' with '" << line
1003 << "' : " << result.error();
1004 }
1005 }
1006
1007 return {};
1008 }
1009
do_chown(const BuiltinArguments & args)1010 static Result<void> do_chown(const BuiltinArguments& args) {
1011 auto uid = DecodeUid(args[1]);
1012 if (!uid.ok()) {
1013 return Error() << "Unable to decode UID for '" << args[1] << "': " << uid.error();
1014 }
1015
1016 // GID is optional and pushes the index of path out by one if specified.
1017 const std::string& path = (args.size() == 4) ? args[3] : args[2];
1018 Result<gid_t> gid = -1;
1019
1020 if (args.size() == 4) {
1021 gid = DecodeUid(args[2]);
1022 if (!gid.ok()) {
1023 return Error() << "Unable to decode GID for '" << args[2] << "': " << gid.error();
1024 }
1025 }
1026
1027 if (lchown(path.c_str(), *uid, *gid) == -1) {
1028 return ErrnoErrorIgnoreEnoent() << "lchown() failed";
1029 }
1030
1031 return {};
1032 }
1033
get_mode(const char * s)1034 static mode_t get_mode(const char *s) {
1035 mode_t mode = 0;
1036 while (*s) {
1037 if (*s >= '0' && *s <= '7') {
1038 mode = (mode<<3) | (*s-'0');
1039 } else {
1040 return -1;
1041 }
1042 s++;
1043 }
1044 return mode;
1045 }
1046
do_chmod(const BuiltinArguments & args)1047 static Result<void> do_chmod(const BuiltinArguments& args) {
1048 mode_t mode = get_mode(args[1].c_str());
1049 if (fchmodat(AT_FDCWD, args[2].c_str(), mode, AT_SYMLINK_NOFOLLOW) < 0) {
1050 return ErrnoErrorIgnoreEnoent() << "fchmodat() failed";
1051 }
1052 return {};
1053 }
1054
do_restorecon(const BuiltinArguments & args)1055 static Result<void> do_restorecon(const BuiltinArguments& args) {
1056 auto restorecon_info = ParseRestorecon(args.args);
1057 if (!restorecon_info.ok()) {
1058 return restorecon_info.error();
1059 }
1060
1061 const auto& [flag, paths] = *restorecon_info;
1062
1063 int ret = 0;
1064 for (const auto& path : paths) {
1065 if (selinux_android_restorecon(path.c_str(), flag) < 0) {
1066 ret = errno;
1067 }
1068 }
1069
1070 if (ret) return ErrnoErrorIgnoreEnoent() << "selinux_android_restorecon() failed";
1071 return {};
1072 }
1073
do_restorecon_recursive(const BuiltinArguments & args)1074 static Result<void> do_restorecon_recursive(const BuiltinArguments& args) {
1075 std::vector<std::string> non_const_args(args.args);
1076 non_const_args.insert(std::next(non_const_args.begin()), "--recursive");
1077 return do_restorecon({.args = std::move(non_const_args), .context = args.context});
1078 }
1079
do_loglevel(const BuiltinArguments & args)1080 static Result<void> do_loglevel(const BuiltinArguments& args) {
1081 // TODO: support names instead/as well?
1082 int log_level = -1;
1083 android::base::ParseInt(args[1], &log_level);
1084 android::base::LogSeverity severity;
1085 switch (log_level) {
1086 case 7: severity = android::base::DEBUG; break;
1087 case 6: severity = android::base::INFO; break;
1088 case 5:
1089 case 4: severity = android::base::WARNING; break;
1090 case 3: severity = android::base::ERROR; break;
1091 case 2:
1092 case 1:
1093 case 0: severity = android::base::FATAL; break;
1094 default:
1095 return Error() << "invalid log level " << log_level;
1096 }
1097 android::base::SetMinimumLogSeverity(severity);
1098 return {};
1099 }
1100
do_load_persist_props(const BuiltinArguments & args)1101 static Result<void> do_load_persist_props(const BuiltinArguments& args) {
1102 SendLoadPersistentPropertiesMessage();
1103
1104 start_waiting_for_property("ro.persistent_properties.ready", "true");
1105 return {};
1106 }
1107
do_load_system_props(const BuiltinArguments & args)1108 static Result<void> do_load_system_props(const BuiltinArguments& args) {
1109 LOG(INFO) << "deprecated action `load_system_props` called.";
1110 return {};
1111 }
1112
do_wait(const BuiltinArguments & args)1113 static Result<void> do_wait(const BuiltinArguments& args) {
1114 auto timeout = kCommandRetryTimeout;
1115 if (args.size() == 3) {
1116 double timeout_double;
1117 if (!android::base::ParseDouble(args[2], &timeout_double, 0)) {
1118 return Error() << "failed to parse timeout";
1119 }
1120 timeout = std::chrono::duration_cast<std::chrono::nanoseconds>(
1121 std::chrono::duration<double>(timeout_double));
1122 }
1123
1124 if (wait_for_file(args[1].c_str(), timeout) != 0) {
1125 return Error() << "wait_for_file() failed";
1126 }
1127
1128 return {};
1129 }
1130
do_wait_for_prop(const BuiltinArguments & args)1131 static Result<void> do_wait_for_prop(const BuiltinArguments& args) {
1132 const char* name = args[1].c_str();
1133 const char* value = args[2].c_str();
1134 size_t value_len = strlen(value);
1135
1136 if (!IsLegalPropertyName(name)) {
1137 return Error() << "IsLegalPropertyName(" << name << ") failed";
1138 }
1139 if (value_len >= PROP_VALUE_MAX) {
1140 return Error() << "value too long";
1141 }
1142 if (!start_waiting_for_property(name, value)) {
1143 return Error() << "already waiting for a property";
1144 }
1145 return {};
1146 }
1147
is_file_crypto()1148 static bool is_file_crypto() {
1149 return android::base::GetProperty("ro.crypto.type", "") == "file";
1150 }
1151
ExecWithFunctionOnFailure(const std::vector<std::string> & args,std::function<void (const std::string &)> function)1152 static Result<void> ExecWithFunctionOnFailure(const std::vector<std::string>& args,
1153 std::function<void(const std::string&)> function) {
1154 auto service = Service::MakeTemporaryOneshotService(args);
1155 if (!service.ok()) {
1156 function("MakeTemporaryOneshotService failed: " + service.error().message());
1157 }
1158 (*service)->AddReapCallback([function](const siginfo_t& siginfo) {
1159 if (siginfo.si_code != CLD_EXITED || siginfo.si_status != 0) {
1160 function(StringPrintf("Exec service failed, status %d", siginfo.si_status));
1161 }
1162 });
1163 if (auto result = (*service)->ExecStart(); !result.ok()) {
1164 function("ExecStart failed: " + result.error().message());
1165 }
1166 ServiceList::GetInstance().AddService(std::move(*service));
1167 return {};
1168 }
1169
ExecVdcRebootOnFailure(const std::string & vdc_arg)1170 static Result<void> ExecVdcRebootOnFailure(const std::string& vdc_arg) {
1171 bool should_reboot_into_recovery = true;
1172 auto reboot_reason = vdc_arg + "_failed";
1173 if (android::sysprop::InitProperties::userspace_reboot_in_progress().value_or(false)) {
1174 should_reboot_into_recovery = false;
1175 reboot_reason = "userspace_failed," + vdc_arg;
1176 }
1177
1178 auto reboot = [reboot_reason, should_reboot_into_recovery](const std::string& message) {
1179 // TODO (b/122850122): support this in gsi
1180 if (should_reboot_into_recovery) {
1181 if (IsFbeEnabled() && !android::gsi::IsGsiRunning()) {
1182 LOG(ERROR) << message << ": Rebooting into recovery, reason: " << reboot_reason;
1183 if (auto result = reboot_into_recovery(
1184 {"--prompt_and_wipe_data", "--reason="s + reboot_reason});
1185 !result.ok()) {
1186 LOG(FATAL) << "Could not reboot into recovery: " << result.error();
1187 }
1188 } else {
1189 LOG(ERROR) << "Failure (reboot suppressed): " << reboot_reason;
1190 }
1191 } else {
1192 LOG(ERROR) << message << ": rebooting, reason: " << reboot_reason;
1193 trigger_shutdown("reboot," + reboot_reason);
1194 }
1195 };
1196
1197 std::vector<std::string> args = {"exec", "/system/bin/vdc", "--wait", "cryptfs", vdc_arg};
1198 return ExecWithFunctionOnFailure(args, reboot);
1199 }
1200
do_remount_userdata(const BuiltinArguments & args)1201 static Result<void> do_remount_userdata(const BuiltinArguments& args) {
1202 if (initial_mount_fstab_return_code == -1) {
1203 return Error() << "Calling remount_userdata too early";
1204 }
1205 Fstab fstab;
1206 if (!ReadDefaultFstab(&fstab)) {
1207 // TODO(b/135984674): should we reboot here?
1208 return Error() << "Failed to read fstab";
1209 }
1210 // TODO(b/135984674): check that fstab contains /data.
1211 if (auto rc = fs_mgr_remount_userdata_into_checkpointing(&fstab); rc < 0) {
1212 std::string proc_mounts_output;
1213 android::base::ReadFileToString("/proc/mounts", &proc_mounts_output, true);
1214 android::base::WriteStringToFile(proc_mounts_output,
1215 "/metadata/userspacereboot/mount_info.txt");
1216 trigger_shutdown("reboot,mount_userdata_failed");
1217 }
1218 if (auto result = queue_fs_event(initial_mount_fstab_return_code, true); !result.ok()) {
1219 return Error() << "queue_fs_event() failed: " << result.error();
1220 }
1221 return {};
1222 }
1223
do_installkey(const BuiltinArguments & args)1224 static Result<void> do_installkey(const BuiltinArguments& args) {
1225 if (!is_file_crypto()) return {};
1226
1227 auto unencrypted_dir = args[1] + fscrypt_unencrypted_folder;
1228 if (!make_dir(unencrypted_dir, 0700) && errno != EEXIST) {
1229 return ErrnoError() << "Failed to create " << unencrypted_dir;
1230 }
1231 return ExecVdcRebootOnFailure("enablefilecrypto");
1232 }
1233
do_init_user0(const BuiltinArguments & args)1234 static Result<void> do_init_user0(const BuiltinArguments& args) {
1235 return ExecVdcRebootOnFailure("init_user0");
1236 }
1237
do_mark_post_data(const BuiltinArguments & args)1238 static Result<void> do_mark_post_data(const BuiltinArguments& args) {
1239 ServiceList::GetInstance().MarkPostData();
1240
1241 return {};
1242 }
1243
GenerateLinkerConfiguration()1244 static Result<void> GenerateLinkerConfiguration() {
1245 const char* linkerconfig_binary = "/apex/com.android.runtime/bin/linkerconfig";
1246 const char* linkerconfig_target = "/linkerconfig";
1247 const char* arguments[] = {linkerconfig_binary, "--target", linkerconfig_target};
1248
1249 if (logwrap_fork_execvp(arraysize(arguments), arguments, nullptr, false, LOG_KLOG, false,
1250 nullptr) != 0) {
1251 return ErrnoError() << "failed to execute linkerconfig";
1252 }
1253
1254 auto current_mount_ns = GetCurrentMountNamespace();
1255 if (!current_mount_ns.ok()) {
1256 return current_mount_ns.error();
1257 }
1258 if (*current_mount_ns == NS_DEFAULT) {
1259 SetDefaultMountNamespaceReady();
1260 }
1261
1262 LOG(INFO) << "linkerconfig generated " << linkerconfig_target
1263 << " with mounted APEX modules info";
1264
1265 return {};
1266 }
1267
MountLinkerConfigForDefaultNamespace()1268 static Result<void> MountLinkerConfigForDefaultNamespace() {
1269 // No need to mount linkerconfig for default mount namespace if the path does not exist (which
1270 // would mean it is already mounted)
1271 if (access("/linkerconfig/default", 0) != 0) {
1272 return {};
1273 }
1274
1275 if (mount("/linkerconfig/default", "/linkerconfig", nullptr, MS_BIND | MS_REC, nullptr) != 0) {
1276 return ErrnoError() << "Failed to mount linker configuration for default mount namespace.";
1277 }
1278
1279 return {};
1280 }
do_update_linker_config(const BuiltinArguments &)1281 static Result<void> do_update_linker_config(const BuiltinArguments&) {
1282 return GenerateLinkerConfiguration();
1283 }
1284
1285 /*
1286 * Creates a directory under /data/misc/apexdata/ for each APEX.
1287 */
create_apex_data_dirs()1288 static Result<void> create_apex_data_dirs() {
1289 auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir("/apex"), closedir);
1290 if (!dirp) {
1291 return ErrnoError() << "Unable to open apex directory";
1292 }
1293 struct dirent* entry;
1294 while ((entry = readdir(dirp.get())) != nullptr) {
1295 if (entry->d_type != DT_DIR) continue;
1296
1297 const char* name = entry->d_name;
1298 // skip any starting with "."
1299 if (name[0] == '.') continue;
1300
1301 if (strchr(name, '@') != nullptr) continue;
1302
1303 auto path = "/data/misc/apexdata/" + std::string(name);
1304 auto options = MkdirOptions{path, 0771, AID_ROOT, AID_SYSTEM, FscryptAction::kNone, "ref"};
1305 make_dir_with_options(options);
1306 }
1307 return {};
1308 }
1309
do_perform_apex_config(const BuiltinArguments & args)1310 static Result<void> do_perform_apex_config(const BuiltinArguments& args) {
1311 auto create_dirs = create_apex_data_dirs();
1312 if (!create_dirs.ok()) {
1313 return create_dirs.error();
1314 }
1315 auto parse_configs = ParseApexConfigs(/*apex_name=*/"");
1316 ServiceList::GetInstance().MarkServicesUpdate();
1317 if (!parse_configs.ok()) {
1318 return parse_configs.error();
1319 }
1320
1321 auto update_linker_config = do_update_linker_config(args);
1322 if (!update_linker_config.ok()) {
1323 return update_linker_config.error();
1324 }
1325
1326 return {};
1327 }
1328
do_enter_default_mount_ns(const BuiltinArguments & args)1329 static Result<void> do_enter_default_mount_ns(const BuiltinArguments& args) {
1330 if (auto result = SwitchToMountNamespaceIfNeeded(NS_DEFAULT); !result.ok()) {
1331 return result.error();
1332 }
1333 if (auto result = MountLinkerConfigForDefaultNamespace(); !result.ok()) {
1334 return result.error();
1335 }
1336 LOG(INFO) << "Switched to default mount namespace";
1337 return {};
1338 }
1339
1340 // Builtin-function-map start
GetBuiltinFunctionMap()1341 const BuiltinFunctionMap& GetBuiltinFunctionMap() {
1342 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
1343 // clang-format off
1344 static const BuiltinFunctionMap builtin_functions = {
1345 {"bootchart", {1, 1, {false, do_bootchart}}},
1346 {"chmod", {2, 2, {true, do_chmod}}},
1347 {"chown", {2, 3, {true, do_chown}}},
1348 {"class_reset", {1, 1, {false, do_class_reset}}},
1349 {"class_restart", {1, 2, {false, do_class_restart}}},
1350 {"class_start", {1, 1, {false, do_class_start}}},
1351 {"class_stop", {1, 1, {false, do_class_stop}}},
1352 {"copy", {2, 2, {true, do_copy}}},
1353 {"copy_per_line", {2, 2, {true, do_copy_per_line}}},
1354 {"domainname", {1, 1, {true, do_domainname}}},
1355 {"enable", {1, 1, {false, do_enable}}},
1356 {"exec", {1, kMax, {false, do_exec}}},
1357 {"exec_background", {1, kMax, {false, do_exec_background}}},
1358 {"exec_start", {1, 1, {false, do_exec_start}}},
1359 {"export", {2, 2, {false, do_export}}},
1360 {"hostname", {1, 1, {true, do_hostname}}},
1361 {"ifup", {1, 1, {true, do_ifup}}},
1362 {"init_user0", {0, 0, {false, do_init_user0}}},
1363 {"insmod", {1, kMax, {true, do_insmod}}},
1364 {"installkey", {1, 1, {false, do_installkey}}},
1365 {"interface_restart", {1, 1, {false, do_interface_restart}}},
1366 {"interface_start", {1, 1, {false, do_interface_start}}},
1367 {"interface_stop", {1, 1, {false, do_interface_stop}}},
1368 {"load_exports", {1, 1, {false, do_load_exports}}},
1369 {"load_persist_props", {0, 0, {false, do_load_persist_props}}},
1370 {"load_system_props", {0, 0, {false, do_load_system_props}}},
1371 {"loglevel", {1, 1, {false, do_loglevel}}},
1372 {"mark_post_data", {0, 0, {false, do_mark_post_data}}},
1373 {"mkdir", {1, 6, {true, do_mkdir}}},
1374 // TODO: Do mount operations in vendor_init.
1375 // mount_all is currently too complex to run in vendor_init as it queues action triggers,
1376 // imports rc scripts, etc. It should be simplified and run in vendor_init context.
1377 // mount and umount are run in the same context as mount_all for symmetry.
1378 {"mount_all", {0, kMax, {false, do_mount_all}}},
1379 {"mount", {3, kMax, {false, do_mount}}},
1380 {"perform_apex_config", {0, 0, {false, do_perform_apex_config}}},
1381 {"umount", {1, 1, {false, do_umount}}},
1382 {"umount_all", {0, 1, {false, do_umount_all}}},
1383 {"update_linker_config", {0, 0, {false, do_update_linker_config}}},
1384 {"readahead", {1, 2, {true, do_readahead}}},
1385 {"remount_userdata", {0, 0, {false, do_remount_userdata}}},
1386 {"restart", {1, 2, {false, do_restart}}},
1387 {"restorecon", {1, kMax, {true, do_restorecon}}},
1388 {"restorecon_recursive", {1, kMax, {true, do_restorecon_recursive}}},
1389 {"rm", {1, 1, {true, do_rm}}},
1390 {"rmdir", {1, 1, {true, do_rmdir}}},
1391 {"setprop", {2, 2, {true, do_setprop}}},
1392 {"setrlimit", {3, 3, {false, do_setrlimit}}},
1393 {"start", {1, 1, {false, do_start}}},
1394 {"stop", {1, 1, {false, do_stop}}},
1395 {"swapon_all", {0, 1, {false, do_swapon_all}}},
1396 {"enter_default_mount_ns", {0, 0, {false, do_enter_default_mount_ns}}},
1397 {"symlink", {2, 2, {true, do_symlink}}},
1398 {"sysclktz", {1, 1, {false, do_sysclktz}}},
1399 {"trigger", {1, 1, {false, do_trigger}}},
1400 {"verity_update_state", {0, 0, {false, do_verity_update_state}}},
1401 {"wait", {1, 2, {true, do_wait}}},
1402 {"wait_for_prop", {2, 2, {false, do_wait_for_prop}}},
1403 {"write", {2, 2, {true, do_write}}},
1404 };
1405 // clang-format on
1406 return builtin_functions;
1407 }
1408 // Builtin-function-map end
1409
1410 } // namespace init
1411 } // namespace android
1412