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/types.h>
30 #include <unistd.h>
31 
32 #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
33 #include <sys/_system_properties.h>
34 
35 #include <functional>
36 #include <map>
37 #include <memory>
38 #include <mutex>
39 #include <optional>
40 #include <thread>
41 #include <vector>
42 
43 #include <android-base/chrono_utils.h>
44 #include <android-base/file.h>
45 #include <android-base/logging.h>
46 #include <android-base/parseint.h>
47 #include <android-base/properties.h>
48 #include <android-base/stringprintf.h>
49 #include <android-base/strings.h>
50 #include <backtrace/Backtrace.h>
51 #include <fs_avb/fs_avb.h>
52 #include <fs_mgr_vendor_overlay.h>
53 #include <keyutils.h>
54 #include <libavb/libavb.h>
55 #include <libgsi/libgsi.h>
56 #include <processgroup/processgroup.h>
57 #include <processgroup/setup.h>
58 #include <selinux/android.h>
59 
60 #include "action_parser.h"
61 #include "builtins.h"
62 #include "epoll.h"
63 #include "first_stage_init.h"
64 #include "first_stage_mount.h"
65 #include "import_parser.h"
66 #include "keychords.h"
67 #include "lmkd_service.h"
68 #include "mount_handler.h"
69 #include "mount_namespace.h"
70 #include "property_service.h"
71 #include "proto_utils.h"
72 #include "reboot.h"
73 #include "reboot_utils.h"
74 #include "security.h"
75 #include "selabel.h"
76 #include "selinux.h"
77 #include "service.h"
78 #include "service_parser.h"
79 #include "sigchld_handler.h"
80 #include "subcontext.h"
81 #include "system/core/init/property_service.pb.h"
82 #include "util.h"
83 
84 using namespace std::chrono_literals;
85 using namespace std::string_literals;
86 
87 using android::base::boot_clock;
88 using android::base::ConsumePrefix;
89 using android::base::GetProperty;
90 using android::base::ReadFileToString;
91 using android::base::SetProperty;
92 using android::base::StringPrintf;
93 using android::base::Timer;
94 using android::base::Trim;
95 using android::fs_mgr::AvbHandle;
96 
97 namespace android {
98 namespace init {
99 
100 static int property_triggers_enabled = 0;
101 
102 static int signal_fd = -1;
103 static int property_fd = -1;
104 
105 struct PendingControlMessage {
106     std::string message;
107     std::string name;
108     pid_t pid;
109     int fd;
110 };
111 static std::mutex pending_control_messages_lock;
112 static std::queue<PendingControlMessage> pending_control_messages;
113 
114 // Init epolls various FDs to wait for various inputs.  It previously waited on property changes
115 // with a blocking socket that contained the information related to the change, however, it was easy
116 // to fill that socket and deadlock the system.  Now we use locks to handle the property changes
117 // directly in the property thread, however we still must wake the epoll to inform init that there
118 // is a change to process, so we use this FD.  It is non-blocking, since we do not care how many
119 // times WakeMainInitThread() is called, only that the epoll will wake.
120 static int wake_main_thread_fd = -1;
InstallInitNotifier(Epoll * epoll)121 static void InstallInitNotifier(Epoll* epoll) {
122     wake_main_thread_fd = eventfd(0, EFD_CLOEXEC);
123     if (wake_main_thread_fd == -1) {
124         PLOG(FATAL) << "Failed to create eventfd for waking init";
125     }
126     auto clear_eventfd = [] {
127         uint64_t counter;
128         TEMP_FAILURE_RETRY(read(wake_main_thread_fd, &counter, sizeof(counter)));
129     };
130 
131     if (auto result = epoll->RegisterHandler(wake_main_thread_fd, clear_eventfd); !result.ok()) {
132         LOG(FATAL) << result.error();
133     }
134 }
135 
WakeMainInitThread()136 static void WakeMainInitThread() {
137     uint64_t counter = 1;
138     TEMP_FAILURE_RETRY(write(wake_main_thread_fd, &counter, sizeof(counter)));
139 }
140 
141 static class PropWaiterState {
142   public:
StartWaiting(const char * name,const char * value)143     bool StartWaiting(const char* name, const char* value) {
144         auto lock = std::lock_guard{lock_};
145         if (waiting_for_prop_) {
146             return false;
147         }
148         if (GetProperty(name, "") != value) {
149             // Current property value is not equal to expected value
150             wait_prop_name_ = name;
151             wait_prop_value_ = value;
152             waiting_for_prop_.reset(new Timer());
153         } else {
154             LOG(INFO) << "start_waiting_for_property(\"" << name << "\", \"" << value
155                       << "\"): already set";
156         }
157         return true;
158     }
159 
ResetWaitForProp()160     void ResetWaitForProp() {
161         auto lock = std::lock_guard{lock_};
162         ResetWaitForPropLocked();
163     }
164 
CheckAndResetWait(const std::string & name,const std::string & value)165     void CheckAndResetWait(const std::string& name, const std::string& value) {
166         auto lock = std::lock_guard{lock_};
167         // We always record how long init waited for ueventd to tell us cold boot finished.
168         // If we aren't waiting on this property, it means that ueventd finished before we even
169         // started to wait.
170         if (name == kColdBootDoneProp) {
171             auto time_waited = waiting_for_prop_ ? waiting_for_prop_->duration().count() : 0;
172             std::thread([time_waited] {
173                 SetProperty("ro.boottime.init.cold_boot_wait", std::to_string(time_waited));
174             }).detach();
175         }
176 
177         if (waiting_for_prop_) {
178             if (wait_prop_name_ == name && wait_prop_value_ == value) {
179                 LOG(INFO) << "Wait for property '" << wait_prop_name_ << "=" << wait_prop_value_
180                           << "' took " << *waiting_for_prop_;
181                 ResetWaitForPropLocked();
182                 WakeMainInitThread();
183             }
184         }
185     }
186 
187     // This is not thread safe because it releases the lock when it returns, so the waiting state
188     // may change.  However, we only use this function to prevent running commands in the main
189     // thread loop when we are waiting, so we do not care about false positives; only false
190     // negatives.  StartWaiting() and this function are always called from the same thread, so false
191     // negatives are not possible and therefore we're okay.
MightBeWaiting()192     bool MightBeWaiting() {
193         auto lock = std::lock_guard{lock_};
194         return static_cast<bool>(waiting_for_prop_);
195     }
196 
197   private:
ResetWaitForPropLocked()198     void ResetWaitForPropLocked() {
199         wait_prop_name_.clear();
200         wait_prop_value_.clear();
201         waiting_for_prop_.reset();
202     }
203 
204     std::mutex lock_;
205     std::unique_ptr<Timer> waiting_for_prop_{nullptr};
206     std::string wait_prop_name_;
207     std::string wait_prop_value_;
208 
209 } prop_waiter_state;
210 
start_waiting_for_property(const char * name,const char * value)211 bool start_waiting_for_property(const char* name, const char* value) {
212     return prop_waiter_state.StartWaiting(name, value);
213 }
214 
ResetWaitForProp()215 void ResetWaitForProp() {
216     prop_waiter_state.ResetWaitForProp();
217 }
218 
219 static class ShutdownState {
220   public:
TriggerShutdown(const std::string & command)221     void TriggerShutdown(const std::string& command) {
222         // We can't call HandlePowerctlMessage() directly in this function,
223         // because it modifies the contents of the action queue, which can cause the action queue
224         // to get into a bad state if this function is called from a command being executed by the
225         // action queue.  Instead we set this flag and ensure that shutdown happens before the next
226         // command is run in the main init loop.
227         auto lock = std::lock_guard{shutdown_command_lock_};
228         shutdown_command_ = command;
229         do_shutdown_ = true;
230         WakeMainInitThread();
231     }
232 
CheckShutdown()233     std::optional<std::string> CheckShutdown() {
234         auto lock = std::lock_guard{shutdown_command_lock_};
235         if (do_shutdown_ && !IsShuttingDown()) {
236             return shutdown_command_;
237         }
238         return {};
239     }
240 
do_shutdown() const241     bool do_shutdown() const { return do_shutdown_; }
set_do_shutdown(bool value)242     void set_do_shutdown(bool value) { do_shutdown_ = value; }
243 
244   private:
245     std::mutex shutdown_command_lock_;
246     std::string shutdown_command_;
247     bool do_shutdown_ = false;
248 } shutdown_state;
249 
UnwindMainThreadStack()250 static void UnwindMainThreadStack() {
251     std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, 1));
252     if (!backtrace->Unwind(0)) {
253         LOG(ERROR) << __FUNCTION__ << "sys.powerctl: Failed to unwind callstack.";
254     }
255     for (size_t i = 0; i < backtrace->NumFrames(); i++) {
256         LOG(ERROR) << "sys.powerctl: " << backtrace->FormatFrameData(i);
257     }
258 }
259 
DebugRebootLogging()260 void DebugRebootLogging() {
261     LOG(INFO) << "sys.powerctl: do_shutdown: " << shutdown_state.do_shutdown()
262               << " IsShuttingDown: " << IsShuttingDown();
263     if (shutdown_state.do_shutdown()) {
264         LOG(ERROR) << "sys.powerctl set while a previous shutdown command has not been handled";
265         UnwindMainThreadStack();
266         DumpShutdownDebugInformation();
267     }
268     if (IsShuttingDown()) {
269         LOG(ERROR) << "sys.powerctl set while init is already shutting down";
270         UnwindMainThreadStack();
271         DumpShutdownDebugInformation();
272     }
273 }
274 
DumpState()275 void DumpState() {
276     ServiceList::GetInstance().DumpState();
277     ActionManager::GetInstance().DumpState();
278 }
279 
CreateParser(ActionManager & action_manager,ServiceList & service_list)280 Parser CreateParser(ActionManager& action_manager, ServiceList& service_list) {
281     Parser parser;
282 
283     parser.AddSectionParser("service", std::make_unique<ServiceParser>(
284                                                &service_list, GetSubcontext(), std::nullopt));
285     parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, GetSubcontext()));
286     parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
287 
288     return parser;
289 }
290 
291 // parser that only accepts new services
CreateServiceOnlyParser(ServiceList & service_list,bool from_apex)292 Parser CreateServiceOnlyParser(ServiceList& service_list, bool from_apex) {
293     Parser parser;
294 
295     parser.AddSectionParser(
296             "service", std::make_unique<ServiceParser>(&service_list, GetSubcontext(), std::nullopt,
297                                                        from_apex));
298     return parser;
299 }
300 
LoadBootScripts(ActionManager & action_manager,ServiceList & service_list)301 static void LoadBootScripts(ActionManager& action_manager, ServiceList& service_list) {
302     Parser parser = CreateParser(action_manager, service_list);
303 
304     std::string bootscript = GetProperty("ro.boot.init_rc", "");
305     if (bootscript.empty()) {
306         parser.ParseConfig("/system/etc/init/hw/init.rc");
307         if (!parser.ParseConfig("/system/etc/init")) {
308             late_import_paths.emplace_back("/system/etc/init");
309         }
310         // late_import is available only in Q and earlier release. As we don't
311         // have system_ext in those versions, skip late_import for system_ext.
312         parser.ParseConfig("/system_ext/etc/init");
313         if (!parser.ParseConfig("/product/etc/init")) {
314             late_import_paths.emplace_back("/product/etc/init");
315         }
316         if (!parser.ParseConfig("/odm/etc/init")) {
317             late_import_paths.emplace_back("/odm/etc/init");
318         }
319         if (!parser.ParseConfig("/vendor/etc/init")) {
320             late_import_paths.emplace_back("/vendor/etc/init");
321         }
322     } else {
323         parser.ParseConfig(bootscript);
324     }
325 }
326 
PropertyChanged(const std::string & name,const std::string & value)327 void PropertyChanged(const std::string& name, const std::string& value) {
328     // If the property is sys.powerctl, we bypass the event queue and immediately handle it.
329     // This is to ensure that init will always and immediately shutdown/reboot, regardless of
330     // if there are other pending events to process or if init is waiting on an exec service or
331     // waiting on a property.
332     // In non-thermal-shutdown case, 'shutdown' trigger will be fired to let device specific
333     // commands to be executed.
334     if (name == "sys.powerctl") {
335         trigger_shutdown(value);
336     }
337 
338     if (property_triggers_enabled) {
339         ActionManager::GetInstance().QueuePropertyChange(name, value);
340         WakeMainInitThread();
341     }
342 
343     prop_waiter_state.CheckAndResetWait(name, value);
344 }
345 
HandleProcessActions()346 static std::optional<boot_clock::time_point> HandleProcessActions() {
347     std::optional<boot_clock::time_point> next_process_action_time;
348     for (const auto& s : ServiceList::GetInstance()) {
349         if ((s->flags() & SVC_RUNNING) && s->timeout_period()) {
350             auto timeout_time = s->time_started() + *s->timeout_period();
351             if (boot_clock::now() > timeout_time) {
352                 s->Timeout();
353             } else {
354                 if (!next_process_action_time || timeout_time < *next_process_action_time) {
355                     next_process_action_time = timeout_time;
356                 }
357             }
358         }
359 
360         if (!(s->flags() & SVC_RESTARTING)) continue;
361 
362         auto restart_time = s->time_started() + s->restart_period();
363         if (boot_clock::now() > restart_time) {
364             if (auto result = s->Start(); !result.ok()) {
365                 LOG(ERROR) << "Could not restart process '" << s->name() << "': " << result.error();
366             }
367         } else {
368             if (!next_process_action_time || restart_time < *next_process_action_time) {
369                 next_process_action_time = restart_time;
370             }
371         }
372     }
373     return next_process_action_time;
374 }
375 
DoControlStart(Service * service)376 static Result<void> DoControlStart(Service* service) {
377     return service->Start();
378 }
379 
DoControlStop(Service * service)380 static Result<void> DoControlStop(Service* service) {
381     service->Stop();
382     return {};
383 }
384 
DoControlRestart(Service * service)385 static Result<void> DoControlRestart(Service* service) {
386     service->Restart();
387     return {};
388 }
389 
390 enum class ControlTarget {
391     SERVICE,    // function gets called for the named service
392     INTERFACE,  // action gets called for every service that holds this interface
393 };
394 
395 using ControlMessageFunction = std::function<Result<void>(Service*)>;
396 
GetControlMessageMap()397 static const std::map<std::string, ControlMessageFunction, std::less<>>& GetControlMessageMap() {
398     // clang-format off
399     static const std::map<std::string, ControlMessageFunction, std::less<>> control_message_functions = {
400         {"sigstop_on",        [](auto* service) { service->set_sigstop(true); return Result<void>{}; }},
401         {"sigstop_off",       [](auto* service) { service->set_sigstop(false); return Result<void>{}; }},
402         {"oneshot_on",        [](auto* service) { service->set_oneshot(true); return Result<void>{}; }},
403         {"oneshot_off",       [](auto* service) { service->set_oneshot(false); return Result<void>{}; }},
404         {"start",             DoControlStart},
405         {"stop",              DoControlStop},
406         {"restart",           DoControlRestart},
407     };
408     // clang-format on
409 
410     return control_message_functions;
411 }
412 
HandleControlMessage(std::string_view message,const std::string & name,pid_t from_pid)413 static bool HandleControlMessage(std::string_view message, const std::string& name,
414                                  pid_t from_pid) {
415     std::string cmdline_path = StringPrintf("proc/%d/cmdline", from_pid);
416     std::string process_cmdline;
417     if (ReadFileToString(cmdline_path, &process_cmdline)) {
418         std::replace(process_cmdline.begin(), process_cmdline.end(), '\0', ' ');
419         process_cmdline = Trim(process_cmdline);
420     } else {
421         process_cmdline = "unknown process";
422     }
423 
424     Service* service = nullptr;
425     auto action = message;
426     if (ConsumePrefix(&action, "interface_")) {
427         service = ServiceList::GetInstance().FindInterface(name);
428     } else {
429         service = ServiceList::GetInstance().FindService(name);
430     }
431 
432     if (service == nullptr) {
433         LOG(ERROR) << "Control message: Could not find '" << name << "' for ctl." << message
434                    << " from pid: " << from_pid << " (" << process_cmdline << ")";
435         return false;
436     }
437 
438     const auto& map = GetControlMessageMap();
439     const auto it = map.find(action);
440     if (it == map.end()) {
441         LOG(ERROR) << "Unknown control msg '" << message << "'";
442         return false;
443     }
444     const auto& function = it->second;
445 
446     if (auto result = function(service); !result.ok()) {
447         LOG(ERROR) << "Control message: Could not ctl." << message << " for '" << name
448                    << "' from pid: " << from_pid << " (" << process_cmdline
449                    << "): " << result.error();
450         return false;
451     }
452 
453     LOG(INFO) << "Control message: Processed ctl." << message << " for '" << name
454               << "' from pid: " << from_pid << " (" << process_cmdline << ")";
455     return true;
456 }
457 
QueueControlMessage(const std::string & message,const std::string & name,pid_t pid,int fd)458 bool QueueControlMessage(const std::string& message, const std::string& name, pid_t pid, int fd) {
459     auto lock = std::lock_guard{pending_control_messages_lock};
460     if (pending_control_messages.size() > 100) {
461         LOG(ERROR) << "Too many pending control messages, dropped '" << message << "' for '" << name
462                    << "' from pid: " << pid;
463         return false;
464     }
465     pending_control_messages.push({message, name, pid, fd});
466     WakeMainInitThread();
467     return true;
468 }
469 
HandleControlMessages()470 static void HandleControlMessages() {
471     auto lock = std::unique_lock{pending_control_messages_lock};
472     // Init historically would only execute handle one property message, including control messages
473     // in each iteration of its main loop.  We retain this behavior here to prevent starvation of
474     // other actions in the main loop.
475     if (!pending_control_messages.empty()) {
476         auto control_message = pending_control_messages.front();
477         pending_control_messages.pop();
478         lock.unlock();
479 
480         bool success = HandleControlMessage(control_message.message, control_message.name,
481                                             control_message.pid);
482 
483         uint32_t response = success ? PROP_SUCCESS : PROP_ERROR_HANDLE_CONTROL_MESSAGE;
484         if (control_message.fd != -1) {
485             TEMP_FAILURE_RETRY(send(control_message.fd, &response, sizeof(response), 0));
486             close(control_message.fd);
487         }
488         lock.lock();
489     }
490     // If we still have items to process, make sure we wake back up to do so.
491     if (!pending_control_messages.empty()) {
492         WakeMainInitThread();
493     }
494 }
495 
wait_for_coldboot_done_action(const BuiltinArguments & args)496 static Result<void> wait_for_coldboot_done_action(const BuiltinArguments& args) {
497     if (!prop_waiter_state.StartWaiting(kColdBootDoneProp, "true")) {
498         LOG(FATAL) << "Could not wait for '" << kColdBootDoneProp << "'";
499     }
500 
501     return {};
502 }
503 
SetupCgroupsAction(const BuiltinArguments &)504 static Result<void> SetupCgroupsAction(const BuiltinArguments&) {
505     // Have to create <CGROUPS_RC_DIR> using make_dir function
506     // for appropriate sepolicy to be set for it
507     make_dir(android::base::Dirname(CGROUPS_RC_PATH), 0711);
508     if (!CgroupSetup()) {
509         return ErrnoError() << "Failed to setup cgroups";
510     }
511 
512     return {};
513 }
514 
export_oem_lock_status()515 static void export_oem_lock_status() {
516     if (!android::base::GetBoolProperty("ro.oem_unlock_supported", false)) {
517         return;
518     }
519     ImportKernelCmdline([](const std::string& key, const std::string& value) {
520         if (key == "androidboot.verifiedbootstate") {
521             SetProperty("ro.boot.flash.locked", value == "orange" ? "0" : "1");
522         }
523     });
524 }
525 
property_enable_triggers_action(const BuiltinArguments & args)526 static Result<void> property_enable_triggers_action(const BuiltinArguments& args) {
527     /* Enable property triggers. */
528     property_triggers_enabled = 1;
529     return {};
530 }
531 
queue_property_triggers_action(const BuiltinArguments & args)532 static Result<void> queue_property_triggers_action(const BuiltinArguments& args) {
533     ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger");
534     ActionManager::GetInstance().QueueAllPropertyActions();
535     return {};
536 }
537 
538 // Set the UDC controller for the ConfigFS USB Gadgets.
539 // Read the UDC controller in use from "/sys/class/udc".
540 // In case of multiple UDC controllers select the first one.
SetUsbController()541 static void SetUsbController() {
542     static auto controller_set = false;
543     if (controller_set) return;
544     std::unique_ptr<DIR, decltype(&closedir)>dir(opendir("/sys/class/udc"), closedir);
545     if (!dir) return;
546 
547     dirent* dp;
548     while ((dp = readdir(dir.get())) != nullptr) {
549         if (dp->d_name[0] == '.') continue;
550 
551         SetProperty("sys.usb.controller", dp->d_name);
552         controller_set = true;
553         break;
554     }
555 }
556 
HandleSigtermSignal(const signalfd_siginfo & siginfo)557 static void HandleSigtermSignal(const signalfd_siginfo& siginfo) {
558     if (siginfo.ssi_pid != 0) {
559         // Drop any userspace SIGTERM requests.
560         LOG(DEBUG) << "Ignoring SIGTERM from pid " << siginfo.ssi_pid;
561         return;
562     }
563 
564     HandlePowerctlMessage("shutdown,container");
565 }
566 
HandleSignalFd()567 static void HandleSignalFd() {
568     signalfd_siginfo siginfo;
569     ssize_t bytes_read = TEMP_FAILURE_RETRY(read(signal_fd, &siginfo, sizeof(siginfo)));
570     if (bytes_read != sizeof(siginfo)) {
571         PLOG(ERROR) << "Failed to read siginfo from signal_fd";
572         return;
573     }
574 
575     switch (siginfo.ssi_signo) {
576         case SIGCHLD:
577             ReapAnyOutstandingChildren();
578             break;
579         case SIGTERM:
580             HandleSigtermSignal(siginfo);
581             break;
582         default:
583             PLOG(ERROR) << "signal_fd: received unexpected signal " << siginfo.ssi_signo;
584             break;
585     }
586 }
587 
UnblockSignals()588 static void UnblockSignals() {
589     const struct sigaction act { .sa_handler = SIG_DFL };
590     sigaction(SIGCHLD, &act, nullptr);
591 
592     sigset_t mask;
593     sigemptyset(&mask);
594     sigaddset(&mask, SIGCHLD);
595     sigaddset(&mask, SIGTERM);
596 
597     if (sigprocmask(SIG_UNBLOCK, &mask, nullptr) == -1) {
598         PLOG(FATAL) << "failed to unblock signals for PID " << getpid();
599     }
600 }
601 
InstallSignalFdHandler(Epoll * epoll)602 static void InstallSignalFdHandler(Epoll* epoll) {
603     // Applying SA_NOCLDSTOP to a defaulted SIGCHLD handler prevents the signalfd from receiving
604     // SIGCHLD when a child process stops or continues (b/77867680#comment9).
605     const struct sigaction act { .sa_handler = SIG_DFL, .sa_flags = SA_NOCLDSTOP };
606     sigaction(SIGCHLD, &act, nullptr);
607 
608     sigset_t mask;
609     sigemptyset(&mask);
610     sigaddset(&mask, SIGCHLD);
611 
612     if (!IsRebootCapable()) {
613         // If init does not have the CAP_SYS_BOOT capability, it is running in a container.
614         // In that case, receiving SIGTERM will cause the system to shut down.
615         sigaddset(&mask, SIGTERM);
616     }
617 
618     if (sigprocmask(SIG_BLOCK, &mask, nullptr) == -1) {
619         PLOG(FATAL) << "failed to block signals";
620     }
621 
622     // Register a handler to unblock signals in the child processes.
623     const int result = pthread_atfork(nullptr, nullptr, &UnblockSignals);
624     if (result != 0) {
625         LOG(FATAL) << "Failed to register a fork handler: " << strerror(result);
626     }
627 
628     signal_fd = signalfd(-1, &mask, SFD_CLOEXEC);
629     if (signal_fd == -1) {
630         PLOG(FATAL) << "failed to create signalfd";
631     }
632 
633     if (auto result = epoll->RegisterHandler(signal_fd, HandleSignalFd); !result.ok()) {
634         LOG(FATAL) << result.error();
635     }
636 }
637 
HandleKeychord(const std::vector<int> & keycodes)638 void HandleKeychord(const std::vector<int>& keycodes) {
639     // Only handle keychords if adb is enabled.
640     std::string adb_enabled = android::base::GetProperty("init.svc.adbd", "");
641     if (adb_enabled != "running") {
642         LOG(WARNING) << "Not starting service for keychord " << android::base::Join(keycodes, ' ')
643                      << " because ADB is disabled";
644         return;
645     }
646 
647     auto found = false;
648     for (const auto& service : ServiceList::GetInstance()) {
649         auto svc = service.get();
650         if (svc->keycodes() == keycodes) {
651             found = true;
652             LOG(INFO) << "Starting service '" << svc->name() << "' from keychord "
653                       << android::base::Join(keycodes, ' ');
654             if (auto result = svc->Start(); !result.ok()) {
655                 LOG(ERROR) << "Could not start service '" << svc->name() << "' from keychord "
656                            << android::base::Join(keycodes, ' ') << ": " << result.error();
657             }
658         }
659     }
660     if (!found) {
661         LOG(ERROR) << "Service for keychord " << android::base::Join(keycodes, ' ') << " not found";
662     }
663 }
664 
UmountDebugRamdisk()665 static void UmountDebugRamdisk() {
666     if (umount("/debug_ramdisk") != 0) {
667         PLOG(ERROR) << "Failed to umount /debug_ramdisk";
668     }
669 }
670 
MountExtraFilesystems()671 static void MountExtraFilesystems() {
672 #define CHECKCALL(x) \
673     if ((x) != 0) PLOG(FATAL) << #x " failed.";
674 
675     // /apex is used to mount APEXes
676     CHECKCALL(mount("tmpfs", "/apex", "tmpfs", MS_NOEXEC | MS_NOSUID | MS_NODEV,
677                     "mode=0755,uid=0,gid=0"));
678 
679     // /linkerconfig is used to keep generated linker configuration
680     CHECKCALL(mount("tmpfs", "/linkerconfig", "tmpfs", MS_NOEXEC | MS_NOSUID | MS_NODEV,
681                     "mode=0755,uid=0,gid=0"));
682 #undef CHECKCALL
683 }
684 
RecordStageBoottimes(const boot_clock::time_point & second_stage_start_time)685 static void RecordStageBoottimes(const boot_clock::time_point& second_stage_start_time) {
686     int64_t first_stage_start_time_ns = -1;
687     if (auto first_stage_start_time_str = getenv(kEnvFirstStageStartedAt);
688         first_stage_start_time_str) {
689         SetProperty("ro.boottime.init", first_stage_start_time_str);
690         android::base::ParseInt(first_stage_start_time_str, &first_stage_start_time_ns);
691     }
692     unsetenv(kEnvFirstStageStartedAt);
693 
694     int64_t selinux_start_time_ns = -1;
695     if (auto selinux_start_time_str = getenv(kEnvSelinuxStartedAt); selinux_start_time_str) {
696         android::base::ParseInt(selinux_start_time_str, &selinux_start_time_ns);
697     }
698     unsetenv(kEnvSelinuxStartedAt);
699 
700     if (selinux_start_time_ns == -1) return;
701     if (first_stage_start_time_ns == -1) return;
702 
703     SetProperty("ro.boottime.init.first_stage",
704                 std::to_string(selinux_start_time_ns - first_stage_start_time_ns));
705     SetProperty("ro.boottime.init.selinux",
706                 std::to_string(second_stage_start_time.time_since_epoch().count() -
707                                selinux_start_time_ns));
708 }
709 
SendLoadPersistentPropertiesMessage()710 void SendLoadPersistentPropertiesMessage() {
711     auto init_message = InitMessage{};
712     init_message.set_load_persistent_properties(true);
713     if (auto result = SendMessage(property_fd, init_message); !result.ok()) {
714         LOG(ERROR) << "Failed to send load persistent properties message: " << result.error();
715     }
716 }
717 
SecondStageMain(int argc,char ** argv)718 int SecondStageMain(int argc, char** argv) {
719     if (REBOOT_BOOTLOADER_ON_PANIC) {
720         InstallRebootSignalHandlers();
721     }
722 
723     boot_clock::time_point start_time = boot_clock::now();
724 
725     trigger_shutdown = [](const std::string& command) { shutdown_state.TriggerShutdown(command); };
726 
727     SetStdioToDevNull(argv);
728     InitSecondStageLogging(argv);
729     LOG(INFO) << "init second stage started!";
730 
731     // Update $PATH in the case the second stage init is newer than first stage init, where it is
732     // first set.
733     if (setenv("PATH", _PATH_DEFPATH, 1) != 0) {
734         PLOG(FATAL) << "Could not set $PATH to '" << _PATH_DEFPATH << "' in second stage";
735     }
736 
737     // Init should not crash because of a dependence on any other process, therefore we ignore
738     // SIGPIPE and handle EPIPE at the call site directly.  Note that setting a signal to SIG_IGN
739     // is inherited across exec, but custom signal handlers are not.  Since we do not want to
740     // ignore SIGPIPE for child processes, we set a no-op function for the signal handler instead.
741     {
742         struct sigaction action = {.sa_flags = SA_RESTART};
743         action.sa_handler = [](int) {};
744         sigaction(SIGPIPE, &action, nullptr);
745     }
746 
747     // Set init and its forked children's oom_adj.
748     if (auto result =
749                 WriteFile("/proc/1/oom_score_adj", StringPrintf("%d", DEFAULT_OOM_SCORE_ADJUST));
750         !result.ok()) {
751         LOG(ERROR) << "Unable to write " << DEFAULT_OOM_SCORE_ADJUST
752                    << " to /proc/1/oom_score_adj: " << result.error();
753     }
754 
755     // Set up a session keyring that all processes will have access to. It
756     // will hold things like FBE encryption keys. No process should override
757     // its session keyring.
758     keyctl_get_keyring_ID(KEY_SPEC_SESSION_KEYRING, 1);
759 
760     // Indicate that booting is in progress to background fw loaders, etc.
761     close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
762 
763     // See if need to load debug props to allow adb root, when the device is unlocked.
764     const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
765     bool load_debug_prop = false;
766     if (force_debuggable_env && AvbHandle::IsDeviceUnlocked()) {
767         load_debug_prop = "true"s == force_debuggable_env;
768     }
769     unsetenv("INIT_FORCE_DEBUGGABLE");
770 
771     // Umount the debug ramdisk so property service doesn't read .prop files from there, when it
772     // is not meant to.
773     if (!load_debug_prop) {
774         UmountDebugRamdisk();
775     }
776 
777     PropertyInit();
778 
779     // Umount the debug ramdisk after property service has read the .prop files when it means to.
780     if (load_debug_prop) {
781         UmountDebugRamdisk();
782     }
783 
784     // Mount extra filesystems required during second stage init
785     MountExtraFilesystems();
786 
787     // Now set up SELinux for second stage.
788     SelinuxSetupKernelLogging();
789     SelabelInitialize();
790     SelinuxRestoreContext();
791 
792     Epoll epoll;
793     if (auto result = epoll.Open(); !result.ok()) {
794         PLOG(FATAL) << result.error();
795     }
796 
797     InstallSignalFdHandler(&epoll);
798     InstallInitNotifier(&epoll);
799     StartPropertyService(&property_fd);
800 
801     // Make the time that init stages started available for bootstat to log.
802     RecordStageBoottimes(start_time);
803 
804     // Set libavb version for Framework-only OTA match in Treble build.
805     if (const char* avb_version = getenv("INIT_AVB_VERSION"); avb_version != nullptr) {
806         SetProperty("ro.boot.avb_version", avb_version);
807     }
808     unsetenv("INIT_AVB_VERSION");
809 
810     fs_mgr_vendor_overlay_mount_all();
811     export_oem_lock_status();
812     MountHandler mount_handler(&epoll);
813     SetUsbController();
814 
815     const BuiltinFunctionMap& function_map = GetBuiltinFunctionMap();
816     Action::set_function_map(&function_map);
817 
818     if (!SetupMountNamespaces()) {
819         PLOG(FATAL) << "SetupMountNamespaces failed";
820     }
821 
822     InitializeSubcontext();
823 
824     ActionManager& am = ActionManager::GetInstance();
825     ServiceList& sm = ServiceList::GetInstance();
826 
827     LoadBootScripts(am, sm);
828 
829     // Turning this on and letting the INFO logging be discarded adds 0.2s to
830     // Nexus 9 boot time, so it's disabled by default.
831     if (false) DumpState();
832 
833     // Make the GSI status available before scripts start running.
834     auto is_running = android::gsi::IsGsiRunning() ? "1" : "0";
835     SetProperty(gsi::kGsiBootedProp, is_running);
836     auto is_installed = android::gsi::IsGsiInstalled() ? "1" : "0";
837     SetProperty(gsi::kGsiInstalledProp, is_installed);
838 
839     am.QueueBuiltinAction(SetupCgroupsAction, "SetupCgroups");
840     am.QueueBuiltinAction(SetKptrRestrictAction, "SetKptrRestrict");
841     am.QueueBuiltinAction(TestPerfEventSelinuxAction, "TestPerfEventSelinux");
842     am.QueueEventTrigger("early-init");
843 
844     // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev...
845     am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
846     // ... so that we can start queuing up actions that require stuff from /dev.
847     am.QueueBuiltinAction(MixHwrngIntoLinuxRngAction, "MixHwrngIntoLinuxRng");
848     am.QueueBuiltinAction(SetMmapRndBitsAction, "SetMmapRndBits");
849     Keychords keychords;
850     am.QueueBuiltinAction(
851             [&epoll, &keychords](const BuiltinArguments& args) -> Result<void> {
852                 for (const auto& svc : ServiceList::GetInstance()) {
853                     keychords.Register(svc->keycodes());
854                 }
855                 keychords.Start(&epoll, HandleKeychord);
856                 return {};
857             },
858             "KeychordInit");
859 
860     // Trigger all the boot actions to get us started.
861     am.QueueEventTrigger("init");
862 
863     // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
864     // wasn't ready immediately after wait_for_coldboot_done
865     am.QueueBuiltinAction(MixHwrngIntoLinuxRngAction, "MixHwrngIntoLinuxRng");
866 
867     // Don't mount filesystems or start core system services in charger mode.
868     std::string bootmode = GetProperty("ro.bootmode", "");
869     if (bootmode == "charger") {
870         am.QueueEventTrigger("charger");
871     } else {
872         am.QueueEventTrigger("late-init");
873     }
874 
875     // Run all property triggers based on current state of the properties.
876     am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
877 
878     // Restore prio before main loop
879     setpriority(PRIO_PROCESS, 0, 0);
880     while (true) {
881         // By default, sleep until something happens.
882         auto epoll_timeout = std::optional<std::chrono::milliseconds>{};
883 
884         auto shutdown_command = shutdown_state.CheckShutdown();
885         if (shutdown_command) {
886             LOG(INFO) << "Got shutdown_command '" << *shutdown_command
887                       << "' Calling HandlePowerctlMessage()";
888             HandlePowerctlMessage(*shutdown_command);
889             shutdown_state.set_do_shutdown(false);
890         }
891 
892         if (!(prop_waiter_state.MightBeWaiting() || Service::is_exec_service_running())) {
893             am.ExecuteOneCommand();
894         }
895         if (!IsShuttingDown()) {
896             auto next_process_action_time = HandleProcessActions();
897 
898             // If there's a process that needs restarting, wake up in time for that.
899             if (next_process_action_time) {
900                 epoll_timeout = std::chrono::ceil<std::chrono::milliseconds>(
901                         *next_process_action_time - boot_clock::now());
902                 if (*epoll_timeout < 0ms) epoll_timeout = 0ms;
903             }
904         }
905 
906         if (!(prop_waiter_state.MightBeWaiting() || Service::is_exec_service_running())) {
907             // If there's more work to do, wake up again immediately.
908             if (am.HasMoreCommands()) epoll_timeout = 0ms;
909         }
910 
911         auto pending_functions = epoll.Wait(epoll_timeout);
912         if (!pending_functions.ok()) {
913             LOG(ERROR) << pending_functions.error();
914         } else if (!pending_functions->empty()) {
915             // We always reap children before responding to the other pending functions. This is to
916             // prevent a race where other daemons see that a service has exited and ask init to
917             // start it again via ctl.start before init has reaped it.
918             ReapAnyOutstandingChildren();
919             for (const auto& function : *pending_functions) {
920                 (*function)();
921             }
922         }
923         if (!IsShuttingDown()) {
924             HandleControlMessages();
925             SetUsbController();
926         }
927     }
928 
929     return 0;
930 }
931 
932 }  // namespace init
933 }  // namespace android
934