編輯:Android 開發教學
研究 Android 源碼,第一步繞不開 init。它是「天字第一號」進程,程式碼晦澀但地位關鍵;搞懂它,後續 Zygote、SystemServer 乃至各核心服務的源碼閱讀都會順暢許多。所以既然要讀源碼,就拿 init 來「庖丁解牛」。
相關資源:
原始碼下載:https://mirrors.tuna.tsinghua.edu.cn/help/AOSP/
編譯教學:https://blog.csdn.net/cjpx00008/article/details/60474883
init 是由核心啟動的使用者層級進程。Linux 核心啟動後運行的第一個進程就是它,由於它是使用者空間的第一個進程,PID 固定為 1。它的生命週期貫穿整個系統運行始終,所有其他進程的共同祖先都是它。可以用 adb shell ps | grep init 確認。
Android init 的入口在 system/core/init/init.cpp。由於它是命令列程式,分析就從 main 函式開始。
把 init.cpp 的 main 拆開來看,大致可以整理成以下步驟:
程式一開頭先判斷自己是否被以 ueventd 或 watchdogd 的身分呼叫,若是則直接轉入對應流程;接著呼叫 umask(0) 清掉檔案建立遮罩,確保之後新建的目錄權限不受影響。然後判斷目前是第一階段還是第二階段——只有啟動參數帶 --second-stage 才算第二階段。
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);
}
umask(0); // 清除 file mode creation mask
add_environment("PATH", _PATH_DEFPATH);
bool is_first_stage = (argc == 1) || (strcmp(argv[1], "--second-stage") != 0);
// 第一階段先把 initramdisk 中最基本的檔案系統準備好
if (is_first_stage) {
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));
mount("sysfs", "/sys", "sysfs", 0, NULL);
}
必須先有 /dev 這個可寫的掛載點,才能建立 kmsg 與 null 裝置節點,否則之後想把 / 重新掛成唯讀就會失敗。tmpfs 掛好之後,init 才真正能與外界溝通。
// 屏蔽標準輸入輸出 → 定義於 system/core/init/Util.cpp
open_devnull_stdio();
// 初始化核心 log 輸出設備 → 定義於 system/core/libcutils/klog.c
klog_init();
klog_set_level(KLOG_NOTICE_LEVEL); // NOTICE level
NOTICE("init %s started!\n", is_first_stage ? "first stage" : "second stage");
if (!is_first_stage) {
// 引入 SELinux 後,以 is_first_stage 區分 init 的運行階段
// 標記開機進行中,供背景 fw loader 等使用
close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
property_init(); // → system/core/init/property_service.cpp
process_kernel_dt(); // 若命令行與 DT 都有設定,DT 優先
process_kernel_cmdline();
// 把核心變數傳遞給 init 內部變數,並設為當前必要的屬性
export_kernel_boot_props();
}
其中 property_init 的實作很薄,只是把初始化工作交給 __system_property_area_init():
void property_init() {
if (__system_property_area_init()) {
ERROR("Failed to initialize property area\n");
exit(1);
}
}
// 設定 SELinux,包括在核心域中載入安全政策
selinux_initialize(is_first_stage);
這個函式做了幾件事:註冊 log 與 audit 兩種回呼函式;在第一階段載入 sepolicy 檔案並把它傳給核心,讓核心取得安全政策設定;比對核心中的 enforcing 狀態與命令行列入的設定,若不一致就以 security_setenforce() 對齊,失敗則進入 security_failure 走 recovery;最後把 /sys/fs/selinux/checkreqprot 寫為 0。
static void selinux_initialize(bool in_kernel_domain) {
Timer t; // 用來計算 SELinux 初始化的耗時
selinux_callback cb;
cb.func_log = selinux_klog_callback; // 列印 Log 的回呼
selinux_set_callback(SELINUX_CB_LOG, cb);
cb.func_audit = audit_callback; // 檢查權限的回呼
selinux_set_callback(SELINUX_CB_AUDIT, cb);
if (in_kernel_domain) {
INFO("Loading SELinux policy...\n");
if (selinux_android_load_policy() < 0) {
ERROR("failed to load policy: %s\n", strerror(errno));
security_failure();
}
bool kernel_enforcing = (security_getenforce() == 1); // 核心中讀到的值
bool is_enforcing = selinux_is_enforcing(); // 命令行得到的值
if (kernel_enforcing != is_enforcing) {
// permissive:所有操作都允許,違反權限時僅記錄日誌
// enforcing:所有操作都進行權限檢查
if (security_setenforce(is_enforcing)) {
ERROR("security_setenforce(%s) failed: %s\n",
is_enforcing ? "true" : "false", strerror(errno));
security_failure(); // 重啟進入 recovery
}
}
if (write_file("/sys/fs/selinux/checkreqprot", "0") == -1) {
security_failure();
}
NOTICE("(Initializing SELinux %s took %.2fs.)\n",
is_enforcing ? "enforcing" : "non-enforcing", t.duration());
} else {
selinux_init_all_handles(); // 第二階段改呼叫這個
}
}
SELinux 政策載入完成後,init 已經可以從核心域轉移到 init 域,做法是重新執行自己一次,並帶上 --second-stage 參數。
if (is_first_stage) {
if (restorecon("/init") == -1) { // 依政策要求重設 init 檔案的 SELinux 標籤
ERROR("restorecon failed: %s\n", strerror(errno));
security_failure();
}
char* path = argv[0];
char* args[] = { path, const_cast<char*>("--second-stage"), nullptr };
if (execv(path, args) == -1) { // 重新進入 main,此回已是第二階段
ERROR("execv(\"%s\") failed: %s\n", path, strerror(errno));
security_failure();
}
}
// 這些目錄在政策載入前就被建立,因此必須在 ueventd 填入 /dev 之前
// 把安全性內容還原成正確的值
NOTICE("Running restorecon...\n");
restorecon("/dev");
restorecon("/dev/socket");
restorecon("/dev/__properties__");
restorecon("/property_contexts");
restorecon_recursive("/sys");
epoll_fd = epoll_create1(EPOLL_CLOEXEC);
if (epoll_fd == -1) {
ERROR("epoll_create1 failed: %s\n", strerror(errno));
exit(1);
}
signal_handler_init(); // 裝載子進程訊號處理器
init 是守護進程,必須在子進程結束時取得結束碼,把對應項目從行程表移除,否則殭屍進程會佔滿行程表空間,最終導致系統無法再啟動新進程。這件事就靠 SIGCHLD 訊號來驅動。
void signal_handler_init() {
// → system/core/init/signal_handler.cpp
// Linux 中父進程靠捕捉 SIGCHLD 得知子進程結束
// 用 socketpair 建立一對已連接的 socket,作為訊號的讀寫端
int s[2];
if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, s) == -1) {
ERROR("socketpair failed: %s\n", strerror(errno));
exit(1);
}
signal_write_fd = s[0];
signal_read_fd = s[1];
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_handler = SIGCHLD_handler; // 訊號處理器
act.sa_flags = SA_NOCLDSTOP; // 僅在子進程終止時才接受 SIGCHLD
sigaction(SIGCHLD, &act, 0); // 向核心註冊
ServiceManager::GetInstance().ReapAnyOutstandingChildren();
register_epoll_handler(signal_read_fd, handle_signal);
}
為什麼要設 SA_NOCLDSTOP?因為系統預設在子進程「暫停」時也會送 SIGCHLD,而 init 只關心子進程真正終止,所以必須把這個標誌位設起來加以過濾。
static void SIGCHLD_handler(int) {
// 收到 SIGCHLD 時向 signal_write_fd 寫入,
// 由於 socketpair 的綁定關係,signal_read_fd 隨即有資料可讀
if (TEMP_FAILURE_RETRY(write(signal_write_fd, "1", 1)) == -1) {
ERROR("write(signal_write_fd) failed: %s\n", strerror(errno));
}
}
void register_epoll_handler(int fd, void (*fn)()) {
// 回到 init.cpp
epoll_event ev;
ev.events = EPOLLIN;
ev.data.ptr = reinterpret_cast<void*>(fn);
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
ERROR("epoll_ctl failed: %s\n", strerror(errno));
}
}
把這幾段串起來看,機制就清楚了:收到子進程終止的 SIGCHLD 後,SIGCHLD_handler 向 signal_write_fd 寫一個位元組;epoll 監聽到 signal_read_fd 可讀,回呼 handle_signal;handle_signal 清空 socket 中的資料,再呼叫 ServiceManager::GetInstance().ReapAnyOutstandingChildren() 收尾。

static void handle_signal() {
// → system/core/init/signal_handler.cpp
char buf[32];
read(signal_read_fd, buf, sizeof(buf)); // 清空待處理請求
ServiceManager::GetInstance().ReapAnyOutstandingChildren();
}
// → system/core/init/service.cpp,ServiceManager 是單例
ServiceManager& ServiceManager::GetInstance() {
static ServiceManager instance;
return instance;
}
void ServiceManager::ReapAnyOutstandingChildren() {
while (ReapOneProcess()) { } // 逐一回收
}
ReapOneProcess 則負責實際善後:
bool ServiceManager::ReapOneProcess() {
int status;
// waitpid 的 WNOHANG 表示非阻塞;回傳正值代表有進程結束了
pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
if (pid == 0) {
return false;
} else if (pid == -1) {
ERROR("waitpid failed: %s\n", strerror(errno));
return false;
}
// FindServiceByPid 會輪詢解析 init.rc 生成的 service_list,找出 pid 相符的 svc
Service* svc = FindServiceByPid(pid);
std::string name;
if (svc) {
name = android::base::StringPrintf("Service '%s' (pid %d)", svc->name().c_str(), pid);
} else {
name = android::base::StringPrintf("Untracked pid %d", pid);
}
if (WIFEXITED(status)) {
NOTICE("%s exited with status %d\n", name.c_str(), WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
NOTICE("%s killed by signal %d\n", name.c_str(), WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
NOTICE("%s stopped by signal %d\n", name.c_str(), WSTOPSIG(status));
} else {
NOTICE("%s state changed", name.c_str());
}
if (!svc) {
return true;
}
if (svc->Reap()) {
// 結束服務;此處已進一步封裝,包含重啟子進程的邏輯,暫不展開
waiting_for_exec = false;
RemoveService(*svc); // 移除服務對應的資訊
}
return true;
}
property_load_boot_defaults();
export_oem_lock_status();
std::string bootmode = property_get("ro.bootmode");
if (strncmp(bootmode.c_str(), "ffbm", 4) == 0) {
property_set("ro.logdumpd", "0");
} else {
property_set("ro.logdumpd", "1");
}
start_property_service();
// → system/core/init/property_service.cpp
// property_load_boot_defaults 實際上就是呼叫 load_properties_from_file 解析設定檔
void property_load_boot_defaults() {
load_properties_from_file(PROP_PATH_RAMDISK_DEFAULT, NULL);
}
// → system/core/init/builtins.cpp
// Action 中保存 function_map,記錄命令與函式之間的對應關係
const BuiltinFunctionMap function_map;
Action::set_function_map(&function_map);
這個 map 就是 init.rc 中所有指令(mount、mkdir、exec_start、setprop 等)能被解析執行的依據。
init 涉及的知識點相當龐雜,程式碼之間的邏輯交錯。因此我選擇分章節來寫,盡量少貼源碼、多講脈絡——一次讀一大篇反而容易半途放棄。
下一篇「Android 啟動篇 — init 原理(二)」,將接著分析 init.rc 的解析過程。
ApiDemos 解析(3):Activity 切換的補間動畫
App->Activity->Animation 示例示範如何為 Activity 之間的切換加上動態效果。示例中定義了兩種動畫:Fade In 讓新出現的
Android 簡明開發教程四:Android 應用的基本概念
Android 平台最顯著的特點之一是「低耦合」。Activity 是 Android 應用最基本的 UI 模組,若拿 Windows Form 應用來類比,它相當於 W
Android 平台調用 Web Service 實作指南
在 Android 平台呼叫 Web Service,常使用輕量級的 ksoap2-android 套件。它能封裝 SOAP 請求,讓開發者更容易與遠端服務溝通。準備工作
Android 使用 HTML Parser 解析網頁內容
行動應用常需要呈現來自傳統網路的內容。原生應用可下載網頁後解析 HTML,再重新排版顯示,以获得更好的效能與使用者體驗。HTML Parser 的整合方式HTML Par