• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <pthread.h>
22 #include <seccomp_policy.h>
23 #include <signal.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/mount.h>
27 #include <sys/signalfd.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30 
31 #include <map>
32 #include <memory>
33 #include <optional>
34 
35 #include <android-base/chrono_utils.h>
36 #include <android-base/file.h>
37 #include <android-base/logging.h>
38 #include <android-base/properties.h>
39 #include <android-base/stringprintf.h>
40 #include <android-base/strings.h>
41 #include <fs_avb/fs_avb.h>
42 #include <fs_mgr_vendor_overlay.h>
43 #include <keyutils.h>
44 #include <libavb/libavb.h>
45 #include <libgsi/libgsi.h>
46 #include <processgroup/processgroup.h>
47 #include <processgroup/setup.h>
48 #include <selinux/android.h>
49 
50 #ifndef RECOVERY
51 #include <binder/ProcessState.h>
52 #endif
53 
54 #include "action_parser.h"
55 #include "boringssl_self_test.h"
56 #include "epoll.h"
57 #include "first_stage_mount.h"
58 #include "import_parser.h"
59 #include "keychords.h"
60 #include "mount_handler.h"
61 #include "mount_namespace.h"
62 #include "property_service.h"
63 #include "reboot.h"
64 #include "reboot_utils.h"
65 #include "security.h"
66 #include "selinux.h"
67 #include "sigchld_handler.h"
68 #include "util.h"
69 
70 using namespace std::chrono_literals;
71 using namespace std::string_literals;
72 
73 using android::base::boot_clock;
74 using android::base::GetProperty;
75 using android::base::ReadFileToString;
76 using android::base::StringPrintf;
77 using android::base::Timer;
78 using android::base::Trim;
79 using android::fs_mgr::AvbHandle;
80 
81 namespace android {
82 namespace init {
83 
84 static int property_triggers_enabled = 0;
85 
86 static char qemu[32];
87 
88 std::string default_console = "/dev/console";
89 
90 static int signal_fd = -1;
91 
92 static std::unique_ptr<Timer> waiting_for_prop(nullptr);
93 static std::string wait_prop_name;
94 static std::string wait_prop_value;
95 static bool shutting_down;
96 static std::string shutdown_command;
97 static bool do_shutdown = false;
98 static bool load_debug_prop = false;
99 
100 std::vector<std::string> late_import_paths;
101 
102 static std::vector<Subcontext>* subcontexts;
103 
DumpState()104 void DumpState() {
105     ServiceList::GetInstance().DumpState();
106     ActionManager::GetInstance().DumpState();
107 }
108 
CreateParser(ActionManager & action_manager,ServiceList & service_list)109 Parser CreateParser(ActionManager& action_manager, ServiceList& service_list) {
110     Parser parser;
111 
112     parser.AddSectionParser("service", std::make_unique<ServiceParser>(&service_list, subcontexts));
113     parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, subcontexts));
114     parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
115 
116     return parser;
117 }
118 
119 // parser that only accepts new services
CreateServiceOnlyParser(ServiceList & service_list)120 Parser CreateServiceOnlyParser(ServiceList& service_list) {
121     Parser parser;
122 
123     parser.AddSectionParser("service", std::make_unique<ServiceParser>(&service_list, subcontexts));
124     return parser;
125 }
126 
LoadBootScripts(ActionManager & action_manager,ServiceList & service_list)127 static void LoadBootScripts(ActionManager& action_manager, ServiceList& service_list) {
128     Parser parser = CreateParser(action_manager, service_list);
129 
130     std::string bootscript = GetProperty("ro.boot.init_rc", "");
131     if (bootscript.empty()) {
132         parser.ParseConfig("/init.rc");
133         if (!parser.ParseConfig("/system/etc/init")) {
134             late_import_paths.emplace_back("/system/etc/init");
135         }
136         if (!parser.ParseConfig("/product/etc/init")) {
137             late_import_paths.emplace_back("/product/etc/init");
138         }
139         if (!parser.ParseConfig("/product_services/etc/init")) {
140             late_import_paths.emplace_back("/product_services/etc/init");
141         }
142         if (!parser.ParseConfig("/odm/etc/init")) {
143             late_import_paths.emplace_back("/odm/etc/init");
144         }
145         if (!parser.ParseConfig("/vendor/etc/init")) {
146             late_import_paths.emplace_back("/vendor/etc/init");
147         }
148     } else {
149         parser.ParseConfig(bootscript);
150     }
151 }
152 
start_waiting_for_property(const char * name,const char * value)153 bool start_waiting_for_property(const char *name, const char *value)
154 {
155     if (waiting_for_prop) {
156         return false;
157     }
158     if (GetProperty(name, "") != value) {
159         // Current property value is not equal to expected value
160         wait_prop_name = name;
161         wait_prop_value = value;
162         waiting_for_prop.reset(new Timer());
163     } else {
164         LOG(INFO) << "start_waiting_for_property(\""
165                   << name << "\", \"" << value << "\"): already set";
166     }
167     return true;
168 }
169 
ResetWaitForProp()170 void ResetWaitForProp() {
171     wait_prop_name.clear();
172     wait_prop_value.clear();
173     waiting_for_prop.reset();
174 }
175 
property_changed(const std::string & name,const std::string & value)176 void property_changed(const std::string& name, const std::string& value) {
177     // If the property is sys.powerctl, we bypass the event queue and immediately handle it.
178     // This is to ensure that init will always and immediately shutdown/reboot, regardless of
179     // if there are other pending events to process or if init is waiting on an exec service or
180     // waiting on a property.
181     // In non-thermal-shutdown case, 'shutdown' trigger will be fired to let device specific
182     // commands to be executed.
183     if (name == "sys.powerctl") {
184         // Despite the above comment, we can't call HandlePowerctlMessage() in this function,
185         // because it modifies the contents of the action queue, which can cause the action queue
186         // to get into a bad state if this function is called from a command being executed by the
187         // action queue.  Instead we set this flag and ensure that shutdown happens before the next
188         // command is run in the main init loop.
189         // TODO: once property service is removed from init, this will never happen from a builtin,
190         // but rather from a callback from the property service socket, in which case this hack can
191         // go away.
192         shutdown_command = value;
193         do_shutdown = true;
194     }
195 
196     if (property_triggers_enabled) ActionManager::GetInstance().QueuePropertyChange(name, value);
197 
198     if (waiting_for_prop) {
199         if (wait_prop_name == name && wait_prop_value == value) {
200             LOG(INFO) << "Wait for property '" << wait_prop_name << "=" << wait_prop_value
201                       << "' took " << *waiting_for_prop;
202             ResetWaitForProp();
203         }
204     }
205 }
206 
HandleProcessActions()207 static std::optional<boot_clock::time_point> HandleProcessActions() {
208     std::optional<boot_clock::time_point> next_process_action_time;
209     for (const auto& s : ServiceList::GetInstance()) {
210         if ((s->flags() & SVC_RUNNING) && s->timeout_period()) {
211             auto timeout_time = s->time_started() + *s->timeout_period();
212             if (boot_clock::now() > timeout_time) {
213                 s->Timeout();
214             } else {
215                 if (!next_process_action_time || timeout_time < *next_process_action_time) {
216                     next_process_action_time = timeout_time;
217                 }
218             }
219         }
220 
221         if (!(s->flags() & SVC_RESTARTING)) continue;
222 
223         auto restart_time = s->time_started() + s->restart_period();
224         if (boot_clock::now() > restart_time) {
225             if (auto result = s->Start(); !result) {
226                 LOG(ERROR) << "Could not restart process '" << s->name() << "': " << result.error();
227             }
228         } else {
229             if (!next_process_action_time || restart_time < *next_process_action_time) {
230                 next_process_action_time = restart_time;
231             }
232         }
233     }
234     return next_process_action_time;
235 }
236 
DoControlStart(Service * service)237 static Result<Success> DoControlStart(Service* service) {
238     return service->Start();
239 }
240 
DoControlStop(Service * service)241 static Result<Success> DoControlStop(Service* service) {
242     service->Stop();
243     return Success();
244 }
245 
DoControlRestart(Service * service)246 static Result<Success> DoControlRestart(Service* service) {
247     service->Restart();
248     return Success();
249 }
250 
251 enum class ControlTarget {
252     SERVICE,    // function gets called for the named service
253     INTERFACE,  // action gets called for every service that holds this interface
254 };
255 
256 struct ControlMessageFunction {
257     ControlTarget target;
258     std::function<Result<Success>(Service*)> action;
259 };
260 
get_control_message_map()261 static const std::map<std::string, ControlMessageFunction>& get_control_message_map() {
262     // clang-format off
263     static const std::map<std::string, ControlMessageFunction> control_message_functions = {
264         {"sigstop_on",        {ControlTarget::SERVICE,
265                                [](auto* service) { service->set_sigstop(true); return Success(); }}},
266         {"sigstop_off",       {ControlTarget::SERVICE,
267                                [](auto* service) { service->set_sigstop(false); return Success(); }}},
268         {"start",             {ControlTarget::SERVICE,   DoControlStart}},
269         {"stop",              {ControlTarget::SERVICE,   DoControlStop}},
270         {"restart",           {ControlTarget::SERVICE,   DoControlRestart}},
271         {"interface_start",   {ControlTarget::INTERFACE, DoControlStart}},
272         {"interface_stop",    {ControlTarget::INTERFACE, DoControlStop}},
273         {"interface_restart", {ControlTarget::INTERFACE, DoControlRestart}},
274     };
275     // clang-format on
276 
277     return control_message_functions;
278 }
279 
HandleControlMessage(const std::string & msg,const std::string & name,pid_t pid)280 void HandleControlMessage(const std::string& msg, const std::string& name, pid_t pid) {
281     const auto& map = get_control_message_map();
282     const auto it = map.find(msg);
283 
284     if (it == map.end()) {
285         LOG(ERROR) << "Unknown control msg '" << msg << "'";
286         return;
287     }
288 
289     std::string cmdline_path = StringPrintf("proc/%d/cmdline", pid);
290     std::string process_cmdline;
291     if (ReadFileToString(cmdline_path, &process_cmdline)) {
292         std::replace(process_cmdline.begin(), process_cmdline.end(), '\0', ' ');
293         process_cmdline = Trim(process_cmdline);
294     } else {
295         process_cmdline = "unknown process";
296     }
297 
298     LOG(INFO) << "Received control message '" << msg << "' for '" << name << "' from pid: " << pid
299               << " (" << process_cmdline << ")";
300 
301     const ControlMessageFunction& function = it->second;
302 
303     Service* svc = nullptr;
304 
305     switch (function.target) {
306         case ControlTarget::SERVICE:
307             svc = ServiceList::GetInstance().FindService(name);
308             break;
309         case ControlTarget::INTERFACE:
310             svc = ServiceList::GetInstance().FindInterface(name);
311             break;
312         default:
313             LOG(ERROR) << "Invalid function target from static map key '" << msg << "': "
314                        << static_cast<std::underlying_type<ControlTarget>::type>(function.target);
315             return;
316     }
317 
318     if (svc == nullptr) {
319         LOG(ERROR) << "Could not find '" << name << "' for ctl." << msg;
320         return;
321     }
322 
323     if (auto result = function.action(svc); !result) {
324         LOG(ERROR) << "Could not ctl." << msg << " for '" << name << "': " << result.error();
325     }
326 }
327 
wait_for_coldboot_done_action(const BuiltinArguments & args)328 static Result<Success> wait_for_coldboot_done_action(const BuiltinArguments& args) {
329     Timer t;
330 
331     LOG(VERBOSE) << "Waiting for " COLDBOOT_DONE "...";
332 
333     // Historically we had a 1s timeout here because we weren't otherwise
334     // tracking boot time, and many OEMs made their sepolicy regular
335     // expressions too expensive (http://b/19899875).
336 
337     // Now we're tracking boot time, just log the time taken to a system
338     // property. We still panic if it takes more than a minute though,
339     // because any build that slow isn't likely to boot at all, and we'd
340     // rather any test lab devices fail back to the bootloader.
341     if (wait_for_file(COLDBOOT_DONE, 60s) < 0) {
342         LOG(FATAL) << "Timed out waiting for " COLDBOOT_DONE;
343     }
344 
345     property_set("ro.boottime.init.cold_boot_wait", std::to_string(t.duration().count()));
346     return Success();
347 }
348 
console_init_action(const BuiltinArguments & args)349 static Result<Success> console_init_action(const BuiltinArguments& args) {
350     std::string console = GetProperty("ro.boot.console", "");
351     if (!console.empty()) {
352         default_console = "/dev/" + console;
353     }
354     return Success();
355 }
356 
SetupCgroupsAction(const BuiltinArguments &)357 static Result<Success> SetupCgroupsAction(const BuiltinArguments&) {
358     // Have to create <CGROUPS_RC_DIR> using make_dir function
359     // for appropriate sepolicy to be set for it
360     make_dir(android::base::Dirname(CGROUPS_RC_PATH), 0711);
361     if (!CgroupSetup()) {
362         return ErrnoError() << "Failed to setup cgroups";
363     }
364 
365     return Success();
366 }
367 
import_kernel_nv(const std::string & key,const std::string & value,bool for_emulator)368 static void import_kernel_nv(const std::string& key, const std::string& value, bool for_emulator) {
369     if (key.empty()) return;
370 
371     if (for_emulator) {
372         // In the emulator, export any kernel option with the "ro.kernel." prefix.
373         property_set("ro.kernel." + key, value);
374         return;
375     }
376 
377     if (key == "qemu") {
378         strlcpy(qemu, value.c_str(), sizeof(qemu));
379     } else if (android::base::StartsWith(key, "androidboot.")) {
380         property_set("ro.boot." + key.substr(12), value);
381     }
382 }
383 
export_oem_lock_status()384 static void export_oem_lock_status() {
385     if (!android::base::GetBoolProperty("ro.oem_unlock_supported", false)) {
386         return;
387     }
388     import_kernel_cmdline(
389             false, [](const std::string& key, const std::string& value, bool in_qemu) {
390                 if (key == "androidboot.verifiedbootstate") {
391                     property_set("ro.boot.flash.locked", value == "orange" ? "0" : "1");
392                 }
393             });
394 }
395 
export_kernel_boot_props()396 static void export_kernel_boot_props() {
397     constexpr const char* UNSET = "";
398     struct {
399         const char *src_prop;
400         const char *dst_prop;
401         const char *default_value;
402     } prop_map[] = {
403         { "ro.boot.serialno",   "ro.serialno",   UNSET, },
404         { "ro.boot.mode",       "ro.bootmode",   "unknown", },
405         { "ro.boot.baseband",   "ro.baseband",   "unknown", },
406         { "ro.boot.bootloader", "ro.bootloader", "unknown", },
407         { "ro.boot.hardware",   "ro.hardware",   "unknown", },
408         { "ro.boot.revision",   "ro.revision",   "0", },
409     };
410     for (const auto& prop : prop_map) {
411         std::string value = GetProperty(prop.src_prop, prop.default_value);
412         if (value != UNSET)
413             property_set(prop.dst_prop, value);
414     }
415 }
416 
process_kernel_dt()417 static void process_kernel_dt() {
418     if (!is_android_dt_value_expected("compatible", "android,firmware")) {
419         return;
420     }
421 
422     std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(get_android_dt_dir().c_str()), closedir);
423     if (!dir) return;
424 
425     std::string dt_file;
426     struct dirent *dp;
427     while ((dp = readdir(dir.get())) != NULL) {
428         if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") || !strcmp(dp->d_name, "name")) {
429             continue;
430         }
431 
432         std::string file_name = get_android_dt_dir() + dp->d_name;
433 
434         android::base::ReadFileToString(file_name, &dt_file);
435         std::replace(dt_file.begin(), dt_file.end(), ',', '.');
436 
437         property_set("ro.boot."s + dp->d_name, dt_file);
438     }
439 }
440 
process_kernel_cmdline()441 static void process_kernel_cmdline() {
442     // The first pass does the common stuff, and finds if we are in qemu.
443     // The second pass is only necessary for qemu to export all kernel params
444     // as properties.
445     import_kernel_cmdline(false, import_kernel_nv);
446     if (qemu[0]) import_kernel_cmdline(true, import_kernel_nv);
447 }
448 
property_enable_triggers_action(const BuiltinArguments & args)449 static Result<Success> property_enable_triggers_action(const BuiltinArguments& args) {
450     /* Enable property triggers. */
451     property_triggers_enabled = 1;
452     return Success();
453 }
454 
queue_property_triggers_action(const BuiltinArguments & args)455 static Result<Success> queue_property_triggers_action(const BuiltinArguments& args) {
456     ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger");
457     ActionManager::GetInstance().QueueAllPropertyActions();
458     return Success();
459 }
460 
InitBinder(const BuiltinArguments & args)461 static Result<Success> InitBinder(const BuiltinArguments& args) {
462     // init's use of binder is very limited. init cannot:
463     //   - have any binder threads
464     //   - receive incoming binder calls
465     //   - pass local binder services to remote processes
466     //   - use death recipients
467     // The main supported usecases are:
468     //   - notifying other daemons (oneway calls only)
469     //   - retrieving data that is necessary to boot
470     // Also, binder can't be used by recovery.
471 #ifndef RECOVERY
472     android::ProcessState::self()->setThreadPoolMaxThreadCount(0);
473     android::ProcessState::self()->setCallRestriction(
474             ProcessState::CallRestriction::ERROR_IF_NOT_ONEWAY);
475 #endif
476     return Success();
477 }
478 
479 // Set the UDC controller for the ConfigFS USB Gadgets.
480 // Read the UDC controller in use from "/sys/class/udc".
481 // In case of multiple UDC controllers select the first one.
set_usb_controller()482 static void set_usb_controller() {
483     std::unique_ptr<DIR, decltype(&closedir)>dir(opendir("/sys/class/udc"), closedir);
484     if (!dir) return;
485 
486     dirent* dp;
487     while ((dp = readdir(dir.get())) != nullptr) {
488         if (dp->d_name[0] == '.') continue;
489 
490         property_set("sys.usb.controller", dp->d_name);
491         break;
492     }
493 }
494 
HandleSigtermSignal(const signalfd_siginfo & siginfo)495 static void HandleSigtermSignal(const signalfd_siginfo& siginfo) {
496     if (siginfo.ssi_pid != 0) {
497         // Drop any userspace SIGTERM requests.
498         LOG(DEBUG) << "Ignoring SIGTERM from pid " << siginfo.ssi_pid;
499         return;
500     }
501 
502     HandlePowerctlMessage("shutdown,container");
503 }
504 
HandleSignalFd()505 static void HandleSignalFd() {
506     signalfd_siginfo siginfo;
507     ssize_t bytes_read = TEMP_FAILURE_RETRY(read(signal_fd, &siginfo, sizeof(siginfo)));
508     if (bytes_read != sizeof(siginfo)) {
509         PLOG(ERROR) << "Failed to read siginfo from signal_fd";
510         return;
511     }
512 
513     switch (siginfo.ssi_signo) {
514         case SIGCHLD:
515             ReapAnyOutstandingChildren();
516             break;
517         case SIGTERM:
518             HandleSigtermSignal(siginfo);
519             break;
520         default:
521             PLOG(ERROR) << "signal_fd: received unexpected signal " << siginfo.ssi_signo;
522             break;
523     }
524 }
525 
UnblockSignals()526 static void UnblockSignals() {
527     const struct sigaction act { .sa_handler = SIG_DFL };
528     sigaction(SIGCHLD, &act, nullptr);
529 
530     sigset_t mask;
531     sigemptyset(&mask);
532     sigaddset(&mask, SIGCHLD);
533     sigaddset(&mask, SIGTERM);
534 
535     if (sigprocmask(SIG_UNBLOCK, &mask, nullptr) == -1) {
536         PLOG(FATAL) << "failed to unblock signals for PID " << getpid();
537     }
538 }
539 
InstallSignalFdHandler(Epoll * epoll)540 static void InstallSignalFdHandler(Epoll* epoll) {
541     // Applying SA_NOCLDSTOP to a defaulted SIGCHLD handler prevents the signalfd from receiving
542     // SIGCHLD when a child process stops or continues (b/77867680#comment9).
543     const struct sigaction act { .sa_handler = SIG_DFL, .sa_flags = SA_NOCLDSTOP };
544     sigaction(SIGCHLD, &act, nullptr);
545 
546     sigset_t mask;
547     sigemptyset(&mask);
548     sigaddset(&mask, SIGCHLD);
549 
550     if (!IsRebootCapable()) {
551         // If init does not have the CAP_SYS_BOOT capability, it is running in a container.
552         // In that case, receiving SIGTERM will cause the system to shut down.
553         sigaddset(&mask, SIGTERM);
554     }
555 
556     if (sigprocmask(SIG_BLOCK, &mask, nullptr) == -1) {
557         PLOG(FATAL) << "failed to block signals";
558     }
559 
560     // Register a handler to unblock signals in the child processes.
561     const int result = pthread_atfork(nullptr, nullptr, &UnblockSignals);
562     if (result != 0) {
563         LOG(FATAL) << "Failed to register a fork handler: " << strerror(result);
564     }
565 
566     signal_fd = signalfd(-1, &mask, SFD_CLOEXEC);
567     if (signal_fd == -1) {
568         PLOG(FATAL) << "failed to create signalfd";
569     }
570 
571     if (auto result = epoll->RegisterHandler(signal_fd, HandleSignalFd); !result) {
572         LOG(FATAL) << result.error();
573     }
574 }
575 
HandleKeychord(const std::vector<int> & keycodes)576 void HandleKeychord(const std::vector<int>& keycodes) {
577     // Only handle keychords if adb is enabled.
578     std::string adb_enabled = android::base::GetProperty("init.svc.adbd", "");
579     if (adb_enabled != "running") {
580         LOG(WARNING) << "Not starting service for keychord " << android::base::Join(keycodes, ' ')
581                      << " because ADB is disabled";
582         return;
583     }
584 
585     auto found = false;
586     for (const auto& service : ServiceList::GetInstance()) {
587         auto svc = service.get();
588         if (svc->keycodes() == keycodes) {
589             found = true;
590             LOG(INFO) << "Starting service '" << svc->name() << "' from keychord "
591                       << android::base::Join(keycodes, ' ');
592             if (auto result = svc->Start(); !result) {
593                 LOG(ERROR) << "Could not start service '" << svc->name() << "' from keychord "
594                            << android::base::Join(keycodes, ' ') << ": " << result.error();
595             }
596         }
597     }
598     if (!found) {
599         LOG(ERROR) << "Service for keychord " << android::base::Join(keycodes, ' ') << " not found";
600     }
601 }
602 
GlobalSeccomp()603 static void GlobalSeccomp() {
604     import_kernel_cmdline(false, [](const std::string& key, const std::string& value,
605                                     bool in_qemu) {
606         if (key == "androidboot.seccomp" && value == "global" && !set_global_seccomp_filter()) {
607             LOG(FATAL) << "Failed to globally enable seccomp!";
608         }
609     });
610 }
611 
UmountDebugRamdisk()612 static void UmountDebugRamdisk() {
613     if (umount("/debug_ramdisk") != 0) {
614         LOG(ERROR) << "Failed to umount /debug_ramdisk";
615     }
616 }
617 
SecondStageMain(int argc,char ** argv)618 int SecondStageMain(int argc, char** argv) {
619     if (REBOOT_BOOTLOADER_ON_PANIC) {
620         InstallRebootSignalHandlers();
621     }
622 
623     SetStdioToDevNull(argv);
624     InitKernelLogging(argv);
625     LOG(INFO) << "init second stage started!";
626 
627     // Set init and its forked children's oom_adj.
628     if (auto result = WriteFile("/proc/1/oom_score_adj", "-1000"); !result) {
629         LOG(ERROR) << "Unable to write -1000 to /proc/1/oom_score_adj: " << result.error();
630     }
631 
632     // Enable seccomp if global boot option was passed (otherwise it is enabled in zygote).
633     GlobalSeccomp();
634 
635     // Set up a session keyring that all processes will have access to. It
636     // will hold things like FBE encryption keys. No process should override
637     // its session keyring.
638     keyctl_get_keyring_ID(KEY_SPEC_SESSION_KEYRING, 1);
639 
640     // Indicate that booting is in progress to background fw loaders, etc.
641     close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
642 
643     property_init();
644 
645     // If arguments are passed both on the command line and in DT,
646     // properties set in DT always have priority over the command-line ones.
647     process_kernel_dt();
648     process_kernel_cmdline();
649 
650     // Propagate the kernel variables to internal variables
651     // used by init as well as the current required properties.
652     export_kernel_boot_props();
653 
654     // Make the time that init started available for bootstat to log.
655     property_set("ro.boottime.init", getenv("INIT_STARTED_AT"));
656     property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK"));
657 
658     // Set libavb version for Framework-only OTA match in Treble build.
659     const char* avb_version = getenv("INIT_AVB_VERSION");
660     if (avb_version) property_set("ro.boot.avb_version", avb_version);
661 
662     // See if need to load debug props to allow adb root, when the device is unlocked.
663     const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
664     if (force_debuggable_env && AvbHandle::IsDeviceUnlocked()) {
665         load_debug_prop = "true"s == force_debuggable_env;
666     }
667 
668     // Clean up our environment.
669     unsetenv("INIT_STARTED_AT");
670     unsetenv("INIT_SELINUX_TOOK");
671     unsetenv("INIT_AVB_VERSION");
672     unsetenv("INIT_FORCE_DEBUGGABLE");
673 
674     // Now set up SELinux for second stage.
675     SelinuxSetupKernelLogging();
676     SelabelInitialize();
677     SelinuxRestoreContext();
678 
679     Epoll epoll;
680     if (auto result = epoll.Open(); !result) {
681         PLOG(FATAL) << result.error();
682     }
683 
684     InstallSignalFdHandler(&epoll);
685 
686     property_load_boot_defaults(load_debug_prop);
687     UmountDebugRamdisk();
688     fs_mgr_vendor_overlay_mount_all();
689     export_oem_lock_status();
690     StartPropertyService(&epoll);
691     MountHandler mount_handler(&epoll);
692     set_usb_controller();
693 
694     const BuiltinFunctionMap function_map;
695     Action::set_function_map(&function_map);
696 
697     if (!SetupMountNamespaces()) {
698         PLOG(FATAL) << "SetupMountNamespaces failed";
699     }
700 
701     subcontexts = InitializeSubcontexts();
702 
703     ActionManager& am = ActionManager::GetInstance();
704     ServiceList& sm = ServiceList::GetInstance();
705 
706     LoadBootScripts(am, sm);
707 
708     // Turning this on and letting the INFO logging be discarded adds 0.2s to
709     // Nexus 9 boot time, so it's disabled by default.
710     if (false) DumpState();
711 
712     // Make the GSI status available before scripts start running.
713     if (android::gsi::IsGsiRunning()) {
714         property_set("ro.gsid.image_running", "1");
715     } else {
716         property_set("ro.gsid.image_running", "0");
717     }
718 
719     am.QueueBuiltinAction(SetupCgroupsAction, "SetupCgroups");
720 
721     am.QueueEventTrigger("early-init");
722 
723     // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev...
724     am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
725     // ... so that we can start queuing up actions that require stuff from /dev.
726     am.QueueBuiltinAction(MixHwrngIntoLinuxRngAction, "MixHwrngIntoLinuxRng");
727     am.QueueBuiltinAction(SetMmapRndBitsAction, "SetMmapRndBits");
728     am.QueueBuiltinAction(SetKptrRestrictAction, "SetKptrRestrict");
729     Keychords keychords;
730     am.QueueBuiltinAction(
731         [&epoll, &keychords](const BuiltinArguments& args) -> Result<Success> {
732             for (const auto& svc : ServiceList::GetInstance()) {
733                 keychords.Register(svc->keycodes());
734             }
735             keychords.Start(&epoll, HandleKeychord);
736             return Success();
737         },
738         "KeychordInit");
739     am.QueueBuiltinAction(console_init_action, "console_init");
740 
741     // Trigger all the boot actions to get us started.
742     am.QueueEventTrigger("init");
743 
744     // Starting the BoringSSL self test, for NIAP certification compliance.
745     am.QueueBuiltinAction(StartBoringSslSelfTest, "StartBoringSslSelfTest");
746 
747     // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
748     // wasn't ready immediately after wait_for_coldboot_done
749     am.QueueBuiltinAction(MixHwrngIntoLinuxRngAction, "MixHwrngIntoLinuxRng");
750 
751     // Initialize binder before bringing up other system services
752     am.QueueBuiltinAction(InitBinder, "InitBinder");
753 
754     // Don't mount filesystems or start core system services in charger mode.
755     std::string bootmode = GetProperty("ro.bootmode", "");
756     if (bootmode == "charger") {
757         am.QueueEventTrigger("charger");
758     } else {
759         am.QueueEventTrigger("late-init");
760     }
761 
762     // Run all property triggers based on current state of the properties.
763     am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
764 
765     while (true) {
766         // By default, sleep until something happens.
767         auto epoll_timeout = std::optional<std::chrono::milliseconds>{};
768 
769         if (do_shutdown && !shutting_down) {
770             do_shutdown = false;
771             if (HandlePowerctlMessage(shutdown_command)) {
772                 shutting_down = true;
773             }
774         }
775 
776         if (!(waiting_for_prop || Service::is_exec_service_running())) {
777             am.ExecuteOneCommand();
778         }
779         if (!(waiting_for_prop || Service::is_exec_service_running())) {
780             if (!shutting_down) {
781                 auto next_process_action_time = HandleProcessActions();
782 
783                 // If there's a process that needs restarting, wake up in time for that.
784                 if (next_process_action_time) {
785                     epoll_timeout = std::chrono::ceil<std::chrono::milliseconds>(
786                             *next_process_action_time - boot_clock::now());
787                     if (*epoll_timeout < 0ms) epoll_timeout = 0ms;
788                 }
789             }
790 
791             // If there's more work to do, wake up again immediately.
792             if (am.HasMoreCommands()) epoll_timeout = 0ms;
793         }
794 
795         if (auto result = epoll.Wait(epoll_timeout); !result) {
796             LOG(ERROR) << result.error();
797         }
798     }
799 
800     return 0;
801 }
802 
803 }  // namespace init
804 }  // namespace android
805