Android 開機啟動鏈拆解:從 init、Zygote 到 SystemServer 的行程孵化與服務註冊時序 / Android Boot Chain Deconstructed: Process Forking, Preloading, and Service Startup from init and Zygote to SystemServer
daily-tech:2026-12-04
現象:上一篇我們拆解了系統跑起來之後,如何用 ftrace 與 perf 揪出核心延遲尖峰與鎖競爭熱點;今天我們把時間軸往回拉,對準按下電源鍵到桌面出現的那幾十秒。你可能遇過這樣的畫面:Android 手機做完系統更新重新開機,或是開發板剛燒錄好新映像檔,螢幕一直停在開機動畫打轉,既沒有直接當機重啟,也看不到哪個環節卡住了。究竟是 Linux 核心還沒交棒、磁碟分區掛載慢了、Zygote 預載類別太重,還是 SystemServer 裡某個系統服務在主執行緒卡死?
Symptom: In our previous post, we used ftrace and perf to hunt down kernel latency spikes and lock contention on a running system. Today we rewind the clock to the tens of seconds between pressing the power button and seeing the home screen. You have likely seen an Android phone after an OS update—or a freshly flashed dev board—spin endlessly on the boot animation without crashing or revealing where time is going. Is the Linux kernel still handing off control, is partition mounting stalled, is Zygote preloading too much, or is a service inside SystemServer blocking the main thread?
想看懂開機時間花去哪裡,不能只把開機動畫當成一個黑盒子。整個 Android 使用者空間(Userspace)的誕生其實是一條高度有序的接力鏈:從 Linux 核心交出第一個使用者行程 init(PID 1),再由 init 喚起行程母體 Zygote 預先暖機 ART(Android Runtime,應用程式執行環境),最後孵化出掌管所有系統服務的 SystemServer 並把畫面交給主畫面 Launcher。把這四棒的銜接與底層記憶體機制看清楚,開機慢、卡 Logo 或首次點開 App 延遲高的原因就能一次對上號。
Understanding where boot time goes requires opening the black box behind the boot animation. Android's userspace comes alive as a tightly ordered relay: the Linux kernel hands off to the first userspace process, init (PID 1); init launches the process incubator Zygote to warm up ART (Android Runtime); and Zygote forks SystemServer to bring up framework services and hand control to the Home Launcher. Once these handoffs and their underlying memory mechanics are clear, boot stalls and slow cold starts become straightforward to diagnose.
init 雙階段掛載與 .rc 觸發、Zygote 預載框架到 SystemServer 三階段服務註冊的完整開機鏈,以及底部原生守護行程與 App 冷啟動孵化路徑。 / Figure 1 | Original architecture diagram (not a product screenshot, derived from local Linux 6.18.55/linux-next 7.3.0-rc6 and AOSP sources): traces the full handoff from Linux PID 1 launch through two-stage Android init, Zygote preloading, and SystemServer's three-phase service startup alongside native daemons and cold app launches.機制一:Linux kernel_init 交棒與 Android 雙階段 init / Mechanism 1: Kernel Handoff to Two-Stage Android init
開機鏈的第一棒從核心內部跨出。直接查核本機 Linux 6.18.55 的 init/main.c(第 165 行與第 1434–1474 行;對照 linux-next 7.3.0-rc6 為第 169 行與第 1552–1594 行),當核心完成記憶體子系統、驅動初始化與 rcu_end_inkernel_boot() 後,核心執行緒 kernel_init() 會優先檢查 ramdisk_execute_command(預設值正是 "/init")並呼叫 run_init_process() 執行 ramdisk(記憶體根檔案系統)裡的 /init;唯有這個路徑失敗,核心才會往後退回 execute_command 或傳統的 /sbin/init,若全數落空才觸發著名的 No working init found. 核心恐慌(panic):
The first baton pass crosses the kernel-to-userspace boundary. Inspecting our local Linux 6.18.55 tree in init/main.c (line 165 and lines 1434–1474; linux-next 7.3.0-rc6 line 169 and lines 1552–1594), once memory setup, driver probing, and rcu_end_inkernel_boot() finish, the kernel_init() thread prioritizes ramdisk_execute_command (defaulting to "/init") and calls run_init_process() to execute /init from ramdisk. Only if that fails does the kernel fall back to execute_command or legacy paths like /sbin/init before panicking with No working init found.:
/* 來源查核:Linux 6.18.55 (init/main.c: L165, L1468-1474) */
static char *ramdisk_execute_command = "/init";
if (ramdisk_execute_command) {
ret = run_init_process(ramdisk_execute_command);
if (!ret)
return 0;
pr_err("Failed to execute %s (error %d)
",
ramdisk_execute_command, ret);
}
拿到控制權的 Android init(PID 1)並非一口氣把所有腳本全跑完,而是依 AOSP system/core/init 設計拆成清晰的雙階段。第一階段(First Stage Init)在剛離開核心的極簡環境中,先掛載 /dev、/proc、/sys 等基本虛擬檔案系統與邏輯分區(如 /system、/vendor),並載入 SELinux(強制存取控制安全策略);準備妥當後,它會帶著 --second-stage 參數重新執行(execv)自己,正式切換進受 SELinux 規則保護的安全網域。接著第二階段(Second Stage Init)初始化系統屬性服務(Property Service),讀取 /system/etc/init/hw/init.rc 以及各分區 etc/init/ 目錄下的模組化 .rc 檔,依序觸發 early-init、init、late-init 與 zygote-start 等動作區塊,拉起 servicemanager、surfaceflinger、lmkd 等原生守護行程,並啟動下一棒的 zygote 服務。
Android's init (PID 1) does not parse every script in one monolithic pass; per AOSP's system/core/init design, it splits into two stages. First Stage Init mounts minimal pseudo-filesystems (/dev, /proc, /sys) and logical partitions (such as /system and /vendor), loads SELinux policy (Mandatory Access Control), and then re-executes itself via execv with --second-stage so PID 1 transitions into its enforced SELinux domain. Second Stage Init initializes the Android Property Service, parses /system/etc/init/hw/init.rc along with modular drop-in .rc files across partitions, and fires ordered triggers (early-init, init, late-init, and zygote-start) to spawn native daemons like servicemanager, surfaceflinger, and lmkd before bringing up zygote.
機制二:Zygote 預載策略與背後的 Linux COW 寫時複製 / Mechanism 2: Zygote Preloading and Linux Copy-on-Write Internals
為什麼 Android 不讓每個 App 都各自從頭啟動一套 ART 虛擬機與框架類別?答案藏在 Zygote(由 init 透過 app_process 啟動)。查核 AOSP 官方 ZygoteInit.java(refs/heads/main),進入點 main()(第 817 行)啟動後會立刻呼叫 preload()(第 128 行),把系統幾乎所有 App 都會用到的數千個核心 Java 類別(定義於 preloaded-classes 清單)、共用繪圖資源與原生函式庫一次載入記憶體;緊接著透過 forkSystemServer()(第 693 與 905 行)孵化出 system_server,再進入 zygoteServer.runSelectLoop()(第 919 行)在 UNIX Domain Socket(本機行程間通訊通道)上靜候 ActivityManagerService 的孵化指令。為了進一步縮短冷啟動延遲,現代 Android 還允許 Zygote 預先孵化一小批尚未特化的空殼行程——USAP(Unspecialized App Process,未特化應用行程池),等使用者點下圖示時直接認領特化。
Why doesn't Android boot a fresh ART runtime and reload framework classes from scratch for every app? The answer is Zygote (launched by init via app_process). Checking AOSP's ZygoteInit.java (refs/heads/main), main() (line 817) immediately invokes preload() (line 128) to load thousands of widely shared Java classes (from preloaded-classes), common resources, and shared libraries once into memory. It then spawns system_server via forkSystemServer() (lines 693 and 905) and enters zygoteServer.runSelectLoop() (line 919) to listen on a UNIX domain socket for spawn requests from ActivityManagerService. To shave off additional cold-start latency, modern Android can also pre-fork a small pool of USAPs (Unspecialized App Processes) ready to be specialized the instant a user taps an app icon.
SystemServer.java 整理):上軌拆解 Zygote 呼叫 fork() 時 Linux 核心如何將頁表設為雙向寫保護以零拷貝共享預載頁,直到首次寫入才進入 do_wp_page();下軌對照 SystemServer 三階段服務啟動與 boot_progress_* 事件時間軸。 / Figure 2 | Original timeline and kernel mechanics diagram (not a product screenshot, derived from local Linux 6.18.55/linux-next 7.3.0-rc6 and AOSP SystemServer.java): top details how Linux write-protects PTEs during fork() for zero-copy sharing until do_wp_page() fires on first write; bottom maps SystemServer's three boot phases onto observable boot_progress_* events.而 Zygote 之所以能「一份預載、百個 App 共享」,全靠底層 Linux 核心的 COW(Copy-on-Write,寫時複製)。打開本機 Linux 6.18.55 原始碼追蹤 fork() 路徑:kernel_clone()(kernel/fork.c 第 2570 行;linux-next 第 2720 行)進入 copy_mm()(6.18.55 第 1520 行;linux-next 第 1567 行)後,因為新行程需要獨立位址空間(未帶 CLONE_VM),核心呼叫 dup_mm() 與 dup_mmap() 複製虛擬記憶體區段(VMA)與頁表,最終在 mm/memory.c 的 copy_page_range()(6.18.55 第 1505 行;linux-next 第 1552 行)裡進入 __copy_present_ptes():
Zygote's ability to preload once and share across dozens of apps rests entirely on Linux COW (Copy-on-Write). Tracing fork() in our local Linux 6.18.55 source: kernel_clone() (kernel/fork.c line 2570; linux-next line 2720) enters copy_mm() (6.18.55 line 1520; linux-next line 1567). Because a forked process needs its own address space (no CLONE_VM), the kernel calls dup_mm() and dup_mmap() to duplicate VMAs and page tables, landing in copy_page_range() (mm/memory.c, 6.18.55 line 1505; linux-next line 1552) and __copy_present_ptes():
/* 來源查核:Linux 6.18.55 (mm/memory.c: L1097-1108) */
static __always_inline void __copy_present_ptes(struct vm_area_struct *dst_vma,
struct vm_area_struct *src_vma, pte_t *dst_pte, pte_t *src_pte,
pte_t pte, unsigned long addr, int nr)
{
struct mm_struct *src_mm = src_vma->vm_mm;
/* 若為 COW 映射且原頁可寫,同步把父子兩端 PTE 都設成寫保護(唯讀) */
if (is_cow_mapping(src_vma->vm_flags) && pte_write(pte)) {
wrprotect_ptes(src_mm, addr, src_pte, nr);
pte = pte_wrprotect(pte);
}
...
}
這幾行程式碼非常值得細看:fork() 當下根本不會搬動任何一塊預載好的實體 RAM,它只是把父行程(Zygote)與子行程的頁表項目(PTE)同時設成寫保護(wrprotect_ptes/pte_wrprotect),指向完全相同的實體頁。比對最新的 linux-next(7.3.0-rc6,mm/memory.c 第 1124–1156 行)還能看見更嚴謹的防呆演進:核心改以 vma_is_cow_mapping(src_vma) 判斷,並先快照 writable = pte_write(pte),防止在處理 userfaultfd 保護解除時誤跳過 COW 寫保護。你可以把 Zygote 想像成「已經熬好高湯底的中央廚房母鍋」,每開一家分店只需先掛牌共用這鍋湯底,不必每間重熬;但這個比喻有個明確的適用邊界——唯有子行程對預載頁面保持唯讀,共享紅利才存在。一旦某支 App 寫入原本共用的頁面,CPU 立刻觸發寫保護頁錯誤並進入 do_wp_page()(6.18.55 第 4063 行;linux-next 第 4442 行)配置新頁複製內容,該頁隨即從 Shared Clean 變成只屬於該 App 的 Private Dirty;這也是為何 preloaded-classes 塞入太多冷門類別反而會拉長開機時間又浪費記憶體。
Those few lines explain the magic: during fork(), Linux copies zero physical pages of preloaded memory—it merely marks both parent (Zygote) and child page-table entries (PTEs) read-only via wrprotect_ptes() and pte_wrprotect() while pointing them at the same physical frames. Comparing against linux-next (7.3.0-rc6, mm/memory.c lines 1124–1156) highlights an even tighter safeguard: the kernel now uses vma_is_cow_mapping(src_vma) and snapshots writable = pte_write(pte) beforehand so disarming userfaultfd protection cannot accidentally skip COW write-protection. Think of Zygote as a central kitchen stockpot that every branch shares by reference instead of simmering anew. The clear boundary of this analogy is read-only access: the moment a child writes to a shared page, the CPU faults into do_wp_page() (6.18.55 line 4063; linux-next line 4442) to allocate and copy a private page, converting Shared Clean into Private Dirty. That is also why bloating preloaded-classes with rarely used classes slows down boot while wasting memory.
機制三:SystemServer 三階段系統服務註冊時序 / Mechanism 3: SystemServer's Three-Phase Service Startup
Zygote 孵化出的第一個重量級子行程就是 system_server,它是整個 Android 框架層的大腦。直接核對 AOSP SystemServer.java(refs/heads/main),從 main()(第 684 行)進入 run()(第 792 行)並透過 createSystemContext()(第 917 與 1094 行)建立系統上下文之後,數十個核心服務並不是亂序並發亂撞,而是按嚴格依賴拆成三個階段依序點火:
Zygote's first heavyweight child is system_server, the control plane of the Android framework. Checking AOSP's SystemServer.java (refs/heads/main), after main() (line 684) enters run() (line 792) and builds the system context via createSystemContext() (lines 917 and 1094), dozens of framework services are not fired blindly in parallel—they boot in three dependency-ordered phases:
第一階段是 startBootstrapServices()(第 976 與 1110 行),啟動系統最底層且彼此緊密相依的引導服務,包括管理行程與生命週期的 ActivityManagerService(AMS)、電源管理 PowerManagerService,以及負責掃描所有已安裝 APK 的 PackageManagerService(PMS)。第二階段 startCoreServices()(第 977 與 1419 行)接續拉起電量統計、用量統計與 WebView 更新等核心輔助服務。第三階段 startOtherServices()(第 978 與 1501 行)則一口氣啟動視窗管理 WindowManagerService(WMS)、輸入系統、網路與通知等大量服務,讓各服務透過原生 servicemanager 完成 Binder IPC(跨行程通訊)註冊。當所有關鍵服務進入就緒階段後,ActivityManagerService.systemReady() 會啟動主畫面 Launcher、由 SurfaceFlinger 停止開機動畫,並寫入 sys.boot_completed=1 宣告開機完成。
Phase one, startBootstrapServices() (lines 976 and 1110), launches tightly coupled foundational services including ActivityManagerService (AMS), PowerManagerService, and PackageManagerService (PMS), which scans installed APKs. Phase two, startCoreServices() (lines 977 and 1419), brings up core supporting services such as battery stats, usage stats, and WebView update tracking. Phase three, startOtherServices() (lines 978 and 1501), starts WindowManagerService (WMS), input, networking, notifications, and more, registering each over Binder IPC with native servicemanager. Once critical services reach ready phases, ActivityManagerService.systemReady() launches the Home Launcher, SurfaceFlinger stops the boot animation, and sys.boot_completed=1 signals boot completion.
影響與實務優化策略:為什麼開機動畫總卡在那幾秒? / Impact & Optimization: Where Boot Animations Stall
把整條啟動鏈攤平之後,AOSP 官方《Optimize boot times》文件裡提到的幾個關鍵瓶頸就完全不再抽象。第一,在 init 階段,若多個彼此無依賴的 .rc 動作寫成嚴格串行,或是大核心在開機初期被 cpuset 與頻率策略鎖在低頻,前置作業就會平白拖慢;在支援 FBE(檔案層級加密)的裝置上,把 Zygote 提前到 zygote-start 觸發器啟動,能讓 ART 暖機與其他原生初始化重疊進行。第二,在 Zygote 與 SystemServer 階段,最常見的兩大元凶分別是「過肥的 preloaded-classes 清單」與「缺乏建置期 DEX 預編譯(dexopt/dex2oat)」——一旦系統更新或刷機後 APK 還沒預先編譯,PMS 在 startBootstrapServices() 期間掃描與編譯位元組碼就會成為最長的一堵牆;此外,若廠商客製化服務在 SystemServer 主執行緒裡做同步磁碟或網路阻塞,也會直接拖住整段進桌面的時間。
With the full chain laid out, the bottlenecks highlighted in AOSP's official Optimize boot times guide make immediate sense. First, during init, serializing independent .rc actions—or leaving early boot workloads pinned to throttled CPU frequencies or restricted cpusets—wastes wall-clock time; on File-Based Encryption (FBE) devices, starting Zygote earlier at the zygote-start trigger lets ART warm up in parallel with native initialization. Second, across Zygote and SystemServer, the biggest culprits are bloated preloaded-classes lists and missing build-time DEX pre-optimization (dexopt/dex2oat), which forces PMS to scan or compile bytecode during startBootstrapServices(). Likewise, any vendor service performing synchronous blocking I/O on SystemServer's main thread holds up the entire path to the Launcher.
可操作小步驟:先用唯讀 adb 驗證行程樹與開機時間軸 / Actionable Steps: Read-Only adb Checks Before Recording Traces
以下指令適用於已啟用 USB 除錯、且透過 adb 連線至電腦的 Android 實體機或官方模擬器(無需 root 權限;本文僅列標準排查指令,不捏造任何實測輸出數字)。步驟 1 與步驟 2 全程皆為唯讀觀察,不會修改系統屬性、檔案或影響裝置正常運作:
The commands below apply to any Android device or official emulator connected over adb with USB debugging enabled (no root required; these are standard diagnostic commands with no fabricated benchmark output). Steps 1 and 2 are strictly read-only and do not alter device state or system properties:
# 步驟 1(唯讀):確認 init (PID 1) → zygote → system_server 的父子行程樹與開機旗標
adb shell "ps -A -o PID,PPID,NAME | grep -E '^( *1 |.*(zygote|system_server|servicemanager))'"
adb shell getprop ro.zygote
adb shell getprop sys.boot_completed
# 步驟 1B(唯讀):觀察 system_server 記憶體的 Shared Clean / Private Dirty(對照 COW 共享狀態)
adb shell dumpsys meminfo system_server | head -n 35
接著用步驟 2(唯讀)直接讀取 Android 內建寫入事件緩衝區的 boot_progress_* 時間戳。你只要算出相鄰兩行事件的時間差,就能立刻分辨時間是耗在 preload_start → preload_end(Zygote 預載)、pms_start → pms_ready(套件掃描),還是 ams_ready → enable_screen(進桌面與畫面解鎖):
Next, Step 2 (read-only) reads Android's built-in boot_progress_* milestones from the events log buffer. Subtracting timestamps between adjacent lines immediately reveals whether time went into preload_start → preload_end (Zygote preloading), pms_start → pms_ready (package scanning), or ams_ready → enable_screen (home launch and display enablement):
# 步驟 2(唯讀):拉出開機關鍵里程碑與開機動畫停止時間戳
adb logcat -b events -d | grep -E "boot_progress|sf_stop_bootanim"
步驟 3(進階開發機寫入型追蹤提醒):如果步驟 2 已經指向特定耗時區段、需要看跨 CPU 與 I/O 的細部火焰圖,AOSP 官方建議在測試機(通常需 userdebug/eng 映像檔或支援開機錄製的開發環境)啟用 Bootchart 或 Perfetto。請注意,在裝置端寫入開機追蹤設定(例如建立 /data/bootchart/enabled 旗標或設定開機期 Perfetto trace config)會在重開機過程寫入暫存檔並增加少量 I/O 開銷,量測完畢務必刪除旗標檔並關閉錄製,避免正式機長期背負額外開機成本。
Step 3 (Write-Operation Notice for Dev Builds): If Step 2 isolates a slow window and you need CPU/I/O timelines, AOSP recommends Bootchart or Perfetto on test devices (typically userdebug/eng builds or boot-tracing setups). Because enabling boot-time recording (such as touching /data/bootchart/enabled or arming a boot Perfetto config) writes trace files to storage and adds minor I/O overhead during boot, always remove the trigger file and disable capture once profiling finishes.
總結回顧:下次再遇到 Android 更新後卡在開機動畫,你腦中已經有一條清晰的分段路線圖:Linux 核心在 kernel_init() 交棒給 /init,雙階段 init 搭好 SELinux 與屬性舞台,Zygote 藉助 Linux __copy_present_ptes() 的 COW 寫時複製替上百個行程攤提預載成本,最後由 SystemServer 按 Bootstrap、Core、Other 三階段點亮所有系統服務。先用唯讀的 boot_progress_* 事件抓出最長的一段,再對症檢查 .rc 串行依賴、預載清單或 DEX 預編譯,就能把開機調校從盲猜變成可量測的工程實踐。
Takeaway: The next time an Android device stalls on the boot animation, you have a clear map to follow: Linux hands off in kernel_init() to /init, two-stage init establishes SELinux and properties, Zygote amortizes preloading via Linux COW in __copy_present_ptes(), and SystemServer brings up Bootstrap, Core, and Other services in dependency order. Start with read-only boot_progress_* timestamps to isolate the slowest segment, then inspect .rc ordering, preload lists, or DEX pre-optimization with evidence instead of guesswork.
反覆執行 adb logcat、檢視 Perfetto 開機時間軸與同時對照 AOSP 及 Linux 核心原始碼時,穩定的傳輸線材、多機桌面收納與順手的人體工學周邊能讓除錯動線清爽不少。若有添購開發工作站周邊的需求,可透過下方連結前往蝦皮瀏覽選品。
導流與延伸閱讀 / Related Articles
參考資料與官方文獻 / References
- Linux Kernel Source Tree (
v6.18.55):init/main.c(L165, L1434–1474)、kernel/fork.c(L1495, L1520–1555, L2570)、mm/memory.c(L1097–1118__copy_present_ptes(), L1505copy_page_range(), L4063do_wp_page())。本機原始碼查核日期:2026-12-04 (Asia/Taipei)。 - Linux Kernel
linux-nextSource Tree (v7.3.0-rc6):init/main.c(L169–170, L1552–1594)、kernel/fork.c(L1542, L1567, L2720)、mm/memory.c(L1124–1160__copy_present_ptes()新增writable快照與vma_is_cow_mapping(), L1552, L4442)。本機原始碼查核日期:2026-12-04 (Asia/Taipei)。 - Android Open Source Project (AOSP):Optimize boot times(查核日期:2026-12-04)。
- Android Open Source Project (AOSP):Android Init Language (system/core/init/README.md)(查核日期:2026-12-04)。
- Android Open Source Project (AOSP):ZygoteInit.java(
preload()L128、forkSystemServer()L693/L905、main()L817、runSelectLoop()L919;查核日期:2026-12-04)。 - Android Open Source Project (AOSP):SystemServer.java(
main()L684、run()L792、createSystemContext()L917/L1094、startBootstrapServices()L1110、startCoreServices()L1419、startOtherServices()L1501;查核日期:2026-12-04)。 - Android Developers:App startup time(查核日期:2026-12-04)。
- The Linux Kernel Documentation:Explaining the "No working init found." boot hang message(查核日期:2026-12-04)。
留言
張貼留言