• 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 <paths.h>
22 #include <pthread.h>
23 #include <signal.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/eventfd.h>
27 #include <sys/mount.h>
28 #include <sys/signalfd.h>
29 #include <sys/system_properties.h>
30 #include <sys/types.h>
31 #include <sys/utsname.h>
32 #include <unistd.h>
33 
34 #include <filesystem>
35 #include <fstream>
36 #include <functional>
37 #include <iostream>
38 #include <map>
39 #include <memory>
40 #include <mutex>
41 #include <optional>
42 #include <thread>
43 #include <vector>
44 
45 #include <android-base/chrono_utils.h>
46 #include <android-base/file.h>
47 #include <android-base/logging.h>
48 #include <android-base/parseint.h>
49 #include <android-base/properties.h>
50 #include <android-base/stringprintf.h>
51 #include <android-base/strings.h>
52 #include <android-base/thread_annotations.h>
53 #include <fs_avb/fs_avb.h>
54 #include <fs_mgr_vendor_overlay.h>
55 #include <libavb/libavb.h>
56 #include <libgsi/libgsi.h>
57 #include <libsnapshot/snapshot.h>
58 #include <logwrap/logwrap.h>
59 #include <processgroup/processgroup.h>
60 #include <processgroup/setup.h>
61 #include <selinux/android.h>
62 #include <unwindstack/AndroidUnwinder.h>
63 
64 #include "action.h"
65 #include "action_manager.h"
66 #include "action_parser.h"
67 #include "apex_init_util.h"
68 #include "epoll.h"
69 #include "first_stage_init.h"
70 #include "first_stage_mount.h"
71 #include "import_parser.h"
72 #include "keychords.h"
73 #include "lmkd_service.h"
74 #include "mount_handler.h"
75 #include "mount_namespace.h"
76 #include "property_service.h"
77 #include "proto_utils.h"
78 #include "reboot.h"
79 #include "reboot_utils.h"
80 #include "second_stage_resources.h"
81 #include "security.h"
82 #include "selabel.h"
83 #include "selinux.h"
84 #include "service.h"
85 #include "service_list.h"
86 #include "service_parser.h"
87 #include "sigchld_handler.h"
88 #include "snapuserd_transition.h"
89 #include "subcontext.h"
90 #include "system/core/init/property_service.pb.h"
91 #include "tradeinmode.h"
92 #include "util.h"
93 
94 #ifndef RECOVERY
95 #include "com_android_apex.h"
96 #endif  // RECOVERY
97 
98 using namespace std::chrono_literals;
99 using namespace std::string_literals;
100 
101 using android::base::boot_clock;
102 using android::base::ConsumePrefix;
103 using android::base::GetProperty;
104 using android::base::GetIntProperty;
105 using android::base::GetBoolProperty;
106 using android::base::ReadFileToString;
107 using android::base::SetProperty;
108 using android::base::StringPrintf;
109 using android::base::Timer;
110 using android::base::Trim;
111 using android::base::unique_fd;
112 using android::fs_mgr::AvbHandle;
113 using android::snapshot::SnapshotManager;
114 using android::base::WaitForProperty;
115 using android::base::WriteStringToFile;
116 
117 namespace android {
118 namespace init {
119 
120 static int property_triggers_enabled = 0;
121 
122 static int sigterm_fd = -1;
123 static int property_fd = -1;
124 
125 struct PendingControlMessage {
126     std::string message;
127     std::string name;
128     pid_t pid;
129     int fd;
130 };
131 static std::mutex pending_control_messages_lock;
132 static std::queue<PendingControlMessage> pending_control_messages;
133 
134 // Init epolls various FDs to wait for various inputs.  It previously waited on property changes
135 // with a blocking socket that contained the information related to the change, however, it was easy
136 // to fill that socket and deadlock the system.  Now we use locks to handle the property changes
137 // directly in the property thread, however we still must wake the epoll to inform init that there
138 // is a change to process, so we use this FD.  It is non-blocking, since we do not care how many
139 // times WakeMainInitThread() is called, only that the epoll will wake.
140 static int wake_main_thread_fd = -1;
InstallInitNotifier(Epoll * epoll)141 static void InstallInitNotifier(Epoll* epoll) {
142     wake_main_thread_fd = eventfd(0, EFD_CLOEXEC);
143     if (wake_main_thread_fd == -1) {
144         PLOG(FATAL) << "Failed to create eventfd for waking init";
145     }
146     auto clear_eventfd = [] {
147         uint64_t counter;
148         TEMP_FAILURE_RETRY(read(wake_main_thread_fd, &counter, sizeof(counter)));
149     };
150 
151     if (auto result = epoll->RegisterHandler(wake_main_thread_fd, clear_eventfd); !result.ok()) {
152         LOG(FATAL) << result.error();
153     }
154 }
155 
WakeMainInitThread()156 static void WakeMainInitThread() {
157     uint64_t counter = 1;
158     TEMP_FAILURE_RETRY(write(wake_main_thread_fd, &counter, sizeof(counter)));
159 }
160 
161 static class PropWaiterState {
162   public:
StartWaiting(const char * name,const char * value)163     bool StartWaiting(const char* name, const char* value) {
164         auto lock = std::lock_guard{lock_};
165         if (waiting_for_prop_) {
166             return false;
167         }
168         if (GetProperty(name, "") != value) {
169             // Current property value is not equal to expected value
170             wait_prop_name_ = name;
171             wait_prop_value_ = value;
172             waiting_for_prop_.reset(new Timer());
173         } else {
174             LOG(INFO) << "start_waiting_for_property(\"" << name << "\", \"" << value
175                       << "\"): already set";
176         }
177         return true;
178     }
179 
ResetWaitForProp()180     void ResetWaitForProp() {
181         auto lock = std::lock_guard{lock_};
182         ResetWaitForPropLocked();
183     }
184 
CheckAndResetWait(const std::string & name,const std::string & value)185     void CheckAndResetWait(const std::string& name, const std::string& value) {
186         auto lock = std::lock_guard{lock_};
187         // We always record how long init waited for ueventd to tell us cold boot finished.
188         // If we aren't waiting on this property, it means that ueventd finished before we even
189         // started to wait.
190         if (name == kColdBootDoneProp) {
191             auto time_waited = waiting_for_prop_ ? waiting_for_prop_->duration().count() : 0;
192             std::thread([time_waited] {
193                 SetProperty("ro.boottime.init.cold_boot_wait", std::to_string(time_waited));
194             }).detach();
195         }
196 
197         if (waiting_for_prop_) {
198             if (wait_prop_name_ == name && wait_prop_value_ == value) {
199                 LOG(INFO) << "Wait for property '" << wait_prop_name_ << "=" << wait_prop_value_
200                           << "' took " << *waiting_for_prop_;
201                 ResetWaitForPropLocked();
202                 WakeMainInitThread();
203             }
204         }
205     }
206 
207     // This is not thread safe because it releases the lock when it returns, so the waiting state
208     // may change.  However, we only use this function to prevent running commands in the main
209     // thread loop when we are waiting, so we do not care about false positives; only false
210     // negatives.  StartWaiting() and this function are always called from the same thread, so false
211     // negatives are not possible and therefore we're okay.
MightBeWaiting()212     bool MightBeWaiting() {
213         auto lock = std::lock_guard{lock_};
214         return static_cast<bool>(waiting_for_prop_);
215     }
216 
217   private:
ResetWaitForPropLocked()218     void ResetWaitForPropLocked() EXCLUSIVE_LOCKS_REQUIRED(lock_) {
219         wait_prop_name_.clear();
220         wait_prop_value_.clear();
221         waiting_for_prop_.reset();
222     }
223 
224     std::mutex lock_;
GUARDED_BY(lock_)225     GUARDED_BY(lock_) std::unique_ptr<Timer> waiting_for_prop_{nullptr};
226     GUARDED_BY(lock_) std::string wait_prop_name_;
227     GUARDED_BY(lock_) std::string wait_prop_value_;
228 
229 } prop_waiter_state;
230 
start_waiting_for_property(const char * name,const char * value)231 bool start_waiting_for_property(const char* name, const char* value) {
232     return prop_waiter_state.StartWaiting(name, value);
233 }
234 
ResetWaitForProp()235 void ResetWaitForProp() {
236     prop_waiter_state.ResetWaitForProp();
237 }
238 
239 static class ShutdownState {
240   public:
TriggerShutdown(const std::string & command)241     void TriggerShutdown(const std::string& command) {
242         // We can't call HandlePowerctlMessage() directly in this function,
243         // because it modifies the contents of the action queue, which can cause the action queue
244         // to get into a bad state if this function is called from a command being executed by the
245         // action queue.  Instead we set this flag and ensure that shutdown happens before the next
246         // command is run in the main init loop.
247         auto lock = std::lock_guard{shutdown_command_lock_};
248         shutdown_command_ = command;
249         do_shutdown_ = true;
250         WakeMainInitThread();
251     }
252 
CheckShutdown()253     std::optional<std::string> CheckShutdown() __attribute__((warn_unused_result)) {
254         auto lock = std::lock_guard{shutdown_command_lock_};
255         if (do_shutdown_ && !IsShuttingDown()) {
256             do_shutdown_ = false;
257             return shutdown_command_;
258         }
259         return {};
260     }
261 
262   private:
263     std::mutex shutdown_command_lock_;
264     std::string shutdown_command_ GUARDED_BY(shutdown_command_lock_);
265     bool do_shutdown_ = false;
266 } shutdown_state;
267 
DumpState()268 void DumpState() {
269     ServiceList::GetInstance().DumpState();
270     ActionManager::GetInstance().DumpState();
271 }
272 
CreateParser(ActionManager & action_manager,ServiceList & service_list)273 Parser CreateParser(ActionManager& action_manager, ServiceList& service_list) {
274     Parser parser;
275 
276     parser.AddSectionParser("service",
277                             std::make_unique<ServiceParser>(&service_list, GetSubcontext()));
278     parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, GetSubcontext()));
279     parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
280 
281     return parser;
282 }
283 
284 #ifndef RECOVERY
285 template <typename T>
286 struct LibXmlErrorHandler {
287     T handler_;
288     template <typename Handler>
LibXmlErrorHandlerandroid::init::LibXmlErrorHandler289     LibXmlErrorHandler(Handler&& handler) : handler_(std::move(handler)) {
290         xmlSetGenericErrorFunc(nullptr, &ErrorHandler);
291     }
~LibXmlErrorHandlerandroid::init::LibXmlErrorHandler292     ~LibXmlErrorHandler() { xmlSetGenericErrorFunc(nullptr, nullptr); }
ErrorHandlerandroid::init::LibXmlErrorHandler293     static void ErrorHandler(void*, const char* msg, ...) {
294         va_list args;
295         va_start(args, msg);
296         char* formatted;
297         if (vasprintf(&formatted, msg, args) >= 0) {
298             LOG(ERROR) << formatted;
299         }
300         free(formatted);
301         va_end(args);
302     }
303 };
304 
305 template <typename Handler>
306 LibXmlErrorHandler(Handler&&) -> LibXmlErrorHandler<Handler>;
307 #endif  // RECOVERY
308 
309 // Returns a Parser that accepts scripts from APEX modules. It supports `service` and `on`.
CreateApexConfigParser(ActionManager & action_manager,ServiceList & service_list)310 Parser CreateApexConfigParser(ActionManager& action_manager, ServiceList& service_list) {
311     Parser parser;
312     auto subcontext = GetSubcontext();
313 #ifndef RECOVERY
314     if (subcontext) {
315         const auto apex_info_list_file = "/apex/apex-info-list.xml";
316         auto error_handler = LibXmlErrorHandler([&](const auto& error_message) {
317             LOG(ERROR) << "Failed to read " << apex_info_list_file << ":" << error_message;
318         });
319         const auto apex_info_list = com::android::apex::readApexInfoList(apex_info_list_file);
320         if (apex_info_list.has_value()) {
321             std::vector<std::string> subcontext_apexes;
322             for (const auto& info : apex_info_list->getApexInfo()) {
323                 if (subcontext->PartitionMatchesSubcontext(info.getPartition())) {
324                     subcontext_apexes.push_back(info.getModuleName());
325                 }
326             }
327             subcontext->SetApexList(std::move(subcontext_apexes));
328         }
329     }
330 #endif  // RECOVERY
331     parser.AddSectionParser("service", std::make_unique<ServiceParser>(&service_list, subcontext));
332     parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, subcontext));
333 
334     return parser;
335 }
336 
LoadBootScripts(ActionManager & action_manager,ServiceList & service_list)337 static void LoadBootScripts(ActionManager& action_manager, ServiceList& service_list) {
338     Parser parser = CreateParser(action_manager, service_list);
339 
340     std::string bootscript = GetProperty("ro.boot.init_rc", "");
341     if (bootscript.empty()) {
342         parser.ParseConfig("/system/etc/init/hw/init.rc");
343         if (!parser.ParseConfig("/system/etc/init")) {
344             late_import_paths.emplace_back("/system/etc/init");
345         }
346         // late_import is available only in Q and earlier release. As we don't
347         // have system_ext in those versions, skip late_import for system_ext.
348         parser.ParseConfig("/system_ext/etc/init");
349         if (!parser.ParseConfig("/vendor/etc/init")) {
350             late_import_paths.emplace_back("/vendor/etc/init");
351         }
352         if (!parser.ParseConfig("/odm/etc/init")) {
353             late_import_paths.emplace_back("/odm/etc/init");
354         }
355         if (!parser.ParseConfig("/product/etc/init")) {
356             late_import_paths.emplace_back("/product/etc/init");
357         }
358     } else {
359         parser.ParseConfig(bootscript);
360     }
361 }
362 
PropertyChanged(const std::string & name,const std::string & value)363 void PropertyChanged(const std::string& name, const std::string& value) {
364     // If the property is sys.powerctl, we bypass the event queue and immediately handle it.
365     // This is to ensure that init will always and immediately shutdown/reboot, regardless of
366     // if there are other pending events to process or if init is waiting on an exec service or
367     // waiting on a property.
368     // In non-thermal-shutdown case, 'shutdown' trigger will be fired to let device specific
369     // commands to be executed.
370     if (name == "sys.powerctl") {
371         trigger_shutdown(value);
372     }
373 
374     if (property_triggers_enabled) {
375         ActionManager::GetInstance().QueuePropertyChange(name, value);
376         WakeMainInitThread();
377     }
378 
379     prop_waiter_state.CheckAndResetWait(name, value);
380 }
381 
HandleProcessActions()382 static std::optional<boot_clock::time_point> HandleProcessActions() {
383     std::optional<boot_clock::time_point> next_process_action_time;
384     for (const auto& s : ServiceList::GetInstance()) {
385         if ((s->flags() & SVC_RUNNING) && s->timeout_period()) {
386             auto timeout_time = s->time_started() + *s->timeout_period();
387             if (boot_clock::now() > timeout_time) {
388                 s->Timeout();
389             } else {
390                 if (!next_process_action_time || timeout_time < *next_process_action_time) {
391                     next_process_action_time = timeout_time;
392                 }
393             }
394         }
395 
396         if (!(s->flags() & SVC_RESTARTING)) continue;
397 
398         auto restart_time = s->time_started() + s->restart_period();
399         if (boot_clock::now() > restart_time) {
400             if (auto result = s->Start(); !result.ok()) {
401                 LOG(ERROR) << "Could not restart process '" << s->name() << "': " << result.error();
402             }
403         } else {
404             if (!next_process_action_time || restart_time < *next_process_action_time) {
405                 next_process_action_time = restart_time;
406             }
407         }
408     }
409     return next_process_action_time;
410 }
411 
DoControlStart(Service * service)412 static Result<void> DoControlStart(Service* service) {
413     return service->Start();
414 }
415 
DoControlStop(Service * service)416 static Result<void> DoControlStop(Service* service) {
417     service->Stop();
418     return {};
419 }
420 
DoControlRestart(Service * service)421 static Result<void> DoControlRestart(Service* service) {
422     service->Restart();
423     return {};
424 }
425 
StopServicesFromApex(const std::string & apex_name)426 int StopServicesFromApex(const std::string& apex_name) {
427     auto services = ServiceList::GetInstance().FindServicesByApexName(apex_name);
428     if (services.empty()) {
429         LOG(INFO) << "No service found for APEX: " << apex_name;
430         return 0;
431     }
432     std::set<std::string> service_names;
433     for (const auto& service : services) {
434         service_names.emplace(service->name());
435     }
436     constexpr std::chrono::milliseconds kServiceStopTimeout = 10s;
437     int still_running = StopServicesAndLogViolations(service_names, kServiceStopTimeout,
438                         true /*SIGTERM*/);
439     // Send SIGKILL to ones that didn't terminate cleanly.
440     if (still_running > 0) {
441         still_running = StopServicesAndLogViolations(service_names, 0ms, false /*SIGKILL*/);
442     }
443     return still_running;
444 }
445 
RemoveServiceAndActionFromApex(const std::string & apex_name)446 void RemoveServiceAndActionFromApex(const std::string& apex_name) {
447     // Remove services and actions that match apex name
448     ActionManager::GetInstance().RemoveActionIf([&](const std::unique_ptr<Action>& action) -> bool {
449         if (GetApexNameFromFileName(action->filename()) == apex_name) {
450             return true;
451         }
452         return false;
453     });
454     ServiceList::GetInstance().RemoveServiceIf([&](const std::unique_ptr<Service>& s) -> bool {
455         if (GetApexNameFromFileName(s->filename()) == apex_name) {
456             return true;
457         }
458         return false;
459     });
460 }
461 
DoUnloadApex(const std::string & apex_name)462 static Result<void> DoUnloadApex(const std::string& apex_name) {
463     if (StopServicesFromApex(apex_name) > 0) {
464         return Error() << "Unable to stop all service from " << apex_name;
465     }
466     RemoveServiceAndActionFromApex(apex_name);
467     return {};
468 }
469 
UpdateApexLinkerConfig(const std::string & apex_name)470 static Result<void> UpdateApexLinkerConfig(const std::string& apex_name) {
471     // Do not invoke linkerconfig when there's no bin/ in the apex.
472     const std::string bin_path = "/apex/" + apex_name + "/bin";
473     if (access(bin_path.c_str(), R_OK) != 0) {
474         return {};
475     }
476     const char* linkerconfig_binary = "/apex/com.android.runtime/bin/linkerconfig";
477     const char* linkerconfig_target = "/linkerconfig";
478     const char* arguments[] = {linkerconfig_binary, "--target", linkerconfig_target, "--apex",
479                                apex_name.c_str(),   "--strict"};
480 
481     if (logwrap_fork_execvp(arraysize(arguments), arguments, nullptr, false, LOG_KLOG, false,
482                             nullptr) != 0) {
483         return ErrnoError() << "failed to execute linkerconfig";
484     }
485     LOG(INFO) << "Generated linker configuration for " << apex_name;
486     return {};
487 }
488 
DoLoadApex(const std::string & apex_name)489 static Result<void> DoLoadApex(const std::string& apex_name) {
490     if (auto result = ParseRcScriptsFromApex(apex_name); !result.ok()) {
491         return result.error();
492     }
493 
494     if (auto result = UpdateApexLinkerConfig(apex_name); !result.ok()) {
495         return result.error();
496     }
497 
498     return {};
499 }
500 
501 enum class ControlTarget {
502     SERVICE,    // function gets called for the named service
503     INTERFACE,  // action gets called for every service that holds this interface
504 };
505 
506 using ControlMessageFunction = std::function<Result<void>(Service*)>;
507 
GetControlMessageMap()508 static const std::map<std::string, ControlMessageFunction, std::less<>>& GetControlMessageMap() {
509     // clang-format off
510     static const std::map<std::string, ControlMessageFunction, std::less<>> control_message_functions = {
511         {"sigstop_on",        [](auto* service) { service->set_sigstop(true); return Result<void>{}; }},
512         {"sigstop_off",       [](auto* service) { service->set_sigstop(false); return Result<void>{}; }},
513         {"oneshot_on",        [](auto* service) { service->set_oneshot(true); return Result<void>{}; }},
514         {"oneshot_off",       [](auto* service) { service->set_oneshot(false); return Result<void>{}; }},
515         {"start",             DoControlStart},
516         {"stop",              DoControlStop},
517         {"restart",           DoControlRestart},
518     };
519     // clang-format on
520 
521     return control_message_functions;
522 }
523 
HandleApexControlMessage(std::string_view action,const std::string & name,std::string_view message)524 static Result<void> HandleApexControlMessage(std::string_view action, const std::string& name,
525                                              std::string_view message) {
526     if (action == "load") {
527         return DoLoadApex(name);
528     } else if (action == "unload") {
529         return DoUnloadApex(name);
530     } else {
531         return Error() << "Unknown control msg '" << message << "'";
532     }
533 }
534 
HandleControlMessage(std::string_view message,const std::string & name,pid_t from_pid)535 static bool HandleControlMessage(std::string_view message, const std::string& name,
536                                  pid_t from_pid) {
537     std::string cmdline_path = StringPrintf("proc/%d/cmdline", from_pid);
538     std::string process_cmdline;
539     if (ReadFileToString(cmdline_path, &process_cmdline)) {
540         std::replace(process_cmdline.begin(), process_cmdline.end(), '\0', ' ');
541         process_cmdline = Trim(process_cmdline);
542     } else {
543         process_cmdline = "unknown process";
544     }
545 
546     auto action = message;
547     if (ConsumePrefix(&action, "apex_")) {
548         if (auto result = HandleApexControlMessage(action, name, message); !result.ok()) {
549             LOG(ERROR) << "Control message: Could not ctl." << message << " for '" << name
550                        << "' from pid: " << from_pid << " (" << process_cmdline
551                        << "): " << result.error();
552             return false;
553         }
554         LOG(INFO) << "Control message: Processed ctl." << message << " for '" << name
555                   << "' from pid: " << from_pid << " (" << process_cmdline << ")";
556         return true;
557     }
558 
559     Service* service = nullptr;
560     if (ConsumePrefix(&action, "interface_")) {
561         service = ServiceList::GetInstance().FindInterface(name);
562     } else {
563         service = ServiceList::GetInstance().FindService(name);
564     }
565 
566     if (service == nullptr) {
567         LOG(ERROR) << "Control message: Could not find '" << name << "' for ctl." << message
568                    << " from pid: " << from_pid << " (" << process_cmdline << ")";
569         return false;
570     }
571 
572     const auto& map = GetControlMessageMap();
573     const auto it = map.find(action);
574     if (it == map.end()) {
575         LOG(ERROR) << "Unknown control msg '" << message << "'";
576         return false;
577     }
578     const auto& function = it->second;
579 
580     if (auto result = function(service); !result.ok()) {
581         LOG(ERROR) << "Control message: Could not ctl." << message << " for '" << name
582                    << "' from pid: " << from_pid << " (" << process_cmdline
583                    << "): " << result.error();
584         return false;
585     }
586 
587     LOG(INFO) << "Control message: Processed ctl." << message << " for '" << name
588               << "' from pid: " << from_pid << " (" << process_cmdline << ")";
589     return true;
590 }
591 
QueueControlMessage(const std::string & message,const std::string & name,pid_t pid,int fd)592 bool QueueControlMessage(const std::string& message, const std::string& name, pid_t pid, int fd) {
593     auto lock = std::lock_guard{pending_control_messages_lock};
594     if (pending_control_messages.size() > 100) {
595         LOG(ERROR) << "Too many pending control messages, dropped '" << message << "' for '" << name
596                    << "' from pid: " << pid;
597         return false;
598     }
599     pending_control_messages.push({message, name, pid, fd});
600     WakeMainInitThread();
601     return true;
602 }
603 
HandleControlMessages()604 static void HandleControlMessages() {
605     auto lock = std::unique_lock{pending_control_messages_lock};
606     // Init historically would only execute handle one property message, including control messages
607     // in each iteration of its main loop.  We retain this behavior here to prevent starvation of
608     // other actions in the main loop.
609     if (!pending_control_messages.empty()) {
610         auto control_message = pending_control_messages.front();
611         pending_control_messages.pop();
612         lock.unlock();
613 
614         bool success = HandleControlMessage(control_message.message, control_message.name,
615                                             control_message.pid);
616 
617         uint32_t response = success ? PROP_SUCCESS : PROP_ERROR_HANDLE_CONTROL_MESSAGE;
618         if (control_message.fd != -1) {
619             TEMP_FAILURE_RETRY(send(control_message.fd, &response, sizeof(response), 0));
620             close(control_message.fd);
621         }
622         lock.lock();
623     }
624     // If we still have items to process, make sure we wake back up to do so.
625     if (!pending_control_messages.empty()) {
626         WakeMainInitThread();
627     }
628 }
629 
wait_for_coldboot_done_action(const BuiltinArguments & args)630 static Result<void> wait_for_coldboot_done_action(const BuiltinArguments& args) {
631     if (!prop_waiter_state.StartWaiting(kColdBootDoneProp, "true")) {
632         LOG(FATAL) << "Could not wait for '" << kColdBootDoneProp << "'";
633     }
634 
635     return {};
636 }
637 
SetupCgroupsAction(const BuiltinArguments &)638 static Result<void> SetupCgroupsAction(const BuiltinArguments&) {
639     if (!CgroupsAvailable()) {
640         LOG(INFO) << "Cgroups support in kernel is not enabled";
641         return {};
642     }
643     if (!CgroupSetup()) {
644         return ErrnoError() << "Failed to setup cgroups";
645     }
646 
647     return {};
648 }
649 
export_oem_lock_status()650 static void export_oem_lock_status() {
651     if (!android::base::GetBoolProperty("ro.oem_unlock_supported", false)) {
652         return;
653     }
654     SetProperty(
655             "ro.boot.flash.locked",
656             android::base::GetProperty("ro.boot.verifiedbootstate", "") == "orange" ? "0" : "1");
657 }
658 
property_enable_triggers_action(const BuiltinArguments & args)659 static Result<void> property_enable_triggers_action(const BuiltinArguments& args) {
660     /* Enable property triggers. */
661     property_triggers_enabled = 1;
662     return {};
663 }
664 
queue_property_triggers_action(const BuiltinArguments & args)665 static Result<void> queue_property_triggers_action(const BuiltinArguments& args) {
666     ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger");
667     ActionManager::GetInstance().QueueAllPropertyActions();
668     return {};
669 }
670 
671 // Set the UDC controller for the ConfigFS USB Gadgets.
672 // Read the UDC controller in use from "/sys/class/udc".
673 // In case of multiple UDC controllers select the first one.
SetUsbController()674 static void SetUsbController() {
675     static auto controller_set = false;
676     if (controller_set) return;
677     std::unique_ptr<DIR, decltype(&closedir)>dir(opendir("/sys/class/udc"), closedir);
678     if (!dir) return;
679 
680     dirent* dp;
681     while ((dp = readdir(dir.get())) != nullptr) {
682         if (dp->d_name[0] == '.') continue;
683 
684         SetProperty("sys.usb.controller", dp->d_name);
685         controller_set = true;
686         break;
687     }
688 }
689 
690 /// Set ro.kernel.version property to contain the major.minor pair as returned
691 /// by uname(2).
SetKernelVersion()692 static void SetKernelVersion() {
693     struct utsname uts;
694     unsigned int major, minor;
695 
696     if ((uname(&uts) != 0) || (sscanf(uts.release, "%u.%u", &major, &minor) != 2)) {
697         LOG(ERROR) << "Could not parse the kernel version from uname";
698         return;
699     }
700     SetProperty("ro.kernel.version", android::base::StringPrintf("%u.%u", major, minor));
701 }
702 
HandleSigtermSignal(const signalfd_siginfo & siginfo)703 static void HandleSigtermSignal(const signalfd_siginfo& siginfo) {
704     if (siginfo.ssi_pid != 0) {
705         // Drop any userspace SIGTERM requests.
706         LOG(DEBUG) << "Ignoring SIGTERM from pid " << siginfo.ssi_pid;
707         return;
708     }
709 
710     HandlePowerctlMessage("shutdown,container");
711 }
712 
HandleSignalFd(int signal)713 static void HandleSignalFd(int signal) {
714     signalfd_siginfo siginfo;
715     const int signal_fd = signal == SIGCHLD ? Service::GetSigchldFd() : sigterm_fd;
716     ssize_t bytes_read = TEMP_FAILURE_RETRY(read(signal_fd, &siginfo, sizeof(siginfo)));
717     if (bytes_read != sizeof(siginfo)) {
718         PLOG(ERROR) << "Failed to read siginfo from signal_fd";
719         return;
720     }
721 
722     switch (siginfo.ssi_signo) {
723         case SIGCHLD:
724             ReapAnyOutstandingChildren();
725             break;
726         case SIGTERM:
727             HandleSigtermSignal(siginfo);
728             break;
729         default:
730             LOG(ERROR) << "signal_fd: received unexpected signal " << siginfo.ssi_signo;
731             break;
732     }
733 }
734 
UnblockSignals()735 static void UnblockSignals() {
736     const struct sigaction act { .sa_handler = SIG_DFL };
737     sigaction(SIGCHLD, &act, nullptr);
738 
739     sigset_t mask;
740     sigemptyset(&mask);
741     sigaddset(&mask, SIGCHLD);
742     sigaddset(&mask, SIGTERM);
743 
744     if (sigprocmask(SIG_UNBLOCK, &mask, nullptr) == -1) {
745         PLOG(FATAL) << "failed to unblock signals for PID " << getpid();
746     }
747 }
748 
RegisterSignalFd(Epoll * epoll,int signal,int fd)749 static Result<void> RegisterSignalFd(Epoll* epoll, int signal, int fd) {
750     return epoll->RegisterHandler(
751             fd, [signal]() { HandleSignalFd(signal); }, EPOLLIN | EPOLLPRI);
752 }
753 
CreateAndRegisterSignalFd(Epoll * epoll,int signal)754 static Result<int> CreateAndRegisterSignalFd(Epoll* epoll, int signal) {
755     sigset_t mask;
756     sigemptyset(&mask);
757     sigaddset(&mask, signal);
758     if (sigprocmask(SIG_BLOCK, &mask, nullptr) == -1) {
759         return ErrnoError() << "failed to block signal " << signal;
760     }
761 
762     unique_fd signal_fd(signalfd(-1, &mask, SFD_CLOEXEC));
763     if (signal_fd.get() < 0) {
764         return ErrnoError() << "failed to create signalfd for signal " << signal;
765     }
766     OR_RETURN(RegisterSignalFd(epoll, signal, signal_fd.get()));
767 
768     return signal_fd.release();
769 }
770 
InstallSignalFdHandler(Epoll * epoll)771 static void InstallSignalFdHandler(Epoll* epoll) {
772     // Applying SA_NOCLDSTOP to a defaulted SIGCHLD handler prevents the signalfd from receiving
773     // SIGCHLD when a child process stops or continues (b/77867680#comment9).
774     const struct sigaction act { .sa_flags = SA_NOCLDSTOP, .sa_handler = SIG_DFL };
775     sigaction(SIGCHLD, &act, nullptr);
776 
777     // Register a handler to unblock signals in the child processes.
778     const int result = pthread_atfork(nullptr, nullptr, &UnblockSignals);
779     if (result != 0) {
780         LOG(FATAL) << "Failed to register a fork handler: " << strerror(result);
781     }
782 
783     Result<void> cs_result = RegisterSignalFd(epoll, SIGCHLD, Service::GetSigchldFd());
784     if (!cs_result.ok()) {
785         PLOG(FATAL) << cs_result.error();
786     }
787 
788     if (!IsRebootCapable()) {
789         Result<int> cs_result = CreateAndRegisterSignalFd(epoll, SIGTERM);
790         if (!cs_result.ok()) {
791             PLOG(FATAL) << cs_result.error();
792         }
793         sigterm_fd = cs_result.value();
794     }
795 }
796 
HandleKeychord(const std::vector<int> & keycodes)797 void HandleKeychord(const std::vector<int>& keycodes) {
798     // Only handle keychords if adb is enabled.
799     std::string adb_enabled = android::base::GetProperty("init.svc.adbd", "");
800     if (adb_enabled != "running") {
801         LOG(WARNING) << "Not starting service for keychord " << android::base::Join(keycodes, ' ')
802                      << " because ADB is disabled";
803         return;
804     }
805 
806     auto found = false;
807     for (const auto& service : ServiceList::GetInstance()) {
808         auto svc = service.get();
809         if (svc->keycodes() == keycodes) {
810             found = true;
811             LOG(INFO) << "Starting service '" << svc->name() << "' from keychord "
812                       << android::base::Join(keycodes, ' ');
813             if (auto result = svc->Start(); !result.ok()) {
814                 LOG(ERROR) << "Could not start service '" << svc->name() << "' from keychord "
815                            << android::base::Join(keycodes, ' ') << ": " << result.error();
816             }
817         }
818     }
819     if (!found) {
820         LOG(ERROR) << "Service for keychord " << android::base::Join(keycodes, ' ') << " not found";
821     }
822 }
823 
UmountDebugRamdisk()824 static void UmountDebugRamdisk() {
825     if (umount("/debug_ramdisk") != 0) {
826         PLOG(ERROR) << "Failed to umount /debug_ramdisk";
827     }
828 }
829 
UmountSecondStageRes()830 static void UmountSecondStageRes() {
831     if (umount(kSecondStageRes) != 0) {
832         PLOG(ERROR) << "Failed to umount " << kSecondStageRes;
833     }
834 }
835 
MountExtraFilesystems()836 static void MountExtraFilesystems() {
837 #define CHECKCALL(x) \
838     if ((x) != 0) PLOG(FATAL) << #x " failed.";
839 
840     // /apex is used to mount APEXes
841     CHECKCALL(mount("tmpfs", "/apex", "tmpfs", MS_NOEXEC | MS_NOSUID | MS_NODEV,
842                     "mode=0755,uid=0,gid=0"));
843 
844     if (NeedsTwoMountNamespaces()) {
845         // /bootstrap-apex is used to mount "bootstrap" APEXes.
846         CHECKCALL(mount("tmpfs", "/bootstrap-apex", "tmpfs", MS_NOEXEC | MS_NOSUID | MS_NODEV,
847                         "mode=0755,uid=0,gid=0"));
848     }
849 
850     // /linkerconfig is used to keep generated linker configuration
851     CHECKCALL(mount("tmpfs", "/linkerconfig", "tmpfs", MS_NOEXEC | MS_NOSUID | MS_NODEV,
852                     "mode=0755,uid=0,gid=0"));
853 #undef CHECKCALL
854 }
855 
RecordStageBoottimes(const boot_clock::time_point & second_stage_start_time)856 static void RecordStageBoottimes(const boot_clock::time_point& second_stage_start_time) {
857     int64_t first_stage_start_time_ns = -1;
858     if (auto first_stage_start_time_str = getenv(kEnvFirstStageStartedAt);
859         first_stage_start_time_str) {
860         SetProperty("ro.boottime.init", first_stage_start_time_str);
861         android::base::ParseInt(first_stage_start_time_str, &first_stage_start_time_ns);
862     }
863     unsetenv(kEnvFirstStageStartedAt);
864 
865     int64_t selinux_start_time_ns = -1;
866     if (auto selinux_start_time_str = getenv(kEnvSelinuxStartedAt); selinux_start_time_str) {
867         android::base::ParseInt(selinux_start_time_str, &selinux_start_time_ns);
868     }
869     unsetenv(kEnvSelinuxStartedAt);
870 
871     if (selinux_start_time_ns == -1) return;
872     if (first_stage_start_time_ns == -1) return;
873 
874     SetProperty("ro.boottime.init.first_stage",
875                 std::to_string(selinux_start_time_ns - first_stage_start_time_ns));
876     SetProperty("ro.boottime.init.selinux",
877                 std::to_string(second_stage_start_time.time_since_epoch().count() -
878                                selinux_start_time_ns));
879     if (auto init_module_time_str = getenv(kEnvInitModuleDurationMs); init_module_time_str) {
880         SetProperty("ro.boottime.init.modules", init_module_time_str);
881         unsetenv(kEnvInitModuleDurationMs);
882     }
883 }
884 
SendLoadPersistentPropertiesMessage()885 void SendLoadPersistentPropertiesMessage() {
886     auto init_message = InitMessage{};
887     init_message.set_load_persistent_properties(true);
888     if (auto result = SendMessage(property_fd, init_message); !result.ok()) {
889         LOG(ERROR) << "Failed to send load persistent properties message: " << result.error();
890     }
891 }
892 
ConnectEarlyStageSnapuserdAction(const BuiltinArguments & args)893 static Result<void> ConnectEarlyStageSnapuserdAction(const BuiltinArguments& args) {
894     auto pid = GetSnapuserdFirstStagePid();
895     if (!pid) {
896         return {};
897     }
898 
899     auto info = GetSnapuserdFirstStageInfo();
900     if (auto iter = std::find(info.begin(), info.end(), "socket"s); iter == info.end()) {
901         // snapuserd does not support socket handoff, so exit early.
902         return {};
903     }
904 
905     // Socket handoff is supported.
906     auto svc = ServiceList::GetInstance().FindService("snapuserd");
907     if (!svc) {
908         LOG(FATAL) << "Failed to find snapuserd service entry";
909     }
910 
911     svc->SetShutdownCritical();
912     svc->SetStartedInFirstStage(*pid);
913 
914     svc = ServiceList::GetInstance().FindService("snapuserd_proxy");
915     if (!svc) {
916         LOG(FATAL) << "Failed find snapuserd_proxy service entry, merge will never initiate";
917     }
918     if (!svc->MarkSocketPersistent("snapuserd")) {
919         LOG(FATAL) << "Could not find snapuserd socket in snapuserd_proxy service entry";
920     }
921     if (auto result = svc->Start(); !result.ok()) {
922         LOG(FATAL) << "Could not start snapuserd_proxy: " << result.error();
923     }
924     return {};
925 }
926 
CheckTradeInModeStatus(const BuiltinArguments & args)927 static Result<void> CheckTradeInModeStatus([[maybe_unused]] const BuiltinArguments& args) {
928     RequestTradeInModeWipeIfNeeded();
929     return {};
930 }
931 
SecondStageBootMonitor(int timeout_sec)932 static void SecondStageBootMonitor(int timeout_sec) {
933     auto cur_time = boot_clock::now().time_since_epoch();
934     int cur_sec = std::chrono::duration_cast<std::chrono::seconds>(cur_time).count();
935     int extra_sec = timeout_sec <= cur_sec? 0 : timeout_sec - cur_sec;
936     auto boot_timeout = std::chrono::seconds(extra_sec);
937 
938     LOG(INFO) << "Started BootMonitorThread, expiring in "
939               << timeout_sec
940               << " seconds from boot-up";
941 
942     if (!WaitForProperty("sys.boot_completed", "1", boot_timeout)) {
943         LOG(ERROR) << "BootMonitorThread: boot didn't complete in "
944                    << timeout_sec
945                    << " seconds. Trigger a panic!";
946 
947         // add a short delay for logs to be flushed out.
948         std::this_thread::sleep_for(200ms);
949 
950         // trigger a kernel panic
951         WriteStringToFile("c", PROC_SYSRQ);
952     }
953 }
954 
StartSecondStageBootMonitor(int timeout_sec)955 static void StartSecondStageBootMonitor(int timeout_sec) {
956     std::thread monitor_thread(&SecondStageBootMonitor, timeout_sec);
957     monitor_thread.detach();
958 }
959 
SecondStageMain(int argc,char ** argv)960 int SecondStageMain(int argc, char** argv) {
961     if (REBOOT_BOOTLOADER_ON_PANIC) {
962         InstallRebootSignalHandlers();
963     }
964 
965     // No threads should be spin up until signalfd
966     // is registered. If the threads are indeed required,
967     // each of these threads _should_ make sure SIGCHLD signal
968     // is blocked. See b/223076262
969     boot_clock::time_point start_time = boot_clock::now();
970 
971     trigger_shutdown = [](const std::string& command) { shutdown_state.TriggerShutdown(command); };
972 
973     SetStdioToDevNull(argv);
974     InitKernelLogging(argv);
975     LOG(INFO) << "init second stage started!";
976 
977     SelinuxSetupKernelLogging();
978 
979     // Update $PATH in the case the second stage init is newer than first stage init, where it is
980     // first set.
981     if (setenv("PATH", _PATH_DEFPATH, 1) != 0) {
982         PLOG(FATAL) << "Could not set $PATH to '" << _PATH_DEFPATH << "' in second stage";
983     }
984 
985     // Init should not crash because of a dependence on any other process, therefore we ignore
986     // SIGPIPE and handle EPIPE at the call site directly.  Note that setting a signal to SIG_IGN
987     // is inherited across exec, but custom signal handlers are not.  Since we do not want to
988     // ignore SIGPIPE for child processes, we set a no-op function for the signal handler instead.
989     {
990         struct sigaction action = {.sa_flags = SA_RESTART};
991         action.sa_handler = [](int) {};
992         sigaction(SIGPIPE, &action, nullptr);
993     }
994 
995     // Set init and its forked children's oom_adj.
996     if (auto result =
997                 WriteFile("/proc/1/oom_score_adj", StringPrintf("%d", DEFAULT_OOM_SCORE_ADJUST));
998         !result.ok()) {
999         LOG(ERROR) << "Unable to write " << DEFAULT_OOM_SCORE_ADJUST
1000                    << " to /proc/1/oom_score_adj: " << result.error();
1001     }
1002 
1003     // Indicate that booting is in progress to background fw loaders, etc.
1004     close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
1005 
1006     // See if need to load debug props to allow adb root, when the device is unlocked.
1007     const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
1008     bool load_debug_prop = false;
1009     if (force_debuggable_env && AvbHandle::IsDeviceUnlocked()) {
1010         load_debug_prop = "true"s == force_debuggable_env;
1011     }
1012     unsetenv("INIT_FORCE_DEBUGGABLE");
1013 
1014     // Umount the debug ramdisk so property service doesn't read .prop files from there, when it
1015     // is not meant to.
1016     if (!load_debug_prop) {
1017         UmountDebugRamdisk();
1018     }
1019 
1020     PropertyInit();
1021 
1022     // Umount second stage resources after property service has read the .prop files.
1023     UmountSecondStageRes();
1024 
1025     // Umount the debug ramdisk after property service has read the .prop files when it means to.
1026     if (load_debug_prop) {
1027         UmountDebugRamdisk();
1028     }
1029 
1030     // Mount extra filesystems required during second stage init
1031     MountExtraFilesystems();
1032 
1033     // Now set up SELinux for second stage.
1034     SelabelInitialize();
1035     SelinuxRestoreContext();
1036 
1037     Epoll epoll;
1038     if (auto result = epoll.Open(); !result.ok()) {
1039         PLOG(FATAL) << result.error();
1040     }
1041 
1042     // We always reap children before responding to the other pending functions. This is to
1043     // prevent a race where other daemons see that a service has exited and ask init to
1044     // start it again via ctl.start before init has reaped it.
1045     epoll.SetFirstCallback(ReapAnyOutstandingChildren);
1046 
1047     InstallSignalFdHandler(&epoll);
1048     InstallInitNotifier(&epoll);
1049     StartPropertyService(&property_fd);
1050 
1051     // If boot_timeout property has been set in a debug build, start the boot monitor
1052     if (GetBoolProperty("ro.debuggable", false)) {
1053         int timeout = GetIntProperty("ro.boot.boot_timeout", 0);
1054         if (timeout > 0) {
1055             StartSecondStageBootMonitor(timeout);
1056         }
1057     }
1058 
1059     // Make the time that init stages started available for bootstat to log.
1060     RecordStageBoottimes(start_time);
1061 
1062     // Set libavb version for Framework-only OTA match in Treble build.
1063     if (const char* avb_version = getenv("INIT_AVB_VERSION"); avb_version != nullptr) {
1064         SetProperty("ro.boot.avb_version", avb_version);
1065     }
1066     unsetenv("INIT_AVB_VERSION");
1067 
1068     fs_mgr_vendor_overlay_mount_all();
1069     export_oem_lock_status();
1070     MountHandler mount_handler(&epoll);
1071     SetUsbController();
1072     SetKernelVersion();
1073 
1074     const BuiltinFunctionMap& function_map = GetBuiltinFunctionMap();
1075     Action::set_function_map(&function_map);
1076 
1077     if (!SetupMountNamespaces()) {
1078         PLOG(FATAL) << "SetupMountNamespaces failed";
1079     }
1080 
1081     InitializeSubcontext();
1082 
1083     ActionManager& am = ActionManager::GetInstance();
1084     ServiceList& sm = ServiceList::GetInstance();
1085 
1086     LoadBootScripts(am, sm);
1087 
1088     // Turning this on and letting the INFO logging be discarded adds 0.2s to
1089     // Nexus 9 boot time, so it's disabled by default.
1090     if (false) DumpState();
1091 
1092     // Make the GSI status available before scripts start running.
1093     auto is_running = android::gsi::IsGsiRunning() ? "1" : "0";
1094     SetProperty(gsi::kGsiBootedProp, is_running);
1095     auto is_installed = android::gsi::IsGsiInstalled() ? "1" : "0";
1096     SetProperty(gsi::kGsiInstalledProp, is_installed);
1097     if (android::gsi::IsGsiRunning()) {
1098         std::string dsu_slot;
1099         if (android::gsi::GetActiveDsu(&dsu_slot)) {
1100             SetProperty(gsi::kDsuSlotProp, dsu_slot);
1101         }
1102     }
1103 
1104     // This needs to happen before SetKptrRestrictAction, as we are trying to
1105     // open /proc/kallsyms while still being allowed to see the full addresses
1106     // (since init holds CAP_SYSLOG, and Linux boots with kptr_restrict=0). The
1107     // address visibility through the saved fd (more specifically, the backing
1108     // open file description) will then be remembered by the kernel for the rest
1109     // of its lifetime, even after we raise the kptr_restrict.
1110     Service::OpenAndSaveStaticKallsymsFd();
1111 
1112     am.QueueBuiltinAction(SetupCgroupsAction, "SetupCgroups");
1113     am.QueueBuiltinAction(SetKptrRestrictAction, "SetKptrRestrict");
1114     am.QueueBuiltinAction(TestPerfEventSelinuxAction, "TestPerfEventSelinux");
1115     am.QueueEventTrigger("early-init");
1116     am.QueueBuiltinAction(ConnectEarlyStageSnapuserdAction, "ConnectEarlyStageSnapuserd");
1117 
1118     // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev...
1119     am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
1120     am.QueueBuiltinAction(CheckTradeInModeStatus, "CheckTradeInModeStatus");
1121     // ... so that we can start queuing up actions that require stuff from /dev.
1122     am.QueueBuiltinAction(SetMmapRndBitsAction, "SetMmapRndBits");
1123     Keychords keychords;
1124     am.QueueBuiltinAction(
1125             [&epoll, &keychords](const BuiltinArguments& args) -> Result<void> {
1126                 for (const auto& svc : ServiceList::GetInstance()) {
1127                     keychords.Register(svc->keycodes());
1128                 }
1129                 keychords.Start(&epoll, HandleKeychord);
1130                 return {};
1131             },
1132             "KeychordInit");
1133 
1134     // Trigger all the boot actions to get us started.
1135     am.QueueEventTrigger("init");
1136 
1137     // Don't mount filesystems or start core system services in charger mode.
1138     std::string bootmode = GetProperty("ro.bootmode", "");
1139     if (bootmode == "charger") {
1140         am.QueueEventTrigger("charger");
1141     } else {
1142         am.QueueEventTrigger("late-init");
1143     }
1144 
1145     // Run all property triggers based on current state of the properties.
1146     am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
1147 
1148     // Restore prio before main loop
1149     setpriority(PRIO_PROCESS, 0, 0);
1150     while (true) {
1151         // By default, sleep until something happens. Do not convert far_future into
1152         // std::chrono::milliseconds because that would trigger an overflow. The unit of boot_clock
1153         // is 1ns.
1154         const boot_clock::time_point far_future = boot_clock::time_point::max();
1155         boot_clock::time_point next_action_time = far_future;
1156 
1157         auto shutdown_command = shutdown_state.CheckShutdown();
1158         if (shutdown_command) {
1159             LOG(INFO) << "Got shutdown_command '" << *shutdown_command
1160                       << "' Calling HandlePowerctlMessage()";
1161             HandlePowerctlMessage(*shutdown_command);
1162         }
1163 
1164         if (!(prop_waiter_state.MightBeWaiting() || Service::is_exec_service_running())) {
1165             am.ExecuteOneCommand();
1166             // If there's more work to do, wake up again immediately.
1167             if (am.HasMoreCommands()) {
1168                 next_action_time = boot_clock::now();
1169             }
1170         }
1171         // Since the above code examined pending actions, no new actions must be
1172         // queued by the code between this line and the Epoll::Wait() call below
1173         // without calling WakeMainInitThread().
1174         if (!IsShuttingDown()) {
1175             auto next_process_action_time = HandleProcessActions();
1176 
1177             // If there's a process that needs restarting, wake up in time for that.
1178             if (next_process_action_time) {
1179                 next_action_time = std::min(next_action_time, *next_process_action_time);
1180             }
1181         }
1182 
1183         std::optional<std::chrono::milliseconds> epoll_timeout;
1184         if (next_action_time != far_future) {
1185             epoll_timeout = std::chrono::ceil<std::chrono::milliseconds>(
1186                     std::max(next_action_time - boot_clock::now(), 0ns));
1187         }
1188         auto epoll_result = epoll.Wait(epoll_timeout);
1189         if (!epoll_result.ok()) {
1190             LOG(ERROR) << epoll_result.error();
1191         }
1192         if (!IsShuttingDown()) {
1193             HandleControlMessages();
1194             SetUsbController();
1195         }
1196     }
1197 
1198     return 0;
1199 }
1200 
1201 }  // namespace init
1202 }  // namespace android
1203