Home | History | Annotate | Download | only in init
      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 "init.h"
     18 
     19 #include <dirent.h>
     20 #include <fcntl.h>
     21 #include <paths.h>
     22 #include <pthread.h>
     23 #include <seccomp_policy.h>
     24 #include <signal.h>
     25 #include <stdlib.h>
     26 #include <string.h>
     27 #include <sys/epoll.h>
     28 #include <sys/mount.h>
     29 #include <sys/signalfd.h>
     30 #include <sys/sysmacros.h>
     31 #include <sys/types.h>
     32 #include <unistd.h>
     33 
     34 #include <android-base/chrono_utils.h>
     35 #include <android-base/file.h>
     36 #include <android-base/logging.h>
     37 #include <android-base/properties.h>
     38 #include <android-base/stringprintf.h>
     39 #include <android-base/strings.h>
     40 #include <cutils/android_reboot.h>
     41 #include <keyutils.h>
     42 #include <libavb/libavb.h>
     43 #include <private/android_filesystem_config.h>
     44 #include <selinux/android.h>
     45 
     46 #include <memory>
     47 #include <optional>
     48 
     49 #include "action_parser.h"
     50 #include "import_parser.h"
     51 #include "init_first_stage.h"
     52 #include "keychords.h"
     53 #include "log.h"
     54 #include "property_service.h"
     55 #include "reboot.h"
     56 #include "security.h"
     57 #include "selinux.h"
     58 #include "sigchld_handler.h"
     59 #include "ueventd.h"
     60 #include "util.h"
     61 #include "watchdogd.h"
     62 
     63 using namespace std::string_literals;
     64 
     65 using android::base::boot_clock;
     66 using android::base::GetProperty;
     67 using android::base::ReadFileToString;
     68 using android::base::StringPrintf;
     69 using android::base::Timer;
     70 using android::base::Trim;
     71 
     72 namespace android {
     73 namespace init {
     74 
     75 static int property_triggers_enabled = 0;
     76 
     77 static char qemu[32];
     78 
     79 std::string default_console = "/dev/console";
     80 
     81 static int epoll_fd = -1;
     82 static int sigterm_signal_fd = -1;
     83 
     84 static std::unique_ptr<Timer> waiting_for_prop(nullptr);
     85 static std::string wait_prop_name;
     86 static std::string wait_prop_value;
     87 static bool shutting_down;
     88 static std::string shutdown_command;
     89 static bool do_shutdown = false;
     90 
     91 std::vector<std::string> late_import_paths;
     92 
     93 static std::vector<Subcontext>* subcontexts;
     94 
     95 void DumpState() {
     96     ServiceList::GetInstance().DumpState();
     97     ActionManager::GetInstance().DumpState();
     98 }
     99 
    100 Parser CreateParser(ActionManager& action_manager, ServiceList& service_list) {
    101     Parser parser;
    102 
    103     parser.AddSectionParser("service", std::make_unique<ServiceParser>(&service_list, subcontexts));
    104     parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, subcontexts));
    105     parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
    106 
    107     return parser;
    108 }
    109 
    110 static void LoadBootScripts(ActionManager& action_manager, ServiceList& service_list) {
    111     Parser parser = CreateParser(action_manager, service_list);
    112 
    113     std::string bootscript = GetProperty("ro.boot.init_rc", "");
    114     if (bootscript.empty()) {
    115         parser.ParseConfig("/init.rc");
    116         if (!parser.ParseConfig("/system/etc/init")) {
    117             late_import_paths.emplace_back("/system/etc/init");
    118         }
    119         if (!parser.ParseConfig("/product/etc/init")) {
    120             late_import_paths.emplace_back("/product/etc/init");
    121         }
    122         if (!parser.ParseConfig("/odm/etc/init")) {
    123             late_import_paths.emplace_back("/odm/etc/init");
    124         }
    125         if (!parser.ParseConfig("/vendor/etc/init")) {
    126             late_import_paths.emplace_back("/vendor/etc/init");
    127         }
    128     } else {
    129         parser.ParseConfig(bootscript);
    130     }
    131 }
    132 
    133 void register_epoll_handler(int fd, void (*fn)()) {
    134     epoll_event ev;
    135     ev.events = EPOLLIN;
    136     ev.data.ptr = reinterpret_cast<void*>(fn);
    137     if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
    138         PLOG(ERROR) << "epoll_ctl failed";
    139     }
    140 }
    141 
    142 bool start_waiting_for_property(const char *name, const char *value)
    143 {
    144     if (waiting_for_prop) {
    145         return false;
    146     }
    147     if (GetProperty(name, "") != value) {
    148         // Current property value is not equal to expected value
    149         wait_prop_name = name;
    150         wait_prop_value = value;
    151         waiting_for_prop.reset(new Timer());
    152     } else {
    153         LOG(INFO) << "start_waiting_for_property(\""
    154                   << name << "\", \"" << value << "\"): already set";
    155     }
    156     return true;
    157 }
    158 
    159 void ResetWaitForProp() {
    160     wait_prop_name.clear();
    161     wait_prop_value.clear();
    162     waiting_for_prop.reset();
    163 }
    164 
    165 void property_changed(const std::string& name, const std::string& value) {
    166     // If the property is sys.powerctl, we bypass the event queue and immediately handle it.
    167     // This is to ensure that init will always and immediately shutdown/reboot, regardless of
    168     // if there are other pending events to process or if init is waiting on an exec service or
    169     // waiting on a property.
    170     // In non-thermal-shutdown case, 'shutdown' trigger will be fired to let device specific
    171     // commands to be executed.
    172     if (name == "sys.powerctl") {
    173         // Despite the above comment, we can't call HandlePowerctlMessage() in this function,
    174         // because it modifies the contents of the action queue, which can cause the action queue
    175         // to get into a bad state if this function is called from a command being executed by the
    176         // action queue.  Instead we set this flag and ensure that shutdown happens before the next
    177         // command is run in the main init loop.
    178         // TODO: once property service is removed from init, this will never happen from a builtin,
    179         // but rather from a callback from the property service socket, in which case this hack can
    180         // go away.
    181         shutdown_command = value;
    182         do_shutdown = true;
    183     }
    184 
    185     if (property_triggers_enabled) ActionManager::GetInstance().QueuePropertyChange(name, value);
    186 
    187     if (waiting_for_prop) {
    188         if (wait_prop_name == name && wait_prop_value == value) {
    189             LOG(INFO) << "Wait for property took " << *waiting_for_prop;
    190             ResetWaitForProp();
    191         }
    192     }
    193 }
    194 
    195 static std::optional<boot_clock::time_point> RestartProcesses() {
    196     std::optional<boot_clock::time_point> next_process_restart_time;
    197     for (const auto& s : ServiceList::GetInstance()) {
    198         if (!(s->flags() & SVC_RESTARTING)) continue;
    199 
    200         auto restart_time = s->time_started() + 5s;
    201         if (boot_clock::now() > restart_time) {
    202             if (auto result = s->Start(); !result) {
    203                 LOG(ERROR) << "Could not restart process '" << s->name() << "': " << result.error();
    204             }
    205         } else {
    206             if (!next_process_restart_time || restart_time < *next_process_restart_time) {
    207                 next_process_restart_time = restart_time;
    208             }
    209         }
    210     }
    211     return next_process_restart_time;
    212 }
    213 
    214 static Result<Success> DoControlStart(Service* service) {
    215     return service->Start();
    216 }
    217 
    218 static Result<Success> DoControlStop(Service* service) {
    219     service->Stop();
    220     return Success();
    221 }
    222 
    223 static Result<Success> DoControlRestart(Service* service) {
    224     service->Restart();
    225     return Success();
    226 }
    227 
    228 enum class ControlTarget {
    229     SERVICE,    // function gets called for the named service
    230     INTERFACE,  // action gets called for every service that holds this interface
    231 };
    232 
    233 struct ControlMessageFunction {
    234     ControlTarget target;
    235     std::function<Result<Success>(Service*)> action;
    236 };
    237 
    238 static const std::map<std::string, ControlMessageFunction>& get_control_message_map() {
    239     // clang-format off
    240     static const std::map<std::string, ControlMessageFunction> control_message_functions = {
    241         {"start",             {ControlTarget::SERVICE,   DoControlStart}},
    242         {"stop",              {ControlTarget::SERVICE,   DoControlStop}},
    243         {"restart",           {ControlTarget::SERVICE,   DoControlRestart}},
    244         {"interface_start",   {ControlTarget::INTERFACE, DoControlStart}},
    245         {"interface_stop",    {ControlTarget::INTERFACE, DoControlStop}},
    246         {"interface_restart", {ControlTarget::INTERFACE, DoControlRestart}},
    247     };
    248     // clang-format on
    249 
    250     return control_message_functions;
    251 }
    252 
    253 void HandleControlMessage(const std::string& msg, const std::string& name, pid_t pid) {
    254     const auto& map = get_control_message_map();
    255     const auto it = map.find(msg);
    256 
    257     if (it == map.end()) {
    258         LOG(ERROR) << "Unknown control msg '" << msg << "'";
    259         return;
    260     }
    261 
    262     std::string cmdline_path = StringPrintf("proc/%d/cmdline", pid);
    263     std::string process_cmdline;
    264     if (ReadFileToString(cmdline_path, &process_cmdline)) {
    265         std::replace(process_cmdline.begin(), process_cmdline.end(), '\0', ' ');
    266         process_cmdline = Trim(process_cmdline);
    267     } else {
    268         process_cmdline = "unknown process";
    269     }
    270 
    271     LOG(INFO) << "Received control message '" << msg << "' for '" << name << "' from pid: " << pid
    272               << " (" << process_cmdline << ")";
    273 
    274     const ControlMessageFunction& function = it->second;
    275 
    276     if (function.target == ControlTarget::SERVICE) {
    277         Service* svc = ServiceList::GetInstance().FindService(name);
    278         if (svc == nullptr) {
    279             LOG(ERROR) << "No such service '" << name << "' for ctl." << msg;
    280             return;
    281         }
    282         if (auto result = function.action(svc); !result) {
    283             LOG(ERROR) << "Could not ctl." << msg << " for service " << name << ": "
    284                        << result.error();
    285         }
    286 
    287         return;
    288     }
    289 
    290     if (function.target == ControlTarget::INTERFACE) {
    291         for (const auto& svc : ServiceList::GetInstance()) {
    292             if (svc->interfaces().count(name) == 0) {
    293                 continue;
    294             }
    295 
    296             if (auto result = function.action(svc.get()); !result) {
    297                 LOG(ERROR) << "Could not handle ctl." << msg << " for service " << svc->name()
    298                            << " with interface " << name << ": " << result.error();
    299             }
    300 
    301             return;
    302         }
    303 
    304         LOG(ERROR) << "Could not find service hosting interface " << name;
    305         return;
    306     }
    307 
    308     LOG(ERROR) << "Invalid function target from static map key '" << msg
    309                << "': " << static_cast<std::underlying_type<ControlTarget>::type>(function.target);
    310 }
    311 
    312 static Result<Success> wait_for_coldboot_done_action(const BuiltinArguments& args) {
    313     Timer t;
    314 
    315     LOG(VERBOSE) << "Waiting for " COLDBOOT_DONE "...";
    316 
    317     // Historically we had a 1s timeout here because we weren't otherwise
    318     // tracking boot time, and many OEMs made their sepolicy regular
    319     // expressions too expensive (http://b/19899875).
    320 
    321     // Now we're tracking boot time, just log the time taken to a system
    322     // property. We still panic if it takes more than a minute though,
    323     // because any build that slow isn't likely to boot at all, and we'd
    324     // rather any test lab devices fail back to the bootloader.
    325     if (wait_for_file(COLDBOOT_DONE, 60s) < 0) {
    326         LOG(FATAL) << "Timed out waiting for " COLDBOOT_DONE;
    327     }
    328 
    329     property_set("ro.boottime.init.cold_boot_wait", std::to_string(t.duration().count()));
    330     return Success();
    331 }
    332 
    333 static Result<Success> keychord_init_action(const BuiltinArguments& args) {
    334     keychord_init();
    335     return Success();
    336 }
    337 
    338 static Result<Success> console_init_action(const BuiltinArguments& args) {
    339     std::string console = GetProperty("ro.boot.console", "");
    340     if (!console.empty()) {
    341         default_console = "/dev/" + console;
    342     }
    343     return Success();
    344 }
    345 
    346 static void import_kernel_nv(const std::string& key, const std::string& value, bool for_emulator) {
    347     if (key.empty()) return;
    348 
    349     if (for_emulator) {
    350         // In the emulator, export any kernel option with the "ro.kernel." prefix.
    351         property_set("ro.kernel." + key, value);
    352         return;
    353     }
    354 
    355     if (key == "qemu") {
    356         strlcpy(qemu, value.c_str(), sizeof(qemu));
    357     } else if (android::base::StartsWith(key, "androidboot.")) {
    358         property_set("ro.boot." + key.substr(12), value);
    359     }
    360 }
    361 
    362 static void export_oem_lock_status() {
    363     if (!android::base::GetBoolProperty("ro.oem_unlock_supported", false)) {
    364         return;
    365     }
    366 
    367     std::string value = GetProperty("ro.boot.verifiedbootstate", "");
    368 
    369     if (!value.empty()) {
    370         property_set("ro.boot.flash.locked", value == "orange" ? "0" : "1");
    371     }
    372 }
    373 
    374 static void export_kernel_boot_props() {
    375     struct {
    376         const char *src_prop;
    377         const char *dst_prop;
    378         const char *default_value;
    379     } prop_map[] = {
    380         { "ro.boot.serialno",   "ro.serialno",   "", },
    381         { "ro.boot.mode",       "ro.bootmode",   "unknown", },
    382         { "ro.boot.baseband",   "ro.baseband",   "unknown", },
    383         { "ro.boot.bootloader", "ro.bootloader", "unknown", },
    384         { "ro.boot.hardware",   "ro.hardware",   "unknown", },
    385         { "ro.boot.revision",   "ro.revision",   "0", },
    386     };
    387     for (size_t i = 0; i < arraysize(prop_map); i++) {
    388         std::string value = GetProperty(prop_map[i].src_prop, "");
    389         property_set(prop_map[i].dst_prop, (!value.empty()) ? value : prop_map[i].default_value);
    390     }
    391 }
    392 
    393 static void process_kernel_dt() {
    394     if (!is_android_dt_value_expected("compatible", "android,firmware")) {
    395         return;
    396     }
    397 
    398     std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(get_android_dt_dir().c_str()), closedir);
    399     if (!dir) return;
    400 
    401     std::string dt_file;
    402     struct dirent *dp;
    403     while ((dp = readdir(dir.get())) != NULL) {
    404         if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") || !strcmp(dp->d_name, "name")) {
    405             continue;
    406         }
    407 
    408         std::string file_name = get_android_dt_dir() + dp->d_name;
    409 
    410         android::base::ReadFileToString(file_name, &dt_file);
    411         std::replace(dt_file.begin(), dt_file.end(), ',', '.');
    412 
    413         property_set("ro.boot."s + dp->d_name, dt_file);
    414     }
    415 }
    416 
    417 static void process_kernel_cmdline() {
    418     // The first pass does the common stuff, and finds if we are in qemu.
    419     // The second pass is only necessary for qemu to export all kernel params
    420     // as properties.
    421     import_kernel_cmdline(false, import_kernel_nv);
    422     if (qemu[0]) import_kernel_cmdline(true, import_kernel_nv);
    423 }
    424 
    425 static Result<Success> property_enable_triggers_action(const BuiltinArguments& args) {
    426     /* Enable property triggers. */
    427     property_triggers_enabled = 1;
    428     return Success();
    429 }
    430 
    431 static Result<Success> queue_property_triggers_action(const BuiltinArguments& args) {
    432     ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger");
    433     ActionManager::GetInstance().QueueAllPropertyActions();
    434     return Success();
    435 }
    436 
    437 static void global_seccomp() {
    438     import_kernel_cmdline(false, [](const std::string& key, const std::string& value, bool in_qemu) {
    439         if (key == "androidboot.seccomp" && value == "global" && !set_global_seccomp_filter()) {
    440             LOG(FATAL) << "Failed to globally enable seccomp!";
    441         }
    442     });
    443 }
    444 
    445 // Set the UDC controller for the ConfigFS USB Gadgets.
    446 // Read the UDC controller in use from "/sys/class/udc".
    447 // In case of multiple UDC controllers select the first one.
    448 static void set_usb_controller() {
    449     std::unique_ptr<DIR, decltype(&closedir)>dir(opendir("/sys/class/udc"), closedir);
    450     if (!dir) return;
    451 
    452     dirent* dp;
    453     while ((dp = readdir(dir.get())) != nullptr) {
    454         if (dp->d_name[0] == '.') continue;
    455 
    456         property_set("sys.usb.controller", dp->d_name);
    457         break;
    458     }
    459 }
    460 
    461 static void InstallRebootSignalHandlers() {
    462     // Instead of panic'ing the kernel as is the default behavior when init crashes,
    463     // we prefer to reboot to bootloader on development builds, as this will prevent
    464     // boot looping bad configurations and allow both developers and test farms to easily
    465     // recover.
    466     struct sigaction action;
    467     memset(&action, 0, sizeof(action));
    468     sigfillset(&action.sa_mask);
    469     action.sa_handler = [](int signal) {
    470         // These signal handlers are also caught for processes forked from init, however we do not
    471         // want them to trigger reboot, so we directly call _exit() for children processes here.
    472         if (getpid() != 1) {
    473             _exit(signal);
    474         }
    475 
    476         // Calling DoReboot() or LOG(FATAL) is not a good option as this is a signal handler.
    477         // RebootSystem uses syscall() which isn't actually async-signal-safe, but our only option
    478         // and probably good enough given this is already an error case and only enabled for
    479         // development builds.
    480         RebootSystem(ANDROID_RB_RESTART2, "bootloader");
    481     };
    482     action.sa_flags = SA_RESTART;
    483     sigaction(SIGABRT, &action, nullptr);
    484     sigaction(SIGBUS, &action, nullptr);
    485     sigaction(SIGFPE, &action, nullptr);
    486     sigaction(SIGILL, &action, nullptr);
    487     sigaction(SIGSEGV, &action, nullptr);
    488 #if defined(SIGSTKFLT)
    489     sigaction(SIGSTKFLT, &action, nullptr);
    490 #endif
    491     sigaction(SIGSYS, &action, nullptr);
    492     sigaction(SIGTRAP, &action, nullptr);
    493 }
    494 
    495 static void HandleSigtermSignal() {
    496     signalfd_siginfo siginfo;
    497     ssize_t bytes_read = TEMP_FAILURE_RETRY(read(sigterm_signal_fd, &siginfo, sizeof(siginfo)));
    498     if (bytes_read != sizeof(siginfo)) {
    499         PLOG(ERROR) << "Failed to read siginfo from sigterm_signal_fd";
    500         return;
    501     }
    502 
    503     if (siginfo.ssi_pid != 0) {
    504         // Drop any userspace SIGTERM requests.
    505         LOG(DEBUG) << "Ignoring SIGTERM from pid " << siginfo.ssi_pid;
    506         return;
    507     }
    508 
    509     HandlePowerctlMessage("shutdown,container");
    510 }
    511 
    512 static void UnblockSigterm() {
    513     sigset_t mask;
    514     sigemptyset(&mask);
    515     sigaddset(&mask, SIGTERM);
    516 
    517     if (sigprocmask(SIG_UNBLOCK, &mask, nullptr) == -1) {
    518         PLOG(FATAL) << "failed to unblock SIGTERM for PID " << getpid();
    519     }
    520 }
    521 
    522 static void InstallSigtermHandler() {
    523     sigset_t mask;
    524     sigemptyset(&mask);
    525     sigaddset(&mask, SIGTERM);
    526 
    527     if (sigprocmask(SIG_BLOCK, &mask, nullptr) == -1) {
    528         PLOG(FATAL) << "failed to block SIGTERM";
    529     }
    530 
    531     // Register a handler to unblock SIGTERM in the child processes.
    532     const int result = pthread_atfork(nullptr, nullptr, &UnblockSigterm);
    533     if (result != 0) {
    534         LOG(FATAL) << "Failed to register a fork handler: " << strerror(result);
    535     }
    536 
    537     sigterm_signal_fd = signalfd(-1, &mask, SFD_CLOEXEC);
    538     if (sigterm_signal_fd == -1) {
    539         PLOG(FATAL) << "failed to create signalfd for SIGTERM";
    540     }
    541 
    542     register_epoll_handler(sigterm_signal_fd, HandleSigtermSignal);
    543 }
    544 
    545 int main(int argc, char** argv) {
    546     if (!strcmp(basename(argv[0]), "ueventd")) {
    547         return ueventd_main(argc, argv);
    548     }
    549 
    550     if (!strcmp(basename(argv[0]), "watchdogd")) {
    551         return watchdogd_main(argc, argv);
    552     }
    553 
    554     if (argc > 1 && !strcmp(argv[1], "subcontext")) {
    555         InitKernelLogging(argv);
    556         const BuiltinFunctionMap function_map;
    557         return SubcontextMain(argc, argv, &function_map);
    558     }
    559 
    560     if (REBOOT_BOOTLOADER_ON_PANIC) {
    561         InstallRebootSignalHandlers();
    562     }
    563 
    564     bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr);
    565 
    566     if (is_first_stage) {
    567         boot_clock::time_point start_time = boot_clock::now();
    568 
    569         // Clear the umask.
    570         umask(0);
    571 
    572         clearenv();
    573         setenv("PATH", _PATH_DEFPATH, 1);
    574         // Get the basic filesystem setup we need put together in the initramdisk
    575         // on / and then we'll let the rc file figure out the rest.
    576         mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
    577         mkdir("/dev/pts", 0755);
    578         mkdir("/dev/socket", 0755);
    579         mount("devpts", "/dev/pts", "devpts", 0, NULL);
    580         #define MAKE_STR(x) __STRING(x)
    581         mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC));
    582         // Don't expose the raw commandline to unprivileged processes.
    583         chmod("/proc/cmdline", 0440);
    584         gid_t groups[] = { AID_READPROC };
    585         setgroups(arraysize(groups), groups);
    586         mount("sysfs", "/sys", "sysfs", 0, NULL);
    587         mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL);
    588 
    589         mknod("/dev/kmsg", S_IFCHR | 0600, makedev(1, 11));
    590 
    591         if constexpr (WORLD_WRITABLE_KMSG) {
    592             mknod("/dev/kmsg_debug", S_IFCHR | 0622, makedev(1, 11));
    593         }
    594 
    595         mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8));
    596         mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9));
    597 
    598         // Mount staging areas for devices managed by vold
    599         // See storage config details at http://source.android.com/devices/storage/
    600         mount("tmpfs", "/mnt", "tmpfs", MS_NOEXEC | MS_NOSUID | MS_NODEV,
    601               "mode=0755,uid=0,gid=1000");
    602         // /mnt/vendor is used to mount vendor-specific partitions that can not be
    603         // part of the vendor partition, e.g. because they are mounted read-write.
    604         mkdir("/mnt/vendor", 0755);
    605 
    606         // Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually
    607         // talk to the outside world...
    608         InitKernelLogging(argv);
    609 
    610         LOG(INFO) << "init first stage started!";
    611 
    612         if (!DoFirstStageMount()) {
    613             LOG(FATAL) << "Failed to mount required partitions early ...";
    614         }
    615 
    616         SetInitAvbVersionInRecovery();
    617 
    618         // Enable seccomp if global boot option was passed (otherwise it is enabled in zygote).
    619         global_seccomp();
    620 
    621         // Set up SELinux, loading the SELinux policy.
    622         SelinuxSetupKernelLogging();
    623         SelinuxInitialize();
    624 
    625         // We're in the kernel domain, so re-exec init to transition to the init domain now
    626         // that the SELinux policy has been loaded.
    627         if (selinux_android_restorecon("/init", 0) == -1) {
    628             PLOG(FATAL) << "restorecon failed of /init failed";
    629         }
    630 
    631         setenv("INIT_SECOND_STAGE", "true", 1);
    632 
    633         static constexpr uint32_t kNanosecondsPerMillisecond = 1e6;
    634         uint64_t start_ms = start_time.time_since_epoch().count() / kNanosecondsPerMillisecond;
    635         setenv("INIT_STARTED_AT", std::to_string(start_ms).c_str(), 1);
    636 
    637         char* path = argv[0];
    638         char* args[] = { path, nullptr };
    639         execv(path, args);
    640 
    641         // execv() only returns if an error happened, in which case we
    642         // panic and never fall through this conditional.
    643         PLOG(FATAL) << "execv(\"" << path << "\") failed";
    644     }
    645 
    646     // At this point we're in the second stage of init.
    647     InitKernelLogging(argv);
    648     LOG(INFO) << "init second stage started!";
    649 
    650     // Set up a session keyring that all processes will have access to. It
    651     // will hold things like FBE encryption keys. No process should override
    652     // its session keyring.
    653     keyctl_get_keyring_ID(KEY_SPEC_SESSION_KEYRING, 1);
    654 
    655     // Indicate that booting is in progress to background fw loaders, etc.
    656     close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
    657 
    658     property_init();
    659 
    660     // If arguments are passed both on the command line and in DT,
    661     // properties set in DT always have priority over the command-line ones.
    662     process_kernel_dt();
    663     process_kernel_cmdline();
    664 
    665     // Propagate the kernel variables to internal variables
    666     // used by init as well as the current required properties.
    667     export_kernel_boot_props();
    668 
    669     // Make the time that init started available for bootstat to log.
    670     property_set("ro.boottime.init", getenv("INIT_STARTED_AT"));
    671     property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK"));
    672 
    673     // Set libavb version for Framework-only OTA match in Treble build.
    674     const char* avb_version = getenv("INIT_AVB_VERSION");
    675     if (avb_version) property_set("ro.boot.avb_version", avb_version);
    676 
    677     // Clean up our environment.
    678     unsetenv("INIT_SECOND_STAGE");
    679     unsetenv("INIT_STARTED_AT");
    680     unsetenv("INIT_SELINUX_TOOK");
    681     unsetenv("INIT_AVB_VERSION");
    682 
    683     // Now set up SELinux for second stage.
    684     SelinuxSetupKernelLogging();
    685     SelabelInitialize();
    686     SelinuxRestoreContext();
    687 
    688     epoll_fd = epoll_create1(EPOLL_CLOEXEC);
    689     if (epoll_fd == -1) {
    690         PLOG(FATAL) << "epoll_create1 failed";
    691     }
    692 
    693     sigchld_handler_init();
    694 
    695     if (!IsRebootCapable()) {
    696         // If init does not have the CAP_SYS_BOOT capability, it is running in a container.
    697         // In that case, receiving SIGTERM will cause the system to shut down.
    698         InstallSigtermHandler();
    699     }
    700 
    701     property_load_boot_defaults();
    702     export_oem_lock_status();
    703     start_property_service();
    704     set_usb_controller();
    705 
    706     const BuiltinFunctionMap function_map;
    707     Action::set_function_map(&function_map);
    708 
    709     subcontexts = InitializeSubcontexts();
    710 
    711     ActionManager& am = ActionManager::GetInstance();
    712     ServiceList& sm = ServiceList::GetInstance();
    713 
    714     LoadBootScripts(am, sm);
    715 
    716     // Turning this on and letting the INFO logging be discarded adds 0.2s to
    717     // Nexus 9 boot time, so it's disabled by default.
    718     if (false) DumpState();
    719 
    720     am.QueueEventTrigger("early-init");
    721 
    722     // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev...
    723     am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
    724     // ... so that we can start queuing up actions that require stuff from /dev.
    725     am.QueueBuiltinAction(MixHwrngIntoLinuxRngAction, "MixHwrngIntoLinuxRng");
    726     am.QueueBuiltinAction(SetMmapRndBitsAction, "SetMmapRndBits");
    727     am.QueueBuiltinAction(SetKptrRestrictAction, "SetKptrRestrict");
    728     am.QueueBuiltinAction(keychord_init_action, "keychord_init");
    729     am.QueueBuiltinAction(console_init_action, "console_init");
    730 
    731     // Trigger all the boot actions to get us started.
    732     am.QueueEventTrigger("init");
    733 
    734     // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
    735     // wasn't ready immediately after wait_for_coldboot_done
    736     am.QueueBuiltinAction(MixHwrngIntoLinuxRngAction, "MixHwrngIntoLinuxRng");
    737 
    738     // Don't mount filesystems or start core system services in charger mode.
    739     std::string bootmode = GetProperty("ro.bootmode", "");
    740     if (bootmode == "charger") {
    741         am.QueueEventTrigger("charger");
    742     } else {
    743         am.QueueEventTrigger("late-init");
    744     }
    745 
    746     // Run all property triggers based on current state of the properties.
    747     am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
    748 
    749     while (true) {
    750         // By default, sleep until something happens.
    751         int epoll_timeout_ms = -1;
    752 
    753         if (do_shutdown && !shutting_down) {
    754             do_shutdown = false;
    755             if (HandlePowerctlMessage(shutdown_command)) {
    756                 shutting_down = true;
    757             }
    758         }
    759 
    760         if (!(waiting_for_prop || Service::is_exec_service_running())) {
    761             am.ExecuteOneCommand();
    762         }
    763         if (!(waiting_for_prop || Service::is_exec_service_running())) {
    764             if (!shutting_down) {
    765                 auto next_process_restart_time = RestartProcesses();
    766 
    767                 // If there's a process that needs restarting, wake up in time for that.
    768                 if (next_process_restart_time) {
    769                     epoll_timeout_ms = std::chrono::ceil<std::chrono::milliseconds>(
    770                                            *next_process_restart_time - boot_clock::now())
    771                                            .count();
    772                     if (epoll_timeout_ms < 0) epoll_timeout_ms = 0;
    773                 }
    774             }
    775 
    776             // If there's more work to do, wake up again immediately.
    777             if (am.HasMoreCommands()) epoll_timeout_ms = 0;
    778         }
    779 
    780         epoll_event ev;
    781         int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, epoll_timeout_ms));
    782         if (nr == -1) {
    783             PLOG(ERROR) << "epoll_wait failed";
    784         } else if (nr == 1) {
    785             ((void (*)()) ev.data.ptr)();
    786         }
    787     }
    788 
    789     return 0;
    790 }
    791 
    792 }  // namespace init
    793 }  // namespace android
    794