引言
安卓系统的启动过程如下:
整个流程分为四个阶段,即引导阶段、内核启动阶段、用户态init阶段、Zygote启动阶段。由于安卓系统内核基于linux修剪而成,其引导和内核启动与linux基本相同,差异性的是用户态init阶段和Zygote启动阶段,特别是Zygote阶段是安卓特有的。
注 1 :本文中断解析用户态init阶段和Zygote启动阶段,引导阶段和内核启动阶段不做剖析。
1 用户态init阶段
1.1 流程概述
用户态第一个进程init的入口main函数在/system/core/init/init.cpp文件中。整个流程大致归纳如下:
整个流程分为五步。首先,过滤非init进程选项,因为有些进行也是从该入口启动;第二步,盘断设备是否是第一次启动,若是进行初始化设置设备;第三步,初始化和设置系统属性、准备环境等设置;第四步,加载并执行rc文件;最后,进入监听循环。
1.2 源码解读
main函数主要流程概述如下:
1 首先它判断第0个参数是否是ueventd、watchdogd,再判断第1个参数是否是subcontext。因为这个后续启动的这三个进程执行的binary和init进程是同一个。若都不是就真正进入我们的init阶段。其代码如下:
545int main(int argc, char** argv) {
546 if (!strcmp(basename(argv[0]), "ueventd")) {
547 return ueventd_main(argc, argv);
548 }
549
550 if (!strcmp(basename(argv[0]), "watchdogd")) {
551 return watchdogd_main(argc, argv);
552 }
553
554 if (argc > 1 && !strcmp(argv[1], "subcontext")) {
555 InitKernelLogging(argv);
556 const BuiltinFunctionMap function_map;
557 return SubcontextMain(argc, argv, &function_map);
558 }
559
560 if (REBOOT_BOOTLOADER_ON_PANIC) {
561 InstallRebootSignalHandlers();
562 }
2 然后,再判断是否是第一次开机启动,若是,就执行第一次开机初始化,创建一些必须的文件、挂载一些目录、初始化selinux等。其代码如下:
564 bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr);
565
566 if (is_first_stage) {
567 boot_clock::time_point start_time = boot_clock::now();
568
569 // Clear the umask.
570 umask(0);
3 初始化加载系统属性、对一些初始属性进行设置、启动selinux、最后启动属性服务等,其核心代码如下。属性服务的代码在/system/core/init/property_service.cpp中。下面的代码中693行调用了sigchld_handler_init函数,该函数在/system/core/init/sigchld_handler.cpp文件中,主要用于监听服务子进程死亡信号,然后重新拉起服务等功能,这也是为什么安卓能保证服务进程非正常死亡能重启的原因。
658 property_init();
659
660 // If arguments are passed both on the command line and in DT,
661 // properties set in DT always have priority over the command-line ones.
662 process_kernel_dt();
663 process_kernel_cmdline();
664
665 // Propagate the kernel variables to internal variables
666 // used by init as well as the current required properties.
667 export_kernel_boot_props();
668
669 // Make the time that init started available for bootstat to log.
670 property_set("ro.boottime.init", getenv("INIT_STARTED_AT"));
671 property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK"));
672
673 // Set libavb version for Framework-only OTA match in Treble build.
674 const char* avb_version = getenv("INIT_AVB_VERSION");
675 if (avb_version) property_set("ro.boot.avb_version", avb_version);
676
677 // Clean up our environment.
678 unsetenv("INIT_SECOND_STAGE");
679 unsetenv("INIT_STARTED_AT");
680 unsetenv("INIT_SELINUX_TOOK");
681 unsetenv("INIT_AVB_VERSION");
682
683 // Now set up SELinux for second stage.
684 SelinuxSetupKernelLogging();
685 SelabelInitialize();
686 SelinuxRestoreContext();
687
688 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
689 if (epoll_fd == -1) {
690 PLOG(FATAL) << "epoll_create1 failed";
691 }
692
693 sigchld_handler_init();
694
695 if (!IsRebootCapable()) {
696 // If init does not have the CAP_SYS_BOOT capability, it is running in a container.
697 // In that case, receiving SIGTERM will cause the system to shut down.
698 InstallSigtermHandler();
699 }
700
701 property_load_boot_defaults();
702 export_oem_lock_status();
703 start_property_service();
704 set_usb_controller();
4 下面的代码是init进程启动服务、挂载文件等启动初始化的核心。首先是通过LoadBootScripts加载rc配置文件,该函数也在/system/core/init/init.cpp中,当ro.boot.init_rc属性没有设置的情况下,会加载/init.rc文件,后依次加载/system/etc/init、/product/etc/init、/odm/etc/init、/vendor/etc/init目录下的rc文件;然后依次通过函数ActionManager::QueueEventTrigger触发early-init、init、charger或late-init,这些系列action又会触发rc文件中的自定义action;然后去启动各种服务。
706 const BuiltinFunctionMap function_map;
707 Action::set_function_map(&function_map);
708
709 subcontexts = InitializeSubcontexts();
710
711 ActionManager& am = ActionManager::GetInstance();
712 ServiceList& sm = ServiceList::GetInstance();
713
714 LoadBootScripts(am, sm);
715
716 // Turning this on and letting the INFO logging be discarded adds 0.2s to
717 // Nexus 9 boot time, so it's disabled by default.
718 if (false) DumpState();
719
720 am.QueueEventTrigger("early-init");
721
722 // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev...
723 am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
724 // ... so that we can start queuing up actions that require stuff from /dev.
725 am.QueueBuiltinAction(MixHwrngIntoLinuxRngAction, "MixHwrngIntoLinuxRng");
726 am.QueueBuiltinAction(SetMmapRndBitsAction, "SetMmapRndBits");
727 am.QueueBuiltinAction(SetKptrRestrictAction, "SetKptrRestrict");
728 am.QueueBuiltinAction(keychord_init_action, "keychord_init");
729 am.QueueBuiltinAction(console_init_action, "console_init");
730
731 // Trigger all the boot actions to get us started.
732 am.QueueEventTrigger("init");
733
734 // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
735 // wasn't ready immediately after wait_for_coldboot_done
736 am.QueueBuiltinAction(MixHwrngIntoLinuxRngAction, "MixHwrngIntoLinuxRng");
737
738 // Don't mount filesystems or start core system services in charger mode.
739 std::string bootmode = GetProperty("ro.bootmode", "");
740 if (bootmode == "charger") {
741 am.QueueEventTrigger("charger");
742 } else {
743 am.QueueEventTrigger("late-init");
744 }
745
746 // Run all property triggers based on current state of the properties.
747 am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
5 最后,进入epoll循环监听事件并处理,例如当子服务进程非正常死亡后,相应的信号函数会往signal_write_fd中写入信息,然后由epoll轮询处理。
749 while (true) {
750 // By default, sleep until something happens.
751 int epoll_timeout_ms = -1;
752
753 if (do_shutdown && !shutting_down) {
754 do_shutdown = false;
755 if (HandlePowerctlMessage(shutdown_command)) {
756 shutting_down = true;
757 }
758 }
759
760 if (!(waiting_for_prop || Service::is_exec_service_running())) {
761 am.ExecuteOneCommand();
762 }
763 if (!(waiting_for_prop || Service::is_exec_service_running())) {
764 if (!shutting_down) {
765 auto next_process_restart_time = RestartProcesses();
766
767 // If there's a process that needs restarting, wake up in time for that.
768 if (next_process_restart_time) {
769 epoll_timeout_ms = std::chrono::ceil<std::chrono::milliseconds>(
770 *next_process_restart_time - boot_clock::now())
771 .count();
772 if (epoll_timeout_ms < 0) epoll_timeout_ms = 0;
773 }
774 }
775
776 // If there's more work to do, wake up again immediately.
777 if (am.HasMoreCommands()) epoll_timeout_ms = 0;
778 }
779
780 epoll_event ev;
781 int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, epoll_timeout_ms));
782 if (nr == -1) {
783 PLOG(ERROR) << "epoll_wait failed";
784 } else if (nr == 1) {
785 ((void (*)()) ev.data.ptr)();
786 }
787 }
2 Zygote启动阶段
zygote的启动过程,后面补充。。。