目錄
第一篇:Android系統(tǒng)啟動之bootloader
第二篇:Android系統(tǒng)啟動之Init流程(上)
第三篇:Android系統(tǒng)啟動之Init流程(下)
第四篇:Android系統(tǒng)啟動之init.rc文件解析過程
第五篇:Android系統(tǒng)啟動之zyogte進(jìn)程
第六篇:Android系統(tǒng)啟動之zyogte進(jìn)程java(上)
第七篇:Android系統(tǒng)啟動之zyogte進(jìn)程java(下)
第八篇:Android系統(tǒng)啟動之SystemServer
本節(jié)主要是對代碼進(jìn)行解釋,十分枯燥.O(∩_∩)O哈哈~
下面開始
啟動代碼(main)
主要分為七部分:
第一部分
判斷啟動部分祥绞,如果是ueventd
,調(diào)用ueventd_main
主函數(shù)赖捌,如果是watchdogd
,調(diào)用watchdogd_main
主函數(shù).
第二部分
add_environment
導(dǎo)入環(huán)境變量评疗,并根據(jù)環(huán)境變量判斷是否是第一次啟動.
第三部分
創(chuàng)建一些基本的目錄,包括/dev佩谷、/porc奥喻、/sysfc等慕嚷。同時把一些文件系統(tǒng)哥牍,如tmpfs、devpt喝检、proc嗅辣、sysfs等mount到項目的目錄。
目錄 | 功能 |
---|---|
tmpfs | 一種基于內(nèi)存的文件系統(tǒng),mount后就可以使用挠说。tmpfs文件系統(tǒng)下的文件都存放在內(nèi)存中澡谭,訪問速度快,但是關(guān)機后所有內(nèi)容偶讀會丟失损俭,因此tmpfs文件系統(tǒng)比較合適存放一些臨時性的文件蛙奖。 |
devpts | 虛擬終端文件系統(tǒng),它通常mount在目錄dev/pts下 |
proc | 一種基于內(nèi)存的虛擬文件系統(tǒng)杆兵,它可以看作是內(nèi)核內(nèi)部數(shù)據(jù)結(jié)構(gòu)的接口雁仲,通過它可以獲得系統(tǒng)的信息,同時能夠在運行時修改特定的內(nèi)核參數(shù) |
sysfs | proc文件系統(tǒng)類似琐脏,它是Linux2.6內(nèi)核引入的攒砖,作用是把系統(tǒng)的設(shè)備和總線按層次組織起來,使得它們可以在用戶空間存取 |
然后使用InitKernelLogging
開啟log,使得init進(jìn)程可以使用kernel的log系統(tǒng)來輸出log.
為什么要使用kernel的log系統(tǒng)?
因為此時Android系統(tǒng)的log還沒有啟動日裙,所以需要使用kernel的log系統(tǒng).
第四部分
SELinex的知識參考android之SELinux小記
主要使用函數(shù)selinux_initialize
啟動SELinux.
另外:
close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
判斷/dev/.booting
文件是否可讀寫和創(chuàng)建.
在/dev目錄下創(chuàng)建一個空文件".booting"表示初始化正在進(jìn)行
is_booting()函數(shù)會依靠空文件".booting"來判斷是否進(jìn)程處于初始化中祭衩,初始化結(jié)束后,這個文件會被刪除
第五部分
初始化系統(tǒng)屬性存儲區(qū)域:
property_init();
property_init
函數(shù)在system/core/init/property_service.cpp
實現(xiàn):
void property_init() {
if (__system_property_area_init()) {
LOG(ERROR) << "Failed to initialize property area";
exit(1);
}
}
然后阅签,設(shè)定內(nèi)核處理命令行.
并設(shè)定相關(guān)系統(tǒng)屬性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].defau lt_value);
}
}
export_kernel_boot_props這個函數(shù),它就是設(shè)置一些屬性蝎抽,設(shè)置ro屬性根據(jù)之前的ro.boot這類的屬性值政钟,如果沒有設(shè)置成unknown,像之前我們有ro.boot.hardware樟结,那我們就可以設(shè)置root.hardware這樣的屬性养交。
第六部分
- 調(diào)用epoll_create1創(chuàng)建epoll句柄,如果創(chuàng)建失敗瓢宦,則退出碎连。
- 調(diào)用signal_handler_init()函數(shù),裝載進(jìn)程信號處理器驮履。
- 調(diào)用property_load_boot_defaults()函數(shù)解析根目錄的default.prop的屬性鱼辙,設(shè)置默認(rèn)屬性配置的相關(guān)工作廉嚼。
- 調(diào)用start_prperty_service()函數(shù),啟動屬性服務(wù)倒戏,并接受屬性的socket的fd加入到epoll中怠噪,定義了處理函數(shù)。
- 解析rc文件(重要).參考:Android系統(tǒng)啟動之init.rc文件解析過程
signal_handler_init
函數(shù)主要是當(dāng)子進(jìn)程被kill之后杜跷,會在父進(jìn)程接受一個信號傍念。
處理這個信號的時候往sockpair一段寫數(shù)據(jù),而另一端的fd是加入epoll中
init是一個守護(hù)進(jìn)程葛闷,為了防止init的子進(jìn)程稱為僵尸進(jìn)程(zombie process)憋槐,需要init在子進(jìn)程結(jié)束時獲取子進(jìn)程的結(jié)束碼,通過結(jié)束碼將程序表中的子進(jìn)程移除淑趾,防止稱為僵尸進(jìn)程的子進(jìn)程占用程序表的空間(程序表的空間達(dá)到上線時阳仔,系統(tǒng)就不能再啟動新的進(jìn)城了,會引起嚴(yán)重的系統(tǒng)問題)治笨。
第七部分
啟動守護(hù)進(jìn)程
源碼如下
int main(int argc, char** argv) {
//---------------------第一部分------------------------------------
// 根據(jù)傳入的參數(shù)驳概,運行不同的主函數(shù)
//----------------------------------------------------------------------
//匹配啟動程序名
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();
}
//---------------------第二部分--------------------------------------
// 設(shè)定環(huán)境變量
//----------------------------------------------------------------------
//設(shè)定環(huán)境變量
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.
// 清楚權(quán)限掩碼
umask(0);
//----------------------第三部分-------------------------------------
// 設(shè)定文件目錄并掛載對應(yīng)的設(shè)備
//----------------------------------------------------------------------
// 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.
// 創(chuàng)建文件系統(tǒng)和對應(yīng)的權(quán)限,并掛載
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旷赖,根據(jù)SELinux的配置重新啟動init
//----------------------------------------------------------------------
// Set up SELinux, loading the SELinux policy.
// 設(shè)置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.
// 根據(jù)SELinux的要求重新設(shè)定init文件屬性
if (restorecon("/init") == -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", StringPrintf("%" PRIu64, start_ms).c_str(), 1);
//設(shè)定參數(shù)
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));
//-----------------------第五部分-------------------------------------
// 運行屬性服務(wù)顺又,根據(jù)屬性值設(shè)定內(nèi)核命令
//----------------------------------------------------------------------
//設(shè)定屬性值
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);
// 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();
//-----------------------第六部分------------------------------------
// 啟動服務(wù),并解析rc文件等孵,根據(jù)rc文件啟動進(jìn)程
//----------------------------------------------------------------------
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);
Parser& parser = Parser::GetInstance();
parser.AddSectionParser("service",std::make_unique<ServiceParser>());
parser.AddSectionParser("on", std::make_unique<ActionParser>());
parser.AddSectionParser("import", std::make_unique<ImportParser>());
std::string bootscript = GetProperty("ro.boot.init_rc", "");
if (bootscript.empty()) {
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) parser.DumpState();
ActionManager& am = ActionManager::GetInstance();
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");
//---------------------第七部分--------------------------------------
// 啟動結(jié)束稚照,開始守護(hù)服務(wù)(守護(hù)進(jìn)程)
//----------------------------------------------------------------------
while (true) {
// By default, sleep until something happens.
int epoll_timeout_ms = -1;
if (!(waiting_for_prop || ServiceManager::GetInstance().IsWaitingForExec())) {
am.ExecuteOneCommand();
}
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;
}
// 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;
}