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