Android系統啟動之Init流程(下)

image.png
目錄
第一篇: Android系統啟動之bootloader
第四篇:
Android系統啟動之init.rc檔案解析過程
本節主要是對程式碼進行解釋,十分枯燥.O(∩_∩)O哈哈~
下面開始
啟動程式碼(main)
主要分為七部分:
第一部分
判斷啟動部分,如果是 ueventd
,呼叫 ueventd_main
主函式,如果是 watchdogd
,呼叫 watchdogd_main
主函式.
第二部分
add_environment
匯入環境變數,並根據環境變數判斷是否是第一次啟動.
第三部分
建立一些基本的目錄,包括/dev、/porc、/sysfc等。同時把一些檔案系統,如tmpfs、devpt、proc、sysfs等mount到專案的目錄。
目錄 | 功能 |
---|---|
tmpfs | 一種基於記憶體的檔案系統,mount後就可以使用。tmpfs檔案系統下的檔案都存放在記憶體中,訪問速度快,但是關機後所有內容偶讀會丟失,因此tmpfs檔案系統比較合適存放一些臨時性的檔案。 |
devpts | 虛擬終端檔案系統,它通常mount在目錄dev/pts下 |
proc | 一種基於記憶體的虛擬檔案系統,它可以看作是核心內部資料結構的介面,通過它可以獲得系統的資訊,同時能夠在執行時修改特定的核心引數 |
sysfs | proc檔案系統類似,它是Linux2.6核心引入的,作用是把系統的裝置和匯流排按層次組織起來,使得它們可以在使用者空間存取 |
然後使用 InitKernelLogging
開啟log,使得init程序可以使用kernel的log系統來輸出log.
為什麼要使用kernel的log系統?
因為此時Android系統的log還沒有啟動,所以需要使用kernel的log系統.
第四部分
SELinex的知識參考android之SELinux小記
主要使用函式 selinux_initialize
啟動SELinux.
另外:
close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
判斷 /dev/.booting
檔案是否可讀寫和建立.
在/dev目錄下建立一個空檔案".booting"表示初始化正在進行
is_booting()函式會依靠空檔案".booting"來判斷是否程序處於初始化中,初始化結束後,這個檔案會被刪除
第五部分
初始化系統屬性儲存區域:
property_init();
property_init
函式在 system/core/init/property_service.cpp
實現:
void property_init() { if (__system_property_area_init()) { LOG(ERROR) << "Failed to initialize property area"; exit(1); } }
然後,設定核心處理命令列.
並設定相關係統屬性 export_kernel_boot_props
:
static void export_kernel_boot_props() { struct { const char *src_prop; const char *dst_prop; const char *default_value; } prop_map[] = { { "ro.boot.serialno","ro.serialno","", }, { "ro.boot.mode","ro.bootmode","unknown", }, { "ro.boot.baseband","ro.baseband","unknown", }, { "ro.boot.bootloader", "ro.bootloader", "unknown", }, { "ro.boot.hardware","ro.hardware","unknown", }, { "ro.boot.revision","ro.revision","0", }, }; for (size_t i = 0; i < arraysize(prop_map); i++) { std::string value = GetProperty(prop_map[i].src_prop, ""); property_set(prop_map[i].dst_prop, (!value.empty()) ? value : prop_map[i].default_value); } }
export_kernel_boot_props這個函式,它就是設定一些屬性,設定ro屬性根據之前的ro.boot這類的屬性值,如果沒有設定成unknown,像之前我們有ro.boot.hardware,那我們就可以設定root.hardware這樣的屬性。
第六部分
- 呼叫epoll_create1建立epoll控制代碼,如果建立失敗,則退出。
- 呼叫signal_handler_init()函式,裝載程序訊號處理器。
- 呼叫property_load_boot_defaults()函式解析根目錄的default.prop的屬性,設定預設屬性配置的相關工作。
- 呼叫start_prperty_service()函式,啟動屬性服務,並接受屬性的socket的fd加入到epoll中,定義了處理函式。
- 解析rc檔案 (重要) .參考: Android系統啟動之init.rc檔案解析過程
signal_handler_init
函式主要是當子程序被kill之後,會在父程序接受一個訊號。
處理這個訊號的時候往sockpair一段寫資料,而另一端的fd是加入epoll中
init是一個守護程序,為了防止init的子程序稱為殭屍程序(zombie process),需要init在子程序結束時獲取子程序的結束碼,通過結束碼將程式表中的子程序移除,防止稱為殭屍程序的子程序佔用程式表的空間(程式表的空間達到上線時,系統就不能再啟動新的進城了,會引起嚴重的系統問題)。
第七部分
啟動守護程序
原始碼如下
int main(int argc, char** argv) { //---------------------第一部分------------------------------------ // 根據傳入的引數,執行不同的主函式 //---------------------------------------------------------------------- //匹配啟動程式名 if (!strcmp(basename(argv[0]), "ueventd")) { return ueventd_main(argc, argv); } if (!strcmp(basename(argv[0]), "watchdogd")) { return watchdogd_main(argc, argv); } if (REBOOT_BOOTLOADER_ON_PANIC) { InstallRebootSignalHandlers(); } //---------------------第二部分-------------------------------------- // 設定環境變數 //---------------------------------------------------------------------- //設定環境變數 add_environment("PATH", _PATH_DEFPATH); bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr); //判斷是否是第一次 if (is_first_stage) { boot_clock::time_point start_time = boot_clock::now(); // Clear the umask. // 清楚許可權掩碼 umask(0); //----------------------第三部分------------------------------------- // 設定檔案目錄並掛載對應的裝置 //---------------------------------------------------------------------- // Get the basic filesystem setup we need put together in the initramdisk // on / and then we'll let the rc file figure out the rest. // 建立檔案系統和對應的許可權,並掛載 mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755"); mkdir("/dev/pts", 0755); mkdir("/dev/socket", 0755); mount("devpts", "/dev/pts", "devpts", 0, NULL); #define MAKE_STR(x) __STRING(x) mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC)); // Don't expose the raw commandline to unprivileged processes. chmod("/proc/cmdline", 0440); gid_t groups[] = { AID_READPROC }; setgroups(arraysize(groups), groups); mount("sysfs", "/sys", "sysfs", 0, NULL); mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL); mknod("/dev/kmsg", S_IFCHR | 0600, makedev(1, 11)); mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8)); mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9)); // Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually // talk to the outside world... //初始化log InitKernelLogging(argv); LOG(INFO) << "init first stage started!"; if (!DoFirstStageMount()) { LOG(ERROR) << "Failed to mount required partitions early ..."; panic(); } SetInitAvbVersionInRecovery(); //-----------------------第四部分------------------------------------- // 啟動SELinux,根據SELinux的配置重新啟動init //---------------------------------------------------------------------- // Set up SELinux, loading the SELinux policy. // 設定SELinux,載入SEPolicy selinux_initialize(true); // We're in the kernel domain, so re-exec init to transition to the init domain now // that the SELinux policy has been loaded. // 根據SELinux的要求重新設定init檔案屬性 if (selinux_android_restorecon("/init", 0) == -1) { PLOG(ERROR) << "restorecon failed"; security_failure(); } setenv("INIT_SECOND_STAGE", "true", 1); static constexpr uint32_t kNanosecondsPerMillisecond = 1e6; uint64_t start_ms = start_time.time_since_epoch().count() / kNanosecondsPerMillisecond; setenv("INIT_STARTED_AT", std::to_string(start_ms).c_str(), 1); //設定引數 char* path = argv[0]; char* args[] = { path, nullptr }; execv(path, args); // execv() only returns if an error happened, in which case we // panic and never fall through this conditional. PLOG(ERROR) << "execv(\"" << path << "\") failed"; security_failure(); } // At this point we're in the second stage of init. InitKernelLogging(argv); LOG(INFO) << "init second stage started!"; // Set up a session keyring that all processes will have access to. It // will hold things like FBE encryption keys. No process should override // its session keyring. keyctl_get_keyring_ID(KEY_SPEC_SESSION_KEYRING, 1); // Indicate that booting is in progress to background fw loaders, etc. close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000)); //-----------------------第五部分------------------------------------- // 執行屬性服務,根據屬性值設定核心命令 //---------------------------------------------------------------------- //設定屬性值 property_init(); // If arguments are passed both on the command line and in DT, // properties set in DT always have priority over the command-line ones. process_kernel_dt(); process_kernel_cmdline(); // Propagate the kernel variables to internal variables // used by init as well as the current required properties. export_kernel_boot_props(); // Make the time that init started available for bootstat to log. property_set("ro.boottime.init", getenv("INIT_STARTED_AT")); property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK")); // Set libavb version for Framework-only OTA match in Treble build. const char* avb_version = getenv("INIT_AVB_VERSION"); if (avb_version) property_set("ro.boot.avb_version", avb_version); // Set memcg property based on kernel cmdline argument bool memcg_enabled = android::base::GetBoolProperty("ro.boot.memcg",false); if (memcg_enabled) { // root memory control cgroup mkdir("/dev/memcg", 0700); chown("/dev/memcg",AID_ROOT,AID_SYSTEM); mount("none", "/dev/memcg", "cgroup", 0, "memory"); // app mem cgroups, used by activity manager, lmkd and zygote mkdir("/dev/memcg/apps/",0755); chown("/dev/memcg/apps/",AID_SYSTEM,AID_SYSTEM); mkdir("/dev/memcg/system",0550); chown("/dev/memcg/system",AID_SYSTEM,AID_SYSTEM); } // Clean up our environment. unsetenv("INIT_SECOND_STAGE"); unsetenv("INIT_STARTED_AT"); unsetenv("INIT_SELINUX_TOOK"); unsetenv("INIT_AVB_VERSION"); // Now set up SELinux for second stage. selinux_initialize(false); selinux_restore_context(); //-----------------------第六部分------------------------------------ // 啟動服務,並解析rc檔案,根據rc檔案啟動程序 //---------------------------------------------------------------------- epoll_fd = epoll_create1(EPOLL_CLOEXEC); if (epoll_fd == -1) { PLOG(ERROR) << "epoll_create1 failed"; exit(1); } signal_handler_init(); property_load_boot_defaults(); export_oem_lock_status(); start_property_service(); set_usb_controller(); const BuiltinFunctionMap function_map; Action::set_function_map(&function_map); ActionManager& am = ActionManager::GetInstance(); ServiceManager& sm = ServiceManager::GetInstance(); Parser& parser = Parser::GetInstance(); parser.AddSectionParser("service", std::make_unique<ServiceParser>(&sm)); parser.AddSectionParser("on", std::make_unique<ActionParser>(&am)); parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser)); std::string bootscript = GetProperty("ro.boot.init_rc", ""); if (bootscript.empty()) { //載入根據rc檔案配置服務 parser.ParseConfig("/init.rc"); parser.set_is_system_etc_init_loaded( parser.ParseConfig("/system/etc/init")); parser.set_is_vendor_etc_init_loaded( parser.ParseConfig("/vendor/etc/init")); parser.set_is_odm_etc_init_loaded(parser.ParseConfig("/odm/etc/init")); } else { parser.ParseConfig(bootscript); parser.set_is_system_etc_init_loaded(true); parser.set_is_vendor_etc_init_loaded(true); parser.set_is_odm_etc_init_loaded(true); } // Turning this on and letting the INFO logging be discarded adds 0.2s to // Nexus 9 boot time, so it's disabled by default. if (false) DumpState(); am.QueueEventTrigger("early-init"); // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev... am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done"); // ... so that we can start queuing up actions that require stuff from /dev. am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng"); am.QueueBuiltinAction(set_mmap_rnd_bits_action, "set_mmap_rnd_bits"); am.QueueBuiltinAction(set_kptr_restrict_action, "set_kptr_restrict"); am.QueueBuiltinAction(keychord_init_action, "keychord_init"); am.QueueBuiltinAction(console_init_action, "console_init"); // Trigger all the boot actions to get us started. am.QueueEventTrigger("init"); // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random // wasn't ready immediately after wait_for_coldboot_done am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng"); // Don't mount filesystems or start core system services in charger mode. std::string bootmode = GetProperty("ro.bootmode", ""); if (bootmode == "charger") { am.QueueEventTrigger("charger"); } else { am.QueueEventTrigger("late-init"); } // Run all property triggers based on current state of the properties. am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers"); //---------------------第七部分-------------------------------------- // 啟動結束,開始守護服務(守護程序) //---------------------------------------------------------------------- while (true) { // By default, sleep until something happens. int epoll_timeout_ms = -1; if (do_shutdown && !shutting_down) { do_shutdown = false; if (HandlePowerctlMessage(shutdown_command)) { shutting_down = true; } } if (!(waiting_for_prop || sm.IsWaitingForExec())) { am.ExecuteOneCommand(); } if (!(waiting_for_prop || sm.IsWaitingForExec())) { if (!shutting_down) restart_processes(); // If there's a process that needs restarting, wake up in time for that. if (process_needs_restart_at != 0) { epoll_timeout_ms = (process_needs_restart_at - time(nullptr)) * 1000; if (epoll_timeout_ms < 0) epoll_timeout_ms = 0; } // If there's more work to do, wake up again immediately. if (am.HasMoreCommands()) epoll_timeout_ms = 0; } epoll_event ev; int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, epoll_timeout_ms)); if (nr == -1) { PLOG(ERROR) << "epoll_wait failed"; } else if (nr == 1) { ((void (*)()) ev.data.ptr)(); } } return 0; }