blob: b1774950ede873c95d2bd438abc4484a96697f35 [file] [log] [blame]
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001/*
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
Tom Cherry3f5eaae52017-04-06 16:30:22 -070017#include "init.h"
18
Rom Lemarchand6a524432015-02-28 06:39:11 -080019#include <dirent.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080020#include <fcntl.h>
yusukes4a4ec14e2018-02-01 17:14:30 -080021#include <pthread.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080022#include <signal.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070023#include <stdlib.h>
24#include <string.h>
Tom Cherry40463332020-03-26 20:32:17 -070025#include <sys/eventfd.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070026#include <sys/mount.h>
Luis Hector Chavez9f97f472017-09-06 13:43:57 -070027#include <sys/signalfd.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080028#include <sys/types.h>
Elliott Hughes8d82ea02015-02-06 20:15:18 -080029#include <unistd.h>
30
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070031#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
32#include <sys/_system_properties.h>
33
Tom Cherry172c83f2019-06-26 14:44:37 -070034#include <functional>
Tom Cherry8ae73752018-05-01 13:39:52 -070035#include <map>
36#include <memory>
Tom Cherry802864c2020-03-12 14:29:25 -070037#include <mutex>
Tom Cherry8ae73752018-05-01 13:39:52 -070038#include <optional>
Tom Cherry802864c2020-03-12 14:29:25 -070039#include <thread>
Tom Cherry172c83f2019-06-26 14:44:37 -070040#include <vector>
Tom Cherry8ae73752018-05-01 13:39:52 -070041
James Hawkinse78ea772017-03-24 11:43:02 -070042#include <android-base/chrono_utils.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080043#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070044#include <android-base/logging.h>
Mark Salyzyn10377df2019-03-27 08:10:41 -070045#include <android-base/parseint.h>
Tom Cherryccf23532017-03-28 16:40:41 -070046#include <android-base/properties.h>
Tom Cherry6f2d56d2018-02-21 10:37:44 -080047#include <android-base/stringprintf.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080048#include <android-base/strings.h>
Tom Cherry1c688362020-03-24 18:00:23 -070049#include <backtrace/Backtrace.h>
Bowgo Tsai1dacd422019-03-04 17:53:34 +080050#include <fs_avb/fs_avb.h>
Justin Yun6bab0a92018-10-29 18:31:48 +090051#include <fs_mgr_vendor_overlay.h>
Elliott Hughesf8627ce2017-05-09 17:09:06 -070052#include <keyutils.h>
bowgotsai76351272017-02-14 22:06:20 +080053#include <libavb/libavb.h>
David Anderson372278c2019-02-14 12:46:13 -080054#include <libgsi/libgsi.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080055#include <processgroup/processgroup.h>
Yifan Hong6f9ce2e2019-03-05 15:47:16 -080056#include <processgroup/setup.h>
Tom Cherryd9e53da2018-09-05 15:37:26 -070057#include <selinux/android.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070058
Tom Cherry0f6417f2018-02-13 15:25:29 -080059#include "action_parser.h"
Tom Cherry172c83f2019-06-26 14:44:37 -070060#include "builtins.h"
Mark Salyzyn6c6ec722015-10-24 16:20:18 -070061#include "epoll.h"
Mark Salyzyn44505ec2019-05-08 12:44:50 -070062#include "first_stage_init.h"
Tom Cherry38a11cc2018-07-20 15:18:04 -070063#include "first_stage_mount.h"
Tom Cherryb7349902015-08-26 11:43:36 -070064#include "import_parser.h"
Tom Cherrybac32992015-07-31 12:45:25 -070065#include "keychords.h"
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -070066#include "lmkd_service.h"
Mark Salyzyna73ed222019-03-13 10:18:24 -070067#include "mount_handler.h"
Jiyong Park68660412019-01-16 23:00:59 +090068#include "mount_namespace.h"
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070069#include "property_service.h"
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070070#include "proto_utils.h"
Tom Cherry98ad32a2017-04-17 16:34:20 -070071#include "reboot.h"
Tom Cherry44aceed2018-08-03 13:36:18 -070072#include "reboot_utils.h"
Tom Cherry0c8d6d22017-08-10 12:22:44 -070073#include "security.h"
Vic Yang92c236e2019-05-28 15:58:35 -070074#include "selabel.h"
Tom Cherry0c8d6d22017-08-10 12:22:44 -070075#include "selinux.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070076#include "service.h"
77#include "service_parser.h"
Luis Hector Chavez9f97f472017-09-06 13:43:57 -070078#include "sigchld_handler.h"
Tom Cherrye3e77d32020-04-28 13:55:19 -070079#include "subcontext.h"
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070080#include "system/core/init/property_service.pb.h"
Tom Cherrybac32992015-07-31 12:45:25 -070081#include "util.h"
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070082
Mark Salyzyn6c6ec722015-10-24 16:20:18 -070083using namespace std::chrono_literals;
Tom Cherry1c3a53f2017-06-22 16:50:31 -070084using namespace std::string_literals;
85
James Hawkinse78ea772017-03-24 11:43:02 -070086using android::base::boot_clock;
Tom Cherrybdbf5042020-03-04 10:52:08 -080087using android::base::ConsumePrefix;
Tom Cherryccf23532017-03-28 16:40:41 -070088using android::base::GetProperty;
Tom Cherry6f2d56d2018-02-21 10:37:44 -080089using android::base::ReadFileToString;
Tom Cherryc88d8f92019-08-19 15:21:25 -070090using android::base::SetProperty;
Tom Cherry6f2d56d2018-02-21 10:37:44 -080091using android::base::StringPrintf;
Tom Cherryede0d532017-07-06 14:20:11 -070092using android::base::Timer;
Tom Cherry6f2d56d2018-02-21 10:37:44 -080093using android::base::Trim;
Bowgo Tsai1dacd422019-03-04 17:53:34 +080094using android::fs_mgr::AvbHandle;
Elliott Hughes9605a942016-11-10 17:43:47 -080095
Tom Cherry81f5d3e2017-06-22 12:53:17 -070096namespace android {
97namespace init {
98
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070099static int property_triggers_enabled = 0;
100
Ryan Prichard1325ec82018-04-11 18:46:38 -0700101static int signal_fd = -1;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700102static int property_fd = -1;
Elliott Hughes929f4072015-04-24 21:13:44 -0700103
Tom Cherry802864c2020-03-12 14:29:25 -0700104struct PendingControlMessage {
105 std::string message;
106 std::string name;
107 pid_t pid;
108 int fd;
109};
110static std::mutex pending_control_messages_lock;
111static std::queue<PendingControlMessage> pending_control_messages;
112
113// Init epolls various FDs to wait for various inputs. It previously waited on property changes
114// with a blocking socket that contained the information related to the change, however, it was easy
115// to fill that socket and deadlock the system. Now we use locks to handle the property changes
116// directly in the property thread, however we still must wake the epoll to inform init that there
117// is a change to process, so we use this FD. It is non-blocking, since we do not care how many
Tom Cherry40463332020-03-26 20:32:17 -0700118// times WakeMainInitThread() is called, only that the epoll will wake.
119static int wake_main_thread_fd = -1;
Tom Cherry802864c2020-03-12 14:29:25 -0700120static void InstallInitNotifier(Epoll* epoll) {
Tom Cherry40463332020-03-26 20:32:17 -0700121 wake_main_thread_fd = eventfd(0, EFD_CLOEXEC);
122 if (wake_main_thread_fd == -1) {
123 PLOG(FATAL) << "Failed to create eventfd for waking init";
Tom Cherry802864c2020-03-12 14:29:25 -0700124 }
Tom Cherry40463332020-03-26 20:32:17 -0700125 auto clear_eventfd = [] {
126 uint64_t counter;
127 TEMP_FAILURE_RETRY(read(wake_main_thread_fd, &counter, sizeof(counter)));
Tom Cherry802864c2020-03-12 14:29:25 -0700128 };
129
Tom Cherry40463332020-03-26 20:32:17 -0700130 if (auto result = epoll->RegisterHandler(wake_main_thread_fd, clear_eventfd); !result.ok()) {
Tom Cherry802864c2020-03-12 14:29:25 -0700131 LOG(FATAL) << result.error();
132 }
133}
134
Tom Cherry40463332020-03-26 20:32:17 -0700135static void WakeMainInitThread() {
136 uint64_t counter = 1;
137 TEMP_FAILURE_RETRY(write(wake_main_thread_fd, &counter, sizeof(counter)));
Tom Cherry802864c2020-03-12 14:29:25 -0700138}
139
140static class PropWaiterState {
141 public:
142 bool StartWaiting(const char* name, const char* value) {
143 auto lock = std::lock_guard{lock_};
144 if (waiting_for_prop_) {
145 return false;
146 }
147 if (GetProperty(name, "") != value) {
148 // Current property value is not equal to expected value
149 wait_prop_name_ = name;
150 wait_prop_value_ = value;
151 waiting_for_prop_.reset(new Timer());
152 } else {
153 LOG(INFO) << "start_waiting_for_property(\"" << name << "\", \"" << value
154 << "\"): already set";
155 }
156 return true;
157 }
158
159 void ResetWaitForProp() {
160 auto lock = std::lock_guard{lock_};
161 ResetWaitForPropLocked();
162 }
163
164 void CheckAndResetWait(const std::string& name, const std::string& value) {
165 auto lock = std::lock_guard{lock_};
166 // We always record how long init waited for ueventd to tell us cold boot finished.
167 // If we aren't waiting on this property, it means that ueventd finished before we even
168 // started to wait.
169 if (name == kColdBootDoneProp) {
170 auto time_waited = waiting_for_prop_ ? waiting_for_prop_->duration().count() : 0;
171 std::thread([time_waited] {
172 SetProperty("ro.boottime.init.cold_boot_wait", std::to_string(time_waited));
173 }).detach();
174 }
175
176 if (waiting_for_prop_) {
177 if (wait_prop_name_ == name && wait_prop_value_ == value) {
178 LOG(INFO) << "Wait for property '" << wait_prop_name_ << "=" << wait_prop_value_
179 << "' took " << *waiting_for_prop_;
180 ResetWaitForPropLocked();
Tom Cherry40463332020-03-26 20:32:17 -0700181 WakeMainInitThread();
Tom Cherry802864c2020-03-12 14:29:25 -0700182 }
183 }
184 }
185
186 // This is not thread safe because it releases the lock when it returns, so the waiting state
187 // may change. However, we only use this function to prevent running commands in the main
188 // thread loop when we are waiting, so we do not care about false positives; only false
189 // negatives. StartWaiting() and this function are always called from the same thread, so false
190 // negatives are not possible and therefore we're okay.
191 bool MightBeWaiting() {
192 auto lock = std::lock_guard{lock_};
193 return static_cast<bool>(waiting_for_prop_);
194 }
195
196 private:
197 void ResetWaitForPropLocked() {
198 wait_prop_name_.clear();
199 wait_prop_value_.clear();
200 waiting_for_prop_.reset();
201 }
202
203 std::mutex lock_;
204 std::unique_ptr<Timer> waiting_for_prop_{nullptr};
205 std::string wait_prop_name_;
206 std::string wait_prop_value_;
207
208} prop_waiter_state;
209
210bool start_waiting_for_property(const char* name, const char* value) {
211 return prop_waiter_state.StartWaiting(name, value);
212}
213
214void ResetWaitForProp() {
215 prop_waiter_state.ResetWaitForProp();
216}
217
Tom Cherry1c688362020-03-24 18:00:23 -0700218static void UnwindMainThreadStack() {
219 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, 1));
220 if (!backtrace->Unwind(0)) {
221 LOG(ERROR) << __FUNCTION__ << ": Failed to unwind callstack.";
222 }
223 for (size_t i = 0; i < backtrace->NumFrames(); i++) {
224 LOG(ERROR) << backtrace->FormatFrameData(i);
225 }
226}
227
Tom Cherry802864c2020-03-12 14:29:25 -0700228static class ShutdownState {
229 public:
230 void TriggerShutdown(const std::string& command) {
231 // We can't call HandlePowerctlMessage() directly in this function,
232 // because it modifies the contents of the action queue, which can cause the action queue
233 // to get into a bad state if this function is called from a command being executed by the
234 // action queue. Instead we set this flag and ensure that shutdown happens before the next
235 // command is run in the main init loop.
236 auto lock = std::lock_guard{shutdown_command_lock_};
237 shutdown_command_ = command;
238 do_shutdown_ = true;
Tom Cherry40463332020-03-26 20:32:17 -0700239 WakeMainInitThread();
Tom Cherry802864c2020-03-12 14:29:25 -0700240 }
241
242 std::optional<std::string> CheckShutdown() {
243 auto lock = std::lock_guard{shutdown_command_lock_};
244 if (do_shutdown_ && !IsShuttingDown()) {
245 do_shutdown_ = false;
246 return shutdown_command_;
247 }
248 return {};
249 }
250
Tom Cherry080fa982020-03-27 14:31:08 -0700251 bool do_shutdown() const { return do_shutdown_; }
252
Tom Cherry802864c2020-03-12 14:29:25 -0700253 private:
254 std::mutex shutdown_command_lock_;
255 std::string shutdown_command_;
256 bool do_shutdown_ = false;
257} shutdown_state;
258
Tom Cherry080fa982020-03-27 14:31:08 -0700259void DebugRebootLogging() {
260 LOG(INFO) << "do_shutdown: " << shutdown_state.do_shutdown()
261 << " IsShuttingDown: " << IsShuttingDown();
262 if (shutdown_state.do_shutdown()) {
263 LOG(ERROR) << "sys.powerctl set while a previous shutdown command has not been handled";
264 UnwindMainThreadStack();
265 }
266 if (IsShuttingDown()) {
267 LOG(ERROR) << "sys.powerctl set while init is already shutting down";
268 UnwindMainThreadStack();
269 }
270}
271
Tom Cherry30a6f272017-04-19 15:31:58 -0700272void DumpState() {
Tom Cherry911b9b12017-07-27 16:20:58 -0700273 ServiceList::GetInstance().DumpState();
Tom Cherry30a6f272017-04-19 15:31:58 -0700274 ActionManager::GetInstance().DumpState();
275}
276
Tom Cherry911b9b12017-07-27 16:20:58 -0700277Parser CreateParser(ActionManager& action_manager, ServiceList& service_list) {
Tom Cherry67dee622017-07-27 12:54:48 -0700278 Parser parser;
279
Tom Cherry14c24722019-09-18 13:47:19 -0700280 parser.AddSectionParser("service", std::make_unique<ServiceParser>(
Tom Cherrye3e77d32020-04-28 13:55:19 -0700281 &service_list, GetSubcontext(), std::nullopt));
282 parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, GetSubcontext()));
Tom Cherry67dee622017-07-27 12:54:48 -0700283 parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
284
285 return parser;
286}
287
Jiyong Parkc2404402018-11-08 17:14:35 +0900288// parser that only accepts new services
Nikita Ioffe091c4d12019-12-05 12:35:19 +0000289Parser CreateServiceOnlyParser(ServiceList& service_list, bool from_apex) {
Jiyong Parkc2404402018-11-08 17:14:35 +0900290 Parser parser;
291
Tom Cherrye3e77d32020-04-28 13:55:19 -0700292 parser.AddSectionParser(
293 "service", std::make_unique<ServiceParser>(&service_list, GetSubcontext(), std::nullopt,
294 from_apex));
Jiyong Parkc2404402018-11-08 17:14:35 +0900295 return parser;
296}
297
Tom Cherry911b9b12017-07-27 16:20:58 -0700298static void LoadBootScripts(ActionManager& action_manager, ServiceList& service_list) {
299 Parser parser = CreateParser(action_manager, service_list);
Tom Cherry67dee622017-07-27 12:54:48 -0700300
301 std::string bootscript = GetProperty("ro.boot.init_rc", "");
302 if (bootscript.empty()) {
Tom Cherryc9f53532019-11-04 10:30:36 -0800303 parser.ParseConfig("/system/etc/init/hw/init.rc");
Tom Cherry67dee622017-07-27 12:54:48 -0700304 if (!parser.ParseConfig("/system/etc/init")) {
305 late_import_paths.emplace_back("/system/etc/init");
306 }
Justin Yun7eaf9b52019-06-28 14:28:00 +0900307 // late_import is available only in Q and earlier release. As we don't
308 // have system_ext in those versions, skip late_import for system_ext.
309 parser.ParseConfig("/system_ext/etc/init");
Jaekyun Seokdff165d2017-11-28 12:10:10 +0900310 if (!parser.ParseConfig("/product/etc/init")) {
311 late_import_paths.emplace_back("/product/etc/init");
Tom Cherry67dee622017-07-27 12:54:48 -0700312 }
313 if (!parser.ParseConfig("/odm/etc/init")) {
314 late_import_paths.emplace_back("/odm/etc/init");
315 }
Jaekyun Seokdff165d2017-11-28 12:10:10 +0900316 if (!parser.ParseConfig("/vendor/etc/init")) {
317 late_import_paths.emplace_back("/vendor/etc/init");
318 }
Tom Cherry67dee622017-07-27 12:54:48 -0700319 } else {
320 parser.ParseConfig(bootscript);
321 }
322}
323
Tom Cherry802864c2020-03-12 14:29:25 -0700324void PropertyChanged(const std::string& name, const std::string& value) {
Tom Cherry98ad32a2017-04-17 16:34:20 -0700325 // If the property is sys.powerctl, we bypass the event queue and immediately handle it.
326 // This is to ensure that init will always and immediately shutdown/reboot, regardless of
327 // if there are other pending events to process or if init is waiting on an exec service or
328 // waiting on a property.
Wei Wangeeab4912017-06-27 22:08:45 -0700329 // In non-thermal-shutdown case, 'shutdown' trigger will be fired to let device specific
330 // commands to be executed.
331 if (name == "sys.powerctl") {
Tom Cherry802864c2020-03-12 14:29:25 -0700332 trigger_shutdown(value);
Wei Wangeeab4912017-06-27 22:08:45 -0700333 }
Tom Cherry98ad32a2017-04-17 16:34:20 -0700334
Tom Cherry802864c2020-03-12 14:29:25 -0700335 if (property_triggers_enabled) {
336 ActionManager::GetInstance().QueuePropertyChange(name, value);
Tom Cherry40463332020-03-26 20:32:17 -0700337 WakeMainInitThread();
Tom Cherry39fafed2019-06-10 17:49:59 -0700338 }
339
Tom Cherry802864c2020-03-12 14:29:25 -0700340 prop_waiter_state.CheckAndResetWait(name, value);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700341}
342
Tom Cherry73f535e2018-09-27 16:10:46 -0700343static std::optional<boot_clock::time_point> HandleProcessActions() {
344 std::optional<boot_clock::time_point> next_process_action_time;
Tom Cherry911b9b12017-07-27 16:20:58 -0700345 for (const auto& s : ServiceList::GetInstance()) {
Tom Cherry73f535e2018-09-27 16:10:46 -0700346 if ((s->flags() & SVC_RUNNING) && s->timeout_period()) {
347 auto timeout_time = s->time_started() + *s->timeout_period();
348 if (boot_clock::now() > timeout_time) {
349 s->Timeout();
350 } else {
351 if (!next_process_action_time || timeout_time < *next_process_action_time) {
352 next_process_action_time = timeout_time;
353 }
354 }
355 }
356
Tom Cherry911b9b12017-07-27 16:20:58 -0700357 if (!(s->flags() & SVC_RESTARTING)) continue;
Tom Cherryd269e3a2017-07-31 13:23:18 -0700358
Tom Cherry73f535e2018-09-27 16:10:46 -0700359 auto restart_time = s->time_started() + s->restart_period();
Tom Cherryd269e3a2017-07-31 13:23:18 -0700360 if (boot_clock::now() > restart_time) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900361 if (auto result = s->Start(); !result.ok()) {
Tom Cherry702ca9a2017-08-25 10:36:52 -0700362 LOG(ERROR) << "Could not restart process '" << s->name() << "': " << result.error();
363 }
Tom Cherryd269e3a2017-07-31 13:23:18 -0700364 } else {
Tom Cherry73f535e2018-09-27 16:10:46 -0700365 if (!next_process_action_time || restart_time < *next_process_action_time) {
366 next_process_action_time = restart_time;
Tom Cherryd269e3a2017-07-31 13:23:18 -0700367 }
368 }
Tom Cherry911b9b12017-07-27 16:20:58 -0700369 }
Tom Cherry73f535e2018-09-27 16:10:46 -0700370 return next_process_action_time;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700371}
372
Tom Cherry832f9f12020-03-10 11:47:24 -0700373static Result<void> DoControlStart(Service* service) {
Steven Morelande055d732017-10-05 18:50:22 -0700374 return service->Start();
375}
376
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700377static Result<void> DoControlStop(Service* service) {
Steven Morelande055d732017-10-05 18:50:22 -0700378 service->Stop();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700379 return {};
Steven Morelande055d732017-10-05 18:50:22 -0700380}
381
Tom Cherry832f9f12020-03-10 11:47:24 -0700382static Result<void> DoControlRestart(Service* service) {
Steven Morelande055d732017-10-05 18:50:22 -0700383 service->Restart();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700384 return {};
Steven Morelande055d732017-10-05 18:50:22 -0700385}
386
387enum class ControlTarget {
388 SERVICE, // function gets called for the named service
389 INTERFACE, // action gets called for every service that holds this interface
390};
391
Tom Cherrybdbf5042020-03-04 10:52:08 -0800392using ControlMessageFunction = std::function<Result<void>(Service*)>;
Steven Morelande055d732017-10-05 18:50:22 -0700393
Tom Cherrybdbf5042020-03-04 10:52:08 -0800394static const std::map<std::string, ControlMessageFunction, std::less<>>& GetControlMessageMap() {
Steven Morelande055d732017-10-05 18:50:22 -0700395 // clang-format off
Tom Cherrybdbf5042020-03-04 10:52:08 -0800396 static const std::map<std::string, ControlMessageFunction, std::less<>> control_message_functions = {
397 {"sigstop_on", [](auto* service) { service->set_sigstop(true); return Result<void>{}; }},
398 {"sigstop_off", [](auto* service) { service->set_sigstop(false); return Result<void>{}; }},
399 {"oneshot_on", [](auto* service) { service->set_oneshot(true); return Result<void>{}; }},
400 {"oneshot_off", [](auto* service) { service->set_oneshot(false); return Result<void>{}; }},
401 {"start", DoControlStart},
402 {"stop", DoControlStop},
403 {"restart", DoControlRestart},
Steven Morelande055d732017-10-05 18:50:22 -0700404 };
405 // clang-format on
406
407 return control_message_functions;
408}
409
Tom Cherrybdbf5042020-03-04 10:52:08 -0800410static bool HandleControlMessage(std::string_view message, const std::string& name,
411 pid_t from_pid) {
412 std::string cmdline_path = StringPrintf("proc/%d/cmdline", from_pid);
Tom Cherry6f2d56d2018-02-21 10:37:44 -0800413 std::string process_cmdline;
414 if (ReadFileToString(cmdline_path, &process_cmdline)) {
415 std::replace(process_cmdline.begin(), process_cmdline.end(), '\0', ' ');
416 process_cmdline = Trim(process_cmdline);
417 } else {
418 process_cmdline = "unknown process";
419 }
420
Tom Cherrybdbf5042020-03-04 10:52:08 -0800421 Service* service = nullptr;
422 auto action = message;
423 if (ConsumePrefix(&action, "interface_")) {
424 service = ServiceList::GetInstance().FindInterface(name);
425 } else {
426 service = ServiceList::GetInstance().FindService(name);
Steven Moreland6227e342018-05-08 13:46:39 -0700427 }
428
Tom Cherrybdbf5042020-03-04 10:52:08 -0800429 if (service == nullptr) {
430 LOG(ERROR) << "Control message: Could not find '" << name << "' for ctl." << message
431 << " from pid: " << from_pid << " (" << process_cmdline << ")";
Wei Wang5f01d3a2019-05-23 12:13:29 -0700432 return false;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700433 }
Steven Morelande055d732017-10-05 18:50:22 -0700434
Tom Cherrybdbf5042020-03-04 10:52:08 -0800435 const auto& map = GetControlMessageMap();
436 const auto it = map.find(action);
437 if (it == map.end()) {
438 LOG(ERROR) << "Unknown control msg '" << message << "'";
439 return false;
440 }
441 const auto& function = it->second;
442
443 if (auto result = function(service); !result.ok()) {
444 LOG(ERROR) << "Control message: Could not ctl." << message << " for '" << name
445 << "' from pid: " << from_pid << " (" << process_cmdline
446 << "): " << result.error();
Wei Wang5f01d3a2019-05-23 12:13:29 -0700447 return false;
Steven Morelande055d732017-10-05 18:50:22 -0700448 }
Steven Moreland9800ad82019-08-28 18:34:24 -0700449
Tom Cherrybdbf5042020-03-04 10:52:08 -0800450 LOG(INFO) << "Control message: Processed ctl." << message << " for '" << name
451 << "' from pid: " << from_pid << " (" << process_cmdline << ")";
Wei Wang5f01d3a2019-05-23 12:13:29 -0700452 return true;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700453}
454
Tom Cherry802864c2020-03-12 14:29:25 -0700455bool QueueControlMessage(const std::string& message, const std::string& name, pid_t pid, int fd) {
456 auto lock = std::lock_guard{pending_control_messages_lock};
457 if (pending_control_messages.size() > 100) {
458 LOG(ERROR) << "Too many pending control messages, dropped '" << message << "' for '" << name
459 << "' from pid: " << pid;
460 return false;
461 }
462 pending_control_messages.push({message, name, pid, fd});
Tom Cherry40463332020-03-26 20:32:17 -0700463 WakeMainInitThread();
Tom Cherry802864c2020-03-12 14:29:25 -0700464 return true;
465}
466
467static void HandleControlMessages() {
468 auto lock = std::unique_lock{pending_control_messages_lock};
469 // Init historically would only execute handle one property message, including control messages
470 // in each iteration of its main loop. We retain this behavior here to prevent starvation of
471 // other actions in the main loop.
472 if (!pending_control_messages.empty()) {
473 auto control_message = pending_control_messages.front();
474 pending_control_messages.pop();
475 lock.unlock();
476
477 bool success = HandleControlMessage(control_message.message, control_message.name,
478 control_message.pid);
479
480 uint32_t response = success ? PROP_SUCCESS : PROP_ERROR_HANDLE_CONTROL_MESSAGE;
481 if (control_message.fd != -1) {
482 TEMP_FAILURE_RETRY(send(control_message.fd, &response, sizeof(response), 0));
483 close(control_message.fd);
484 }
485 lock.lock();
486 }
487 // If we still have items to process, make sure we wake back up to do so.
488 if (!pending_control_messages.empty()) {
Tom Cherry40463332020-03-26 20:32:17 -0700489 WakeMainInitThread();
Tom Cherry802864c2020-03-12 14:29:25 -0700490 }
491}
492
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700493static Result<void> wait_for_coldboot_done_action(const BuiltinArguments& args) {
Tom Cherry802864c2020-03-12 14:29:25 -0700494 if (!prop_waiter_state.StartWaiting(kColdBootDoneProp, "true")) {
Tom Cherry39fafed2019-06-10 17:49:59 -0700495 LOG(FATAL) << "Could not wait for '" << kColdBootDoneProp << "'";
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700496 }
497
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700498 return {};
Colin Crossebc6ff12010-04-13 19:52:01 -0700499}
500
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700501static Result<void> SetupCgroupsAction(const BuiltinArguments&) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800502 // Have to create <CGROUPS_RC_DIR> using make_dir function
503 // for appropriate sepolicy to be set for it
Suren Baghdasaryan5b535732019-03-26 20:34:32 +0000504 make_dir(android::base::Dirname(CGROUPS_RC_PATH), 0711);
Yifan Hong9d7b89a2019-04-02 15:10:40 -0700505 if (!CgroupSetup()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800506 return ErrnoError() << "Failed to setup cgroups";
507 }
508
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700509 return {};
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800510}
511
Sami Tolvanen9e9efca2015-12-07 12:33:58 +0000512static void export_oem_lock_status() {
Tom Cherryccf23532017-03-28 16:40:41 -0700513 if (!android::base::GetBoolProperty("ro.oem_unlock_supported", false)) {
Sami Tolvanen9e9efca2015-12-07 12:33:58 +0000514 return;
515 }
Tom Cherryc88d8f92019-08-19 15:21:25 -0700516 ImportKernelCmdline([](const std::string& key, const std::string& value) {
517 if (key == "androidboot.verifiedbootstate") {
518 SetProperty("ro.boot.flash.locked", value == "orange" ? "0" : "1");
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700519 }
Tom Cherryc88d8f92019-08-19 15:21:25 -0700520 });
Colin Crossebc6ff12010-04-13 19:52:01 -0700521}
522
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700523static Result<void> property_enable_triggers_action(const BuiltinArguments& args) {
caozhiyuanb104c502016-11-26 21:14:07 +0800524 /* Enable property triggers. */
525 property_triggers_enabled = 1;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700526 return {};
caozhiyuanb104c502016-11-26 21:14:07 +0800527}
528
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700529static Result<void> queue_property_triggers_action(const BuiltinArguments& args) {
caozhiyuanb104c502016-11-26 21:14:07 +0800530 ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger");
Tom Cherry26ed9cb2017-04-17 13:25:29 -0700531 ActionManager::GetInstance().QueueAllPropertyActions();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700532 return {};
Colin Crossebc6ff12010-04-13 19:52:01 -0700533}
534
Amit Pundird2e74db2016-06-29 19:00:00 +0530535// Set the UDC controller for the ConfigFS USB Gadgets.
536// Read the UDC controller in use from "/sys/class/udc".
537// In case of multiple UDC controllers select the first one.
538static void set_usb_controller() {
539 std::unique_ptr<DIR, decltype(&closedir)>dir(opendir("/sys/class/udc"), closedir);
540 if (!dir) return;
541
542 dirent* dp;
543 while ((dp = readdir(dir.get())) != nullptr) {
544 if (dp->d_name[0] == '.') continue;
545
Tom Cherryc88d8f92019-08-19 15:21:25 -0700546 SetProperty("sys.usb.controller", dp->d_name);
Amit Pundird2e74db2016-06-29 19:00:00 +0530547 break;
548 }
549}
550
Ryan Prichard1325ec82018-04-11 18:46:38 -0700551static void HandleSigtermSignal(const signalfd_siginfo& siginfo) {
Luis Hector Chavez9f97f472017-09-06 13:43:57 -0700552 if (siginfo.ssi_pid != 0) {
553 // Drop any userspace SIGTERM requests.
554 LOG(DEBUG) << "Ignoring SIGTERM from pid " << siginfo.ssi_pid;
555 return;
556 }
557
Mark Salyzyn161b8622017-09-26 08:26:12 -0700558 HandlePowerctlMessage("shutdown,container");
Luis Hector Chavez9f97f472017-09-06 13:43:57 -0700559}
560
Ryan Prichard1325ec82018-04-11 18:46:38 -0700561static void HandleSignalFd() {
562 signalfd_siginfo siginfo;
563 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(signal_fd, &siginfo, sizeof(siginfo)));
564 if (bytes_read != sizeof(siginfo)) {
565 PLOG(ERROR) << "Failed to read siginfo from signal_fd";
566 return;
567 }
yusukes4a4ec14e2018-02-01 17:14:30 -0800568
Ryan Prichard1325ec82018-04-11 18:46:38 -0700569 switch (siginfo.ssi_signo) {
570 case SIGCHLD:
571 ReapAnyOutstandingChildren();
572 break;
573 case SIGTERM:
574 HandleSigtermSignal(siginfo);
575 break;
576 default:
577 PLOG(ERROR) << "signal_fd: received unexpected signal " << siginfo.ssi_signo;
578 break;
yusukes4a4ec14e2018-02-01 17:14:30 -0800579 }
580}
581
Ryan Prichard1325ec82018-04-11 18:46:38 -0700582static void UnblockSignals() {
583 const struct sigaction act { .sa_handler = SIG_DFL };
584 sigaction(SIGCHLD, &act, nullptr);
585
Luis Hector Chavez9f97f472017-09-06 13:43:57 -0700586 sigset_t mask;
587 sigemptyset(&mask);
Ryan Prichard1325ec82018-04-11 18:46:38 -0700588 sigaddset(&mask, SIGCHLD);
Luis Hector Chavez9f97f472017-09-06 13:43:57 -0700589 sigaddset(&mask, SIGTERM);
590
Ryan Prichard1325ec82018-04-11 18:46:38 -0700591 if (sigprocmask(SIG_UNBLOCK, &mask, nullptr) == -1) {
592 PLOG(FATAL) << "failed to unblock signals for PID " << getpid();
593 }
594}
595
Mark Salyzyn6c6ec722015-10-24 16:20:18 -0700596static void InstallSignalFdHandler(Epoll* epoll) {
Ryan Prichard1325ec82018-04-11 18:46:38 -0700597 // Applying SA_NOCLDSTOP to a defaulted SIGCHLD handler prevents the signalfd from receiving
598 // SIGCHLD when a child process stops or continues (b/77867680#comment9).
599 const struct sigaction act { .sa_handler = SIG_DFL, .sa_flags = SA_NOCLDSTOP };
600 sigaction(SIGCHLD, &act, nullptr);
601
602 sigset_t mask;
603 sigemptyset(&mask);
604 sigaddset(&mask, SIGCHLD);
605
606 if (!IsRebootCapable()) {
607 // If init does not have the CAP_SYS_BOOT capability, it is running in a container.
608 // In that case, receiving SIGTERM will cause the system to shut down.
609 sigaddset(&mask, SIGTERM);
Luis Hector Chavez9f97f472017-09-06 13:43:57 -0700610 }
611
Ryan Prichard1325ec82018-04-11 18:46:38 -0700612 if (sigprocmask(SIG_BLOCK, &mask, nullptr) == -1) {
613 PLOG(FATAL) << "failed to block signals";
614 }
615
616 // Register a handler to unblock signals in the child processes.
617 const int result = pthread_atfork(nullptr, nullptr, &UnblockSignals);
yusukes4a4ec14e2018-02-01 17:14:30 -0800618 if (result != 0) {
619 LOG(FATAL) << "Failed to register a fork handler: " << strerror(result);
620 }
621
Ryan Prichard1325ec82018-04-11 18:46:38 -0700622 signal_fd = signalfd(-1, &mask, SFD_CLOEXEC);
623 if (signal_fd == -1) {
624 PLOG(FATAL) << "failed to create signalfd";
Luis Hector Chavez9f97f472017-09-06 13:43:57 -0700625 }
626
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900627 if (auto result = epoll->RegisterHandler(signal_fd, HandleSignalFd); !result.ok()) {
Mark Salyzyn6c6ec722015-10-24 16:20:18 -0700628 LOG(FATAL) << result.error();
629 }
Luis Hector Chavez9f97f472017-09-06 13:43:57 -0700630}
631
Mark Salyzyn13857252018-05-18 15:25:15 -0700632void HandleKeychord(const std::vector<int>& keycodes) {
Mark Salyzyneca25072018-05-16 15:10:24 -0700633 // Only handle keychords if adb is enabled.
634 std::string adb_enabled = android::base::GetProperty("init.svc.adbd", "");
Mark Salyzyn13857252018-05-18 15:25:15 -0700635 if (adb_enabled != "running") {
636 LOG(WARNING) << "Not starting service for keychord " << android::base::Join(keycodes, ' ')
637 << " because ADB is disabled";
638 return;
639 }
640
641 auto found = false;
642 for (const auto& service : ServiceList::GetInstance()) {
643 auto svc = service.get();
644 if (svc->keycodes() == keycodes) {
645 found = true;
646 LOG(INFO) << "Starting service '" << svc->name() << "' from keychord "
647 << android::base::Join(keycodes, ' ');
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900648 if (auto result = svc->Start(); !result.ok()) {
Mark Salyzyn13857252018-05-18 15:25:15 -0700649 LOG(ERROR) << "Could not start service '" << svc->name() << "' from keychord "
650 << android::base::Join(keycodes, ' ') << ": " << result.error();
Mark Salyzyneca25072018-05-16 15:10:24 -0700651 }
Mark Salyzyneca25072018-05-16 15:10:24 -0700652 }
Mark Salyzyn13857252018-05-18 15:25:15 -0700653 }
654 if (!found) {
655 LOG(ERROR) << "Service for keychord " << android::base::Join(keycodes, ' ') << " not found";
Mark Salyzyneca25072018-05-16 15:10:24 -0700656 }
657}
658
Bowgo Tsai30afda72019-04-11 23:57:24 +0800659static void UmountDebugRamdisk() {
660 if (umount("/debug_ramdisk") != 0) {
Kiyoung Kim99df54b2019-11-22 16:14:10 +0900661 PLOG(ERROR) << "Failed to umount /debug_ramdisk";
Bowgo Tsai30afda72019-04-11 23:57:24 +0800662 }
663}
664
Kiyoung Kim99df54b2019-11-22 16:14:10 +0900665static void MountExtraFilesystems() {
666#define CHECKCALL(x) \
667 if ((x) != 0) PLOG(FATAL) << #x " failed.";
668
669 // /apex is used to mount APEXes
670 CHECKCALL(mount("tmpfs", "/apex", "tmpfs", MS_NOEXEC | MS_NOSUID | MS_NODEV,
671 "mode=0755,uid=0,gid=0"));
672
673 // /linkerconfig is used to keep generated linker configuration
674 CHECKCALL(mount("tmpfs", "/linkerconfig", "tmpfs", MS_NOEXEC | MS_NOSUID | MS_NODEV,
675 "mode=0755,uid=0,gid=0"));
676#undef CHECKCALL
677}
678
Mark Salyzyn10377df2019-03-27 08:10:41 -0700679static void RecordStageBoottimes(const boot_clock::time_point& second_stage_start_time) {
680 int64_t first_stage_start_time_ns = -1;
Mark Salyzyn44505ec2019-05-08 12:44:50 -0700681 if (auto first_stage_start_time_str = getenv(kEnvFirstStageStartedAt);
Mark Salyzyn10377df2019-03-27 08:10:41 -0700682 first_stage_start_time_str) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700683 SetProperty("ro.boottime.init", first_stage_start_time_str);
Mark Salyzyn10377df2019-03-27 08:10:41 -0700684 android::base::ParseInt(first_stage_start_time_str, &first_stage_start_time_ns);
685 }
Mark Salyzyn44505ec2019-05-08 12:44:50 -0700686 unsetenv(kEnvFirstStageStartedAt);
Mark Salyzyn10377df2019-03-27 08:10:41 -0700687
688 int64_t selinux_start_time_ns = -1;
Mark Salyzyn44505ec2019-05-08 12:44:50 -0700689 if (auto selinux_start_time_str = getenv(kEnvSelinuxStartedAt); selinux_start_time_str) {
Mark Salyzyn10377df2019-03-27 08:10:41 -0700690 android::base::ParseInt(selinux_start_time_str, &selinux_start_time_ns);
691 }
Mark Salyzyn44505ec2019-05-08 12:44:50 -0700692 unsetenv(kEnvSelinuxStartedAt);
Mark Salyzyn10377df2019-03-27 08:10:41 -0700693
694 if (selinux_start_time_ns == -1) return;
695 if (first_stage_start_time_ns == -1) return;
696
Tom Cherryc88d8f92019-08-19 15:21:25 -0700697 SetProperty("ro.boottime.init.first_stage",
698 std::to_string(selinux_start_time_ns - first_stage_start_time_ns));
699 SetProperty("ro.boottime.init.selinux",
700 std::to_string(second_stage_start_time.time_since_epoch().count() -
701 selinux_start_time_ns));
Mark Salyzyn10377df2019-03-27 08:10:41 -0700702}
703
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700704void SendLoadPersistentPropertiesMessage() {
705 auto init_message = InitMessage{};
706 init_message.set_load_persistent_properties(true);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900707 if (auto result = SendMessage(property_fd, init_message); !result.ok()) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700708 LOG(ERROR) << "Failed to send load persistent properties message: " << result.error();
709 }
710}
711
Tom Cherry7bfea3d2018-11-06 14:12:05 -0800712int SecondStageMain(int argc, char** argv) {
Tom Cherry663fdfc2017-03-10 14:46:38 -0800713 if (REBOOT_BOOTLOADER_ON_PANIC) {
Tom Cherry1ca83242017-08-25 15:10:48 -0700714 InstallRebootSignalHandlers();
Tom Cherry663fdfc2017-03-10 14:46:38 -0800715 }
716
Mark Salyzyn10377df2019-03-27 08:10:41 -0700717 boot_clock::time_point start_time = boot_clock::now();
718
Tom Cherry802864c2020-03-12 14:29:25 -0700719 trigger_shutdown = [](const std::string& command) { shutdown_state.TriggerShutdown(command); };
Tom Cherry18278d22019-11-12 16:21:20 -0800720
Tom Cherry59656fb2019-05-28 10:19:44 -0700721 SetStdioToDevNull(argv);
722 InitKernelLogging(argv);
Tom Cherry34e70412017-03-16 18:08:56 -0700723 LOG(INFO) << "init second stage started!";
724
Tom Cherryfd470e82020-03-16 10:17:05 -0700725 // Init should not crash because of a dependence on any other process, therefore we ignore
726 // SIGPIPE and handle EPIPE at the call site directly. Note that setting a signal to SIG_IGN
727 // is inherited across exec, but custom signal handlers are not. Since we do not want to
728 // ignore SIGPIPE for child processes, we set a no-op function for the signal handler instead.
729 {
730 struct sigaction action = {.sa_flags = SA_RESTART};
731 action.sa_handler = [](int) {};
732 sigaction(SIGPIPE, &action, nullptr);
733 }
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -0700734
Wei Wang45d81742019-04-18 14:56:24 -0700735 // Set init and its forked children's oom_adj.
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -0700736 if (auto result =
737 WriteFile("/proc/1/oom_score_adj", StringPrintf("%d", DEFAULT_OOM_SCORE_ADJUST));
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900738 !result.ok()) {
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -0700739 LOG(ERROR) << "Unable to write " << DEFAULT_OOM_SCORE_ADJUST
740 << " to /proc/1/oom_score_adj: " << result.error();
Wei Wang45d81742019-04-18 14:56:24 -0700741 }
742
Mark Salyzyn45996272017-05-02 14:44:39 -0700743 // Set up a session keyring that all processes will have access to. It
744 // will hold things like FBE encryption keys. No process should override
745 // its session keyring.
Elliott Hughesf8627ce2017-05-09 17:09:06 -0700746 keyctl_get_keyring_ID(KEY_SPEC_SESSION_KEYRING, 1);
Mark Salyzyn45996272017-05-02 14:44:39 -0700747
Tom Cherry34e70412017-03-16 18:08:56 -0700748 // Indicate that booting is in progress to background fw loaders, etc.
749 close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
750
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800751 // See if need to load debug props to allow adb root, when the device is unlocked.
752 const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
Tom Cherryc88d8f92019-08-19 15:21:25 -0700753 bool load_debug_prop = false;
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800754 if (force_debuggable_env && AvbHandle::IsDeviceUnlocked()) {
755 load_debug_prop = "true"s == force_debuggable_env;
756 }
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800757 unsetenv("INIT_FORCE_DEBUGGABLE");
Tom Cherry34e70412017-03-16 18:08:56 -0700758
Tom Cherryc88d8f92019-08-19 15:21:25 -0700759 // Umount the debug ramdisk so property service doesn't read .prop files from there, when it
760 // is not meant to.
761 if (!load_debug_prop) {
762 UmountDebugRamdisk();
763 }
764
765 PropertyInit();
766
767 // Umount the debug ramdisk after property service has read the .prop files when it means to.
768 if (load_debug_prop) {
769 UmountDebugRamdisk();
770 }
771
Kiyoung Kim99df54b2019-11-22 16:14:10 +0900772 // Mount extra filesystems required during second stage init
773 MountExtraFilesystems();
774
Tom Cherry34e70412017-03-16 18:08:56 -0700775 // Now set up SELinux for second stage.
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700776 SelinuxSetupKernelLogging();
777 SelabelInitialize();
778 SelinuxRestoreContext();
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500779
Mark Salyzyn6c6ec722015-10-24 16:20:18 -0700780 Epoll epoll;
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900781 if (auto result = epoll.Open(); !result.ok()) {
Mark Salyzyn6c6ec722015-10-24 16:20:18 -0700782 PLOG(FATAL) << result.error();
Elliott Hughes929f4072015-04-24 21:13:44 -0700783 }
784
Mark Salyzyn6c6ec722015-10-24 16:20:18 -0700785 InstallSignalFdHandler(&epoll);
Tom Cherry802864c2020-03-12 14:29:25 -0700786 InstallInitNotifier(&epoll);
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700787 StartPropertyService(&property_fd);
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700788
Tom Cherryc88d8f92019-08-19 15:21:25 -0700789 // Make the time that init stages started available for bootstat to log.
790 RecordStageBoottimes(start_time);
791
792 // Set libavb version for Framework-only OTA match in Treble build.
793 if (const char* avb_version = getenv("INIT_AVB_VERSION"); avb_version != nullptr) {
794 SetProperty("ro.boot.avb_version", avb_version);
795 }
796 unsetenv("INIT_AVB_VERSION");
797
798 fs_mgr_vendor_overlay_mount_all();
799 export_oem_lock_status();
Mark Salyzyna73ed222019-03-13 10:18:24 -0700800 MountHandler mount_handler(&epoll);
Amit Pundird2e74db2016-06-29 19:00:00 +0530801 set_usb_controller();
Dima Zavind7634c92011-12-16 14:18:06 -0800802
Tom Cherryd52a5b32019-07-22 16:05:36 -0700803 const BuiltinFunctionMap& function_map = GetBuiltinFunctionMap();
Tom Cherryb7349902015-08-26 11:43:36 -0700804 Action::set_function_map(&function_map);
805
Jiyong Park68660412019-01-16 23:00:59 +0900806 if (!SetupMountNamespaces()) {
807 PLOG(FATAL) << "SetupMountNamespaces failed";
808 }
809
Tom Cherrye3e77d32020-04-28 13:55:19 -0700810 InitializeSubcontext();
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700811
Tom Cherry30a6f272017-04-19 15:31:58 -0700812 ActionManager& am = ActionManager::GetInstance();
Tom Cherry911b9b12017-07-27 16:20:58 -0700813 ServiceList& sm = ServiceList::GetInstance();
Tom Cherry30a6f272017-04-19 15:31:58 -0700814
Tom Cherry67dee622017-07-27 12:54:48 -0700815 LoadBootScripts(am, sm);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700816
Tom Cherryd8a72572017-03-13 12:24:49 -0700817 // Turning this on and letting the INFO logging be discarded adds 0.2s to
818 // Nexus 9 boot time, so it's disabled by default.
Tom Cherry30a6f272017-04-19 15:31:58 -0700819 if (false) DumpState();
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700820
David Anderson372278c2019-02-14 12:46:13 -0800821 // Make the GSI status available before scripts start running.
Howard Chen2e1c6b22020-02-25 16:31:10 +0800822 auto is_running = android::gsi::IsGsiRunning() ? "1" : "0";
823 SetProperty(gsi::kGsiBootedProp, is_running);
824 auto is_installed = android::gsi::IsGsiInstalled() ? "1" : "0";
825 SetProperty(gsi::kGsiInstalledProp, is_installed);
David Anderson372278c2019-02-14 12:46:13 -0800826
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800827 am.QueueBuiltinAction(SetupCgroupsAction, "SetupCgroups");
Ravi Kumar Siddojigari33783fc2019-07-30 16:41:20 +0530828 am.QueueBuiltinAction(SetKptrRestrictAction, "SetKptrRestrict");
Ryan Savitskif0f7e702020-01-14 22:02:53 +0000829 am.QueueBuiltinAction(TestPerfEventSelinuxAction, "TestPerfEventSelinux");
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700830 am.QueueEventTrigger("early-init");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700831
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700832 // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev...
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700833 am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700834 // ... so that we can start queuing up actions that require stuff from /dev.
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700835 am.QueueBuiltinAction(MixHwrngIntoLinuxRngAction, "MixHwrngIntoLinuxRng");
836 am.QueueBuiltinAction(SetMmapRndBitsAction, "SetMmapRndBits");
Mark Salyzyn06aeb412018-05-18 15:25:15 -0700837 Keychords keychords;
Mark Salyzyn6c6ec722015-10-24 16:20:18 -0700838 am.QueueBuiltinAction(
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700839 [&epoll, &keychords](const BuiltinArguments& args) -> Result<void> {
840 for (const auto& svc : ServiceList::GetInstance()) {
841 keychords.Register(svc->keycodes());
842 }
843 keychords.Start(&epoll, HandleKeychord);
844 return {};
845 },
846 "KeychordInit");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700847
Elliott Hughesda40c002015-03-27 23:20:44 -0700848 // Trigger all the boot actions to get us started.
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700849 am.QueueEventTrigger("init");
Dima Zavinca47cef2011-08-24 15:28:23 -0700850
Elliott Hughes8d82ea02015-02-06 20:15:18 -0800851 // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
852 // wasn't ready immediately after wait_for_coldboot_done
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700853 am.QueueBuiltinAction(MixHwrngIntoLinuxRngAction, "MixHwrngIntoLinuxRng");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700854
Elliott Hughes8d82ea02015-02-06 20:15:18 -0800855 // Don't mount filesystems or start core system services in charger mode.
Tom Cherryccf23532017-03-28 16:40:41 -0700856 std::string bootmode = GetProperty("ro.bootmode", "");
Yabin Cui74edcea2015-07-24 10:11:05 -0700857 if (bootmode == "charger") {
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700858 am.QueueEventTrigger("charger");
Dima Zavinca47cef2011-08-24 15:28:23 -0700859 } else {
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700860 am.QueueEventTrigger("late-init");
Dima Zavinca47cef2011-08-24 15:28:23 -0700861 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700862
Elliott Hughes8d82ea02015-02-06 20:15:18 -0800863 // Run all property triggers based on current state of the properties.
Tom Cherryfa0c21c2015-07-23 17:53:11 -0700864 am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700865
Elliott Hughesc6c26ed2015-04-24 18:50:30 -0700866 while (true) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800867 // By default, sleep until something happens.
Mark Salyzyn6c6ec722015-10-24 16:20:18 -0700868 auto epoll_timeout = std::optional<std::chrono::milliseconds>{};
Elliott Hughes9605a942016-11-10 17:43:47 -0800869
Tom Cherry802864c2020-03-12 14:29:25 -0700870 auto shutdown_command = shutdown_state.CheckShutdown();
871 if (shutdown_command) {
Tom Cherry1c688362020-03-24 18:00:23 -0700872 LOG(INFO) << "Got shutdown_command '" << *shutdown_command
873 << "' Calling HandlePowerctlMessage()";
Tom Cherry802864c2020-03-12 14:29:25 -0700874 HandlePowerctlMessage(*shutdown_command);
Tom Cherry3633a402017-09-13 14:39:45 -0700875 }
876
Tom Cherry802864c2020-03-12 14:29:25 -0700877 if (!(prop_waiter_state.MightBeWaiting() || Service::is_exec_service_running())) {
Tom Cherry77ddcd52017-03-23 16:54:38 -0700878 am.ExecuteOneCommand();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700879 }
Tom Cherry44d5ec32020-01-31 08:33:36 -0800880 if (!IsShuttingDown()) {
881 auto next_process_action_time = HandleProcessActions();
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700882
Tom Cherry44d5ec32020-01-31 08:33:36 -0800883 // If there's a process that needs restarting, wake up in time for that.
884 if (next_process_action_time) {
885 epoll_timeout = std::chrono::ceil<std::chrono::milliseconds>(
886 *next_process_action_time - boot_clock::now());
887 if (*epoll_timeout < 0ms) epoll_timeout = 0ms;
Tom Cherry77ddcd52017-03-23 16:54:38 -0700888 }
Tom Cherry44d5ec32020-01-31 08:33:36 -0800889 }
Tom Cherry77ddcd52017-03-23 16:54:38 -0700890
Tom Cherry802864c2020-03-12 14:29:25 -0700891 if (!(prop_waiter_state.MightBeWaiting() || Service::is_exec_service_running())) {
Tom Cherry77ddcd52017-03-23 16:54:38 -0700892 // If there's more work to do, wake up again immediately.
Mark Salyzyn6c6ec722015-10-24 16:20:18 -0700893 if (am.HasMoreCommands()) epoll_timeout = 0ms;
Tom Cherry77ddcd52017-03-23 16:54:38 -0700894 }
Wei Wang16db4342016-11-30 15:43:42 -0800895
Tom Cherry905a5df2019-08-30 14:12:56 -0700896 auto pending_functions = epoll.Wait(epoll_timeout);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900897 if (!pending_functions.ok()) {
Tom Cherry905a5df2019-08-30 14:12:56 -0700898 LOG(ERROR) << pending_functions.error();
899 } else if (!pending_functions->empty()) {
900 // We always reap children before responding to the other pending functions. This is to
901 // prevent a race where other daemons see that a service has exited and ask init to
902 // start it again via ctl.start before init has reaped it.
903 ReapAnyOutstandingChildren();
904 for (const auto& function : *pending_functions) {
905 (*function)();
906 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700907 }
Tom Cherry22d63482020-03-27 14:08:20 -0700908 if (!IsShuttingDown()) {
909 HandleControlMessages();
910 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700911 }
912
913 return 0;
914}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700915
916} // namespace init
917} // namespace android