Android init进程
16lz
2021-01-23
android源码学习目录
目录
- android init进程
- init进程--属性服务器
- init进程--init.rc解析与zynote进程启动
介绍
Android init进程是Android系统中用户空间的第一个进程,他有极多工作,例如启动属性服务器和启动Zygote进程,init进程由多个源码组成,位于system/core/init文件夹中。
一:Init进程启动前的准备
Android系统启动过程:介绍了init进程前是linux内核启动,后会寻找init.rc文件进行加载,这时并没有对init.rc进行解析。后启动init进程。
二:Init进程
Iinit进程做了很多工作,主要用来初始化和启动属性服务器,并启动Zygote(孵化器)进程
2.1:init进程的入口函数
/*** Android 8.0 init进程main函数**/int main(int argc, char** argv) { if (!strcmp(basename(argv[0]), "ueventd")) { return ueventd_main(argc, argv); //根据参数启动ueventd,关于硬件设备 } if (!strcmp(basename(argv[0]), "watchdogd")) { return watchdogd_main(argc, argv); //根据参数启动watchdogd,关于程序监控 } if (REBOOT_BOOTLOADER_ON_PANIC) { install_reboot_signal_handlers(); //若是紧急启动则安装对应的消息处理器 } add_environment("PATH", _PATH_DEFPATH); //添加环境变量 bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr);//获取环境变量是否第一次启动 if (is_first_stage) { //第一次开启手机 /*************init的第一个阶段*********/ /* 用户为root用户 * 1>创建文件系统目录并挂载相关文件系统 * 2>重定向输入输出内核log系统 * 3>挂载一些分区设备 * 4>完成SELinux相关工作 * 5>重新启动init进程 */ 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"); //挂载tmpfs文件系统 mkdir("/dev/pts", 0755); mkdir("/dev/socket", 0755); mount("devpts", "/dev/pts", "devpts", 0, NULL); //挂载devpts文件系统 #define MAKE_STR(x) __STRING(x) mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC)); //挂载proc文件系统 // Don't expose the raw commandline to unprivileged processes. chmod("/proc/cmdline", 0440); //改变收紧cmdline目录权限,8.0新增 gid_t groups[] = { AID_READPROC }; setgroups(arraysize(groups), groups); //增加一个用户组,8.0新增 mount("sysfs", "/sys", "sysfs", 0, NULL); //挂载sysfs文件系统 mount("selinuxfs", "/sys/fs/selinux", "selinuxfs", 0, NULL); //挂载selinuxfs,8.0新增 mknod("/dev/kmsg", S_IFCHR | 0600, makedev(1, 11)); //提前创建kmsg设备节点,用于输出log 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... InitKernelLogging(argv); //在android内核中重定向输入输出log系统 LOG(INFO) << "init first stage started!"; if (!DoFirstStageMount()) { //挂载特定的分区设备 LOG(ERROR) << "Failed to mount required partitions early ..."; panic(); //挂载不成功,panic尝试reboot } SetInitAvbVersionInRecovery(); // Set up SELinux, loading the SELinux policy. selinux_initialize(true); //初始化SELinux, // We're in the kernel domain, so re-exec init to transition to the init domain now // that the SELinux policy has been loaded. if (restorecon("/init") == -1) { //按selinux policy要求,重新设置init文件属性 PLOG(ERROR) << "restorecon failed"; security_failure(); //设置失败reboot } 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", StringPrintf("%" PRIu64, start_ms).c_str(), 1); //记录初始化时的时间 char* path = argv[0]; char* args[] = { path, nullptr }; execv(path, args); //再次执行init的main函数,这次init进程为用户状态,不在需要创建各种系统 // 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(); //重新执行init的main函数失败,重启reboot } /***************init第二阶段,重启后用户为user********************/ /* 1>重定向输入输出kernel log系统给 * 2>初始化属性服务器, 重要 * 3>清除用过的环境变量 * 4>完成SELinux相关工作 * 5>创建epoll句柄 * 6>装载子进程信号处理器 * 7>启动属性服务器 * 8>匹配命令和函数之间的对应关系。 */ // At this point we're in the second stage of init. InitKernelLogging(argv); //屏蔽标准的输入输出,并重定向输入输出kernel log系统 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(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(); //1 初始化属性服务器 // 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); // 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(); //再次完成SELinux的相关工作 epoll_fd = epoll_create1(EPOLL_CLOEXEC); //创建epoll句柄 if (epoll_fd == -1) { PLOG(ERROR) << "epoll_create1 failed"; exit(1); } signal_handler_init(); //装在子进程信号处理器 property_load_boot_defaults(); //进行默认的属性配置相关工作 export_oem_lock_status(); //最终决定ro.boot.fllash.locked的值 start_property_service(); //2 启动属性服务器 set_usb_controller(); //匹配命令和函数之间的对应关系 const BuiltinFunctionMap function_map; //system/core/init/builtins.cpp,定义Action中的function_map为BuiltinFuntionMap Action::set_function_map(&function_map); //在Action中保存的function_map队形,记录了命令和函数之间的关系 /****************init第三阶段************************/ /* 1>>构建解析init.rc等文件的解析器对象 * 2>解析init.rc文件 */ Parser& parser = Parser::GetInstance(); //构建解析init.rc等文件的解析器对象 //为解析器增加解析能力,增加一个ServiceParser对应Serrvice,on对应ActionParser,import--importParse parser.AddSectionParser("service",std::make_unique()); parser.AddSectionParser("on", std::make_unique()); parser.AddSectionParser("import", std::make_unique()); std::string bootscript = GetProperty("ro.boot.init_rc", ""); //判断bootScript是否存在 if (bootscript.empty()) { parser.ParseConfig("/init.rc"); //解析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); //如果存在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) parser.DumpState(); /******************init进程第四阶段***********************/ /* 1>通过am对命令执行顺序进行控制 * 2>向am中添加执行action * 3>执行命令 */ ActionManager& am = ActionManager::GetInstance(); am.QueueEventTrigger("early-init"); //添加触发器early-init,执行on 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"); //添加触发器init,执行on 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"); //充电模式下运行 on charger } else { am.QueueEventTrigger("late-init"); //非充电模式下运行 on 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 (!(waiting_for_prop || ServiceManager::GetInstance().IsWaitingForExec())) { am.ExecuteOneCommand(); //依次执行action中的command } if (!(waiting_for_prop || ServiceManager::GetInstance().IsWaitingForExec())) { 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; // 有action待处理,不等待 } // 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) { //有事件到来,执行对应处理函数 //根据上文知道,epoll句柄(即epoll_fd)主要监听子进程结束,及其它进程设置系统属性的请求 ((void (*)()) ev.data.ptr)(); } } return 0;}
init main函数做了很多工作比较复杂,在开始时进行了文件系统的创建和挂载,对于一个系统我们不需要了解那么详细,我们只需要关注几点就可以了。
- init进程--属性服务器
- init进程--init.rc解析与zynote进程启动
- signal_handler_init()函数用于设置子进程,定义在system/core/init/signale_handler.cpp中,主要用于防止init进程的子进程成为僵尸进程, 当子进程暂停或者终止会发出SIGCHLD信号,signal_handler_init函数会接受这个信号.
eg:如果init进程的子进程zynote进程终止了,signal_handler_init函数会收到终止信号,并找到zynote进程,移除所有zynote进程的所有消息,在根据配置(是否需要重启)重启zynote进程。
更多相关文章
- Android Service进程间双向通信之Messenger(系列4)
- Android5.0开关机模块——zygote进程
- Android-Layout:RelativeLayout常用XML属性
- Android 属性动画(Property Animation) 完全解析【附源码】
- ListView的分割线属性操作