安卓啟動過程
- 引言
- 1 使用者态init階段
-
- 1.1 流程概述
- 1.2 源碼解讀
- 2 Zygote啟動階段
引言
安卓系統的啟動過程如下:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIwczX0xiRGZkRGZ0Xy9GbvNGL2EzXlpXazxSP9cmT1kkeNpnWywEMW1mY1RzRapnTtxkb5ckYplTeMZTTINGMShUYfRHelRHLwEzX39GZhh2css2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xyayFWbyVGdhd3LcV2Zh1Wa9M3clN2byBXLzN3btg3Pn5GcuQzNzMDNyUTM2ATMwAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
整個流程分為四個階段,即引導階段、核心啟動階段、使用者态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的啟動過程,後面補充。。。