Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 5 源碼剖析:Zygote與SystemServer啟動全流程

編輯:關於 Android 開發

Android 5 源碼剖析:Zygote與SystemServer啟動全流程

前言

Android 5.0.1的啟動流程相比之前版本變化不大——雖然SystemServer啟動過程中的init1()、init2()被拿掉了,但主幹流程依舊不變:Linux內核加載完畢後,首先啟動init進程,接著解析init.rc,並據此裝載Android文件系統、創建系統目錄、初始化屬性系統、拉起若干守護進程,其中最重要的就是Zygote進程。Zygote初始化時會創建Dalvik虛擬機、預裝載系統資源與Java類,所有由它fork出來的使用者進程都會繼承並共享這些預加載資源。可以說,init是Android的第一個進程,Zygote則是所有使用者進程的根進程,而SystemServer是Zygote fork出的第一個進程,也是整個系統的核心進程。

Zygote 進程

解析 zygote.rc

文件 /system/core/rootdir/init.rc 中包含了 zygote.rc:

 import /init.${ro.zygote}.rc

${ro.zygote}是平台相關參數,可對應到 init.zygote32.rc、init.zygote64.rc、init.zygote64_32.rc、init.zygote32_64.rc。前兩個只啟動單一app_process(64)進程,後兩個則會啟動兩個app_process進程(第二個稱為secondary)。為簡化起見,這裡只討論單進程情形。

以 init.zygote32.rc 為例:

  service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server class main socket zygote stream 660 root system onrestart write /sys/android_power/request_state wake onrestart write /sys/power/state on onrestart restart media onrestart restart netd

第一行創建了名為zygote的進程,透過app_process的main啟動,並以"-Xzygote /system/bin –zygote –start-system-server"作為入口參數。

app_process對應 framework/base/cmds/app_process/app_main.cpp。在其main函數中:

 AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv)); if (zygote) { runtime.start("com.android.internal.os.ZygoteInit", args); } else if (className) { runtime.start("com.android.internal.os.RuntimeInit", args); }

由入口參數可知zygote為true,args中包含了"start-system-server"。AppRuntime繼承自AndroidRuntime,因此下一步進入AndroidRuntime的start函數。

 void AndroidRuntime::start(const char* className, const Vector& options) { /* start the virtual machine */ // 創建虛擬機 JniInvocation jni_invocation; jni_invocation.Init(NULL); JNIEnv* env; if (startVm(&mJavaVM, &env) != 0) { return; } onVmCreated(env); ... //調用className對應類的靜態main()函數 char* slashClassName = toSlashClassName(className); jclass startClass = env->FindClass(slashClassName); jmethodID startMeth = env->GetStaticMethodID(startClass, "main", env->CallStaticVoidMethod(startClass, startMeth, strArray); ... }

start函數主要做兩件事:創建虛擬機,以及調用傳入類名對應類的main函數。因此下一步進入 com.android.internal.os.ZygoteInit 的 main 函數。

  public static void main(String argv[]) { try { boolean startSystemServer = false; String socketName = "zygote"; for (int i = 1; i < argv.length; i++) { if ("start-system-server".equals(argv[i])) { startSystemServer = true; } ... } registerZygoteSocket(socketName); ... preload(); ... if (startSystemServer) { startSystemServer(abiList, socketName); } Log.i(TAG, "Accepting command socket connections"); runSelectLoop(abiList); closeServerSocket(); } catch (MethodAndArgsCaller caller) { caller.run(); } catch (RuntimeException ex) { Log.e(TAG, "Zygote died with exception", ex); closeServerSocket(); throw ex; } }

它主要做了三件事:
1. 調用 registerZygoteSocket 創建一個socket接口,用來和ActivityManagerService通訊;
2. 調用 startSystemServer 啟動SystemServer;
3. 調用 runSelectLoop 進入無限循環,在socket接口上等待ActivityManagerService請求創建新的應用程式進程。

這裡要留意 catch (MethodAndArgsCaller caller) 這一行——Android在這裡透過拋出一個異常來處理正常的業務邏輯。

  socket zygote stream 660 root system

系統啟動腳本init.rc由init進程解釋執行,其源碼位於system/core/init目錄。在init.c中,由service_start函數解釋init.zygote32.rc裡的service命令:

  void service_start(struct service *svc, const char *dynamic_args) { ... pid = fork(); if (pid == 0) { struct socketinfo *si; ... for (si = svc->sockets; si; si = si->next) { int socket_type = ( !strcmp(si->type, "stream") ? SOCK_STREAM : (!strcmp(si->type, "dgram") ? SOCK_DGRAM : SOCK_SEQPACKET)); int s = create_socket(si->name, socket_type, si->perm, si->uid, si->gid, si->socketcon ?: scon); if (s >= 0) { publish_socket(si->name, s); } } ... } ... }

每個service命令都會促使init進程調用fork創建新進程;在新進程中,會解析其中的socket選項,對每個socket選項透過create_socket在 /dev/socket 目錄下創建文件。zygote的socket選項為"socket zygote stream 660 root system",因此這個文件便是zygote了。接著得到的文件描述符透過publish_socket寫入環境變量:

  static void publish_socket(const char *name, int fd) { char key[64] = ANDROID_SOCKET_ENV_PREFIX; char val[64]; strlcpy(key + sizeof(ANDROID_SOCKET_ENV_PREFIX) - 1, name, sizeof(key) - sizeof(ANDROID_SOCKET_ENV_PREFIX)); snprintf(val, sizeof(val), "%d", fd); add_environment(key, val); /* make sure we don't close-on-exec */ fcntl(fd, F_SETFD, 0); }

這裡name值為"zygote",而 ANDROID_SOCKET_ENV_PREFIX 在 system/core/include/cutils/sockets.h 中定義為:

 #define ANDROID_SOCKET_ENV_PREFIX "ANDROID_SOCKET_" #define ANDROID_SOCKET_DIR "/dev/socket"

於是文件描述符被寫入以"ANDROID_SOCKET_zygote"為key的環境變量。由於 ZygoteInit.registerZygoteSocket 與 create_socket 運行在同一進程,前者可直接用這個文件描述符創建Java層的LocalServerSocket物件。也就是說,創建zygote socket之後,ActivityManagerService就能透過該socket與zygote進程通信,從而fork創建新進程——Android中的所有應用進程都是這樣由zygote fork出來的。在ActivityManagerService的startProcessLocked中調用了Process.start(),進而調用 Process.startViaZygote 和 Process.openZygoteSocketIfNeeded。

啟動 SystemServer

socket創建完成後,緊接著透過 startSystemServer 函數啟動SystemServer進程。

  private static boolean startSystemServer(String abiList, String socketName) { long capabilities = posixCapabilitiesAsBits( OsConstants.CAP_BLOCK_SUSPEND, OsConstants.CAP_KILL, OsConstants.CAP_NET_ADMIN, OsConstants.CAP_NET_BIND_SERVICE, OsConstants.CAP_NET_BROADCAST, OsConstants.CAP_NET_RAW, OsConstants.CAP_SYS_MODULE, OsConstants.CAP_SYS_NICE, OsConstants.CAP_SYS_RESOURCE, OsConstants.CAP_SYS_TIME, OsConstants.CAP_SYS_TTY_CONFIG ); /* Hardcoded command line to start the system server */ String args[] = { "--setuid=1000", "--setgid=1000", "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1032,3001,3002,3003,3006,3007", "--capabilities=" + capabilities + "," + capabilities, "--runtime-init", "--nice-name=system_server", "com.android.server.SystemServer", }; ZygoteConnection.Arguments parsedArgs = null; int pid; try { parsedArgs = new ZygoteConnection.Arguments(args); ... /* Request to fork the system server process */ pid = Zygote.forkSystemServer( parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.debugFlags, null, parsedArgs.permittedCapabilities, parsedArgs.effectiveCapabilities); } catch (IllegalArgumentException ex) { throw new RuntimeException(ex); } /* For child process */ if (pid == 0) { if (hasSecondZygote(abiList)) { waitForSecondaryZygote(socketName); } handleSystemServerProcess(parsedArgs); } return true; }

從參數可推測:創建名為"system_server"的進程,入口是 com.android.server.SystemServer 的 main 函數。zygote透過 Zygote.forkSystemServer 創建新進程來啟動SystemServer,返回值pid為0的地方就是新進程要執行的路徑,即 handleSystemServerProcess 函數。hasSecondZygote針對 init.zygote64_32.rc、init.zygote32_64.rc 兩種情況,這裡跳過。接著看 handleSystemServerProcess:

  /** * Finish remaining work for the newly forked system server process. */ private static void handleSystemServerProcess( ZygoteConnection.Arguments parsedArgs) throws ZygoteInit.MethodAndArgsCaller { closeServerSocket(); // set umask to 0077 so new files and directories will default to owner-only permissions. Os.umask(S_IRWXG | S_IRWXO); if (parsedArgs.niceName != null) { Process.setArgV0(parsedArgs.niceName); } final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH"); ClassLoader cl = null; if (systemServerClasspath != null) { cl = new PathClassLoader(systemServerClasspath, ClassLoader.getSystemClassLoader()); Thread.currentThread().setContextClassLoader(cl); } /* * Pass the remaining arguments to SystemServer. */ RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl); /* should never reach here */ }

handleSystemServerProcess會拋出MethodAndArgsCaller異常——前面提過,這個異常其實是用來處理正常業務邏輯的,相當於一個回調。由於zygote創建的子進程會繼承前面創建的socket文件描述符,而子進程並用不到它,因此這裡調用 closeServerSocket 將其關閉。SYSTEMSERVERCLASSPATH是包含 /system/framework/framework.jar 的環境變量,定義在 system/core/rootdir/init.environ.rc.in 中:

  on init export PATH /sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin export ANDROID_BOOTLOGO 1 export ANDROID_ROOT /system export SYSTEMSERVERCLASSPATH %SYSTEMSERVERCLASSPATH% export LD_PRELOAD libsigchain.so

handleSystemServerProcess接著調用 RuntimeInit.zygoteInit 進一步啟動SystemServer組件。

  public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) throws ZygoteInit.MethodAndArgsCaller { commonInit(); nativeZygoteInit(); applicationInit(targetSdkVersion, argv, classLoader); }

commonInit設置線程未處理異常handler、時區等;JNI方法 nativeZygoteInit 實現在 frameworks/base/core/jni/AndroidRuntime.cpp 中:

 static AndroidRuntime* gCurRuntime = NULL; static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz) { gCurRuntime->onZygoteInit(); }

AndroidRuntime是帶虛函數的基類,真正的實現在 app_main.cpp 的 AppRuntime:

 class AppRuntime : public AndroidRuntime { virtual void onStarted() { sp proc = ProcessState::self(); ALOGV("App process: starting thread pool.\n"); proc->startThreadPool(); AndroidRuntime* ar = AndroidRuntime::getRuntime(); ar->callMain(mClassName, mClass, mArgs); IPCThreadState::self()->stopProcess(); } virtual void onZygoteInit() { // Re-enable tracing now that we're no longer in Zygote. atrace_set_tracing_enabled(true); sp proc = ProcessState::self(); ALOGV("App process: starting thread pool.\n"); proc->startThreadPool(); } virtual void onExit(int code) { if (mClassName.isEmpty()) { // if zygote IPCThreadState::self()->stopProcess(); } AndroidRuntime::onExit(code); } };

透過執行 AppRuntime::onZygoteInit,這個進程的Binder進程間通信基礎設施就準備好了(參考 frameworks/native/libs/binder/ProcessState.cpp)。接著看 applicationInit:

  private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) throws ZygoteInit.MethodAndArgsCaller { final Arguments args; try { args = new Arguments(argv); } catch (IllegalArgumentException ex) { Slog.e(TAG, ex.getMessage()); // let the process exit return; } // Remaining arguments are passed to the start class's static main invokeStaticMain(args.startClass, args.startArgs, classLoader); }

applicationInit僅僅轉調 invokeStaticMain:

  private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader) throws ZygoteInit.MethodAndArgsCaller { Class cl; cl = Class.forName(className, true, classLoader); Method m; m = cl.getMethod("main", new Class[] { String[].class }); /* * This throw gets caught in ZygoteInit.main(), which responds * by invoking the exception's run() method. This arrangement * clears up all the stack frames that were required in setting * up the process. */ throw new ZygoteInit.MethodAndArgsCaller(m, argv); }

invokeStaticMain透過反射找到參數className對應類的靜態main方法,並把該方法與參數封裝成 ZygoteInit.MethodAndArgsCaller 物件當作異常拋出,這個異常會在 ZygoteInit 的 main 函數中被捕獲並執行其 run 方法。

  /** * Helper exception class which holds a method and arguments and * can call them. This is used as part of a trampoline to get rid of * the initial process setup stack frames. */ public static class MethodAndArgsCaller extends Exception implements Runnable { public void run() { ... mMethod.invoke(null, new Object[] { mArgs }); ... } }

看似繁複的跳轉,其實只做了一件簡單的事:根據className反射調用該類的靜態main方法。這個類名是在 ZygoteInit.startSystemServer 中寫死的 com.android.server.SystemServer,從而進入 SystemServer 類的 main() 方法。

執行 ZygoteInit.runSelectLoop

在 startSystemServer 中,創建 system_server 進程後,pid等於0時在新進程中執行 SystemServer.main,否則回到zygote進程執行 ZygoteInit.runSelectLoop:

  private static void runSelectLoop(String abiList) throws MethodAndArgsCaller { ArrayList fds = new ArrayList(); ArrayList peers = new ArrayList(); FileDescriptor[] fdArray = new FileDescriptor[4]; fds.add(sServerSocket.getFileDescriptor()); peers.add(null); int loopCount = GC_LOOP_COUNT; while (true) { int index; /* * Call gc() before we block in select(). * It's work that has to be done anyway, and it's better * to avoid making every child do it. It will also * madvise() any free memory as a side-effect. * * Don't call it every time, because walking the entire * heap is a lot of overhead to free a few hundred bytes. */ if (loopCount <= 0) { gc(); loopCount = GC_LOOP_COUNT; } else { loopCount--; } try { fdArray = fds.toArray(fdArray); index = selectReadable(fdArray); } catch (IOException ex) { throw new RuntimeException("Error in select()", ex); } if (index < 0) { throw new RuntimeException("Error in select()"); } else if (index == 0) { ZygoteConnection newPeer = acceptCommandPeer(abiList); peers.add(newPeer); fds.add(newPeer.getFileDescriptor()); } else { boolean done; done = peers.get(index).runOnce(); if (done) { peers.remove(index); fds.remove(index); } } } }

runSelectLoop邏輯較簡單,主要有兩點:
1、處理客戶端的連接與請求。前面創建的LocalServerSocket物件保存在 sServerSocket,透過 selectReadable 等待 ActivityManagerService(簡稱AMS)與之通信。selectReadable是native函數,內部調用select等待AMS連接,返回後:返回值<0表示內部出錯;=0表示首次連接;>0表示已建立連接並開始發送數據。每個鏈接在zygote進程中用 ZygoteConnection 物件表示。
2、客戶端請求由 ZygoteConnection.runOnce 處理,這個方法同樣拋出MethodAndArgsCaller異常,從而進入 MethodAndArgsCaller.run 中,根據請求數據反射出的類的main方法。

  private String[] readArgumentList() { int argc; try { String s = mSocketReader.readLine(); if (s == null) { // EOF reached. return null; } argc = Integer.parseInt(s); } catch (NumberFormatException ex) { Log.e(TAG, "invalid Zygote wire format: non-int at argc"); throw new IOException("invalid wire format"); } String[] result = new String[argc]; for (int i = 0; i < argc; i++) { result[i] = mSocketReader.readLine(); if (result[i] == null) { // We got an unexpected EOF. throw new IOException("truncated request"); } } return result; } boolean runOnce() throws ZygoteInit.MethodAndArgsCaller { String args[]; Arguments parsedArgs = null; args = readArgumentList(); parsedArgs = new Arguments(args); ... pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo, parsedArgs.niceName, fdsToClose, parsedArgs.instructionSet, parsedArgs.appDataDir); ... }

SystemServer 啟動過程

前面提到,透過反射調用 com.android.server.SystemServer 的 main() 函數,便開始了SystemServer的初始化流程。

SystemServer.main()

  /** * The main entry point from zygote. */ public static void main(String[] args) { new SystemServer().run(); }

main函數創建一個SystemServer物件,調用其 run() 方法。

  private void run() { // If a device's clock is before 1970 (before 0), a lot of // APIs crash dealing with negative numbers, notably // java.io.File#setLastModified, so instead we fake it and // hope that time from cell towers or NTP fixes it shortly. if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) { Slog.w(TAG, "System clock is before 1970; setting to 1970."); SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME); } // 檢測時間設置 // Here we go! Slog.i(TAG, "Entered the Android system server!"); EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis()); // In case the runtime switched since last boot (such as when // the old runtime was removed in an OTA), set the system // property so that it is in sync. We can't do this in // libnativehelper's JniInvocation::Init code where we already // had to fallback to a different runtime because it is // running as root and we need to be the system user to set // the property. https://b/11463182 SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary()); // Enable the sampling profiler. if (SamplingProfilerIntegration.isEnabled()) { SamplingProfilerIntegration.start(); mProfilerSnapshotTimer = new Timer(); mProfilerSnapshotTimer.schedule(new TimerTask() { @Override public void run() { SamplingProfilerIntegration.writeSnapshot("system_server", null); } }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL); } // 啟動性能分析采樣 // Mmmmmm... more memory! VMRuntime.getRuntime().clearGrowthLimit(); // The system server has to run all of the time, so it needs to be // as efficient as possible with its memory usage. VMRuntime.getRuntime().setTargetHeapUtilization(0.8f); // Some devices rely on runtime fingerprint generation, so make sure // we've defined it before booting further. Build.ensureFingerprintProperty(); // Within the system server, it is an error to access Environment paths without // explicitly specifying a user. Environment.setUserRequired(true); // Ensure binder calls into the system always run at foreground priority. BinderInternal.disableBackgroundScheduling(true); // Prepare the main looper thread (this thread). android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_FOREGROUND); android.os.Process.setCanSelfBackground(false); Looper.prepareMainLooper(); // 准備主線程循環 // Initialize native services. System.loadLibrary("android_servers"); nativeInit(); // Check whether we failed to shut down last time we tried. // This call may not return. performPendingShutdown(); // Initialize the system context. createSystemContext(); // Create the system service manager. mSystemServiceManager = new SystemServiceManager(mSystemContext); LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); // Start services. // 啟動服務 try { startBootstrapServices(); startCoreServices(); startOtherServices(); } catch (Throwable ex) { Slog.e("System", "******************************************"); Slog.e("System", "************ Failure starting system services", ex); throw ex; } // For debug builds, log event loop stalls to dropbox for analysis. if (StrictMode.conditionallyEnableDebugLogging()) { Slog.i(TAG, "Enabled StrictMode for system server main thread."); } // Loop forever. Looper.loop(); // 啟動線程循環,等待消息處理 throw new RuntimeException("Main thread loop unexpectedly exited"); }

在 run 方法中主要完成三件事:創建 system context 與 system service manager、啟動一系列系統服務、進入主線程消息循環。

Zygote 的 fork 本地方法分析

接下來仔細分析 Zygote.forkSystemServer 與 Zygote.forkAndSpecialize 兩個方法。

forkSystemServer

  private static final ZygoteHooks VM_HOOKS = new ZygoteHooks(); public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags, int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) { VM_HOOKS.preFork(); int pid = nativeForkSystemServer( uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities); VM_HOOKS.postForkCommon(); return pid; }

在調用 nativeForkSystemServer 創建 system_server 進程的前後,都會調用 ZygoteHooks 做前置與後置處理。

ZygoteHooks.preFork

前置處理 ZygoteHooks.preFork:

  public void preFork() { Daemons.stop(); waitUntilAllThreadsStopped(); token = nativePreFork(); }

Daemons.stop() 停止虛擬機中的一些守護線程(引用隊列、終接器、GC等):

  public static void stop() { ReferenceQueueDaemon.INSTANCE.stop(); FinalizerDaemon.INSTANCE.stop(); FinalizerWatchdogDaemon.INSTANCE.stop(); HeapTrimmerDaemon.INSTANCE.stop(); GCDaemon.INSTANCE.stop(); }

waitUntilAllThreadsStopped 保證被fork的進程是單線程,這樣可以確保透過copy-on-write fork出來的進程也是單線程,從而節省資源,與前面關閉socket有異曲同工之妙。

  /** * We must not fork until we're single-threaded again. Wait until /proc shows we're * down to just one thread. */ private static void waitUntilAllThreadsStopped() { File tasks = new File("/proc/self/task"); while (tasks.list().length > 1) { try { // Experimentally, booting and playing about with a stingray, I never saw us // go round this loop more than once with a 10ms sleep. Thread.sleep(10); } catch (InterruptedException ignored) { } } }

本地方法 nativePreFork 實現在 art/runtime/native/dalvik_system_ZygoteHooks.cc 中。

  static jlong ZygoteHooks_nativePreFork(JNIEnv* env, jclass) { Runtime* runtime = Runtime::Current(); CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote"; runtime->PreZygoteFork(); // Grab thread before fork potentially makes Thread::pthread_key_self_ unusable. Thread* self = Thread::Current(); return reinterpret_cast(self); }

ZygoteHooks_nativePreFork透過調用 Runtime::PreZygoteFork 完成gc堆的一些初始化(代碼在 art/runtime/runtime.cc 中):

  heap_ = new gc::Heap(...); void Runtime::PreZygoteFork() { heap_->PreZygoteFork(); }

創建 system_server 進程

nativeForkSystemServer 實現在 framework/base/core/jni/com_android_internal_os_Zygote.cpp 中:

  static jint com_android_internal_os_Zygote_nativeForkSystemServer( JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids, jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities, jlong effectiveCapabilities) { pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags, rlimits, permittedCapabilities, effectiveCapabilities, MOUNT_EXTERNAL_NONE, NULL, NULL, true, NULL, NULL, NULL); if (pid > 0) { // The zygote process checks whether the child process has died or not. ALOGI("System server process %d has been created", pid); gSystemServerPid = pid; // There is a slight window that the system server process has crashed // but it went unnoticed because we haven't published its pid yet. So // we recheck here just to make sure that all is well. int status; if (waitpid(pid, &status, WNOHANG) == pid) { ALOGE("System server process %d has died. Restarting Zygote!", pid); RuntimeAbort(env); } } return pid; }

它轉調 ForkAndSpecializeCommon 創建新進程,並確保 system_server 創建成功;若不成功便重啟zygote(因為沒有system_server就幹不了什麼事)。ForkAndSpecializeCommon實現如下:

  static const char kZygoteClassName[] = "com/android/internal/os/Zygote"; gZygoteClass = (jclass) env->NewGlobalRef(env->FindClass(kZygoteClassName)); gCallPostForkChildHooks = env->GetStaticMethodID(gZygoteClass, "callPostForkChildHooks", "(ILjava/lang/String;)V"); // Utility routine to fork zygote and specialize the child process. static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids, jint debug_flags, jobjectArray javaRlimits, jlong permittedCapabilities, jlong effectiveCapabilities, jint mount_external, jstring java_se_info, jstring java_se_name, bool is_system_server, jintArray fdsToClose, jstring instructionSet, jstring dataDir) { SetSigChldHandler(); pid_t pid = fork(); if (pid == 0) { // The child process. ... rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str); ... UnsetSigChldHandler(); ... env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags, is_system_server ? NULL : instructionSet); } else if (pid > 0) { // the parent process } return pid; }

ForkAndSpecializeCommon首先設置子進程異常處理handler,然後fork新進程;在新進程中設置SELinux、清除子進程異常處理handler,然後調用 Zygote.callPostForkChildHooks。

  private static void callPostForkChildHooks(int debugFlags, String instructionSet) { long startTime = SystemClock.elapsedRealtime(); VM_HOOKS.postForkChild(debugFlags, instructionSet); checkTime(startTime, "Zygote.callPostForkChildHooks"); }

callPostForkChildHooks又轉調 ZygoteHooks.postForkChild:

  public void postForkChild(int debugFlags, String instructionSet) { nativePostForkChild(token, debugFlags, instructionSet); }

本地方法 nativePostForkChild 又進入 dalvik_system_ZygoteHooks.cc:

  static void ZygoteHooks_nativePostForkChild(JNIEnv* env, jclass, jlong token, jint debug_flags, jstring instruction_set) { Thread* thread = reinterpret_cast(token); // Our system thread ID, etc, has changed so reset Thread state. thread->InitAfterFork(); EnableDebugFeatures(debug_flags); if (instruction_set != nullptr) { ScopedUtfChars isa_string(env, instruction_set); InstructionSet isa = GetInstructionSetFromString(isa_string.c_str()); Runtime::NativeBridgeAction action = Runtime::NativeBridgeAction::kUnload; if (isa != kNone && isa != kRuntimeISA) { action = Runtime::NativeBridgeAction::kInitialize; } Runtime::Current()->DidForkFromZygote(env, action, isa_string.c_str()); } else { Runtime::Current()->DidForkFromZygote(env, Runtime::NativeBridgeAction::kUnload, nullptr); } }

thread->InitAfterFork()(art/runtime/thread.cc)設置新進程主線程的線程id。DidForkFromZygote(Runtime.cc)如下:

  void Runtime::DidForkFromZygote(JNIEnv* env, NativeBridgeAction action, const char* isa) { is_zygote_ = false; switch (action) { case NativeBridgeAction::kUnload: UnloadNativeBridge(); break; case NativeBridgeAction::kInitialize: InitializeNativeBridge(env, isa); break; } // Create the thread pool. heap_->CreateThreadPool(); StartSignalCatcher(); // Start the JDWP thread. If the command-line debugger flags specified "suspend=y", // this will pause the runtime, so we probably want this to come last. Dbg::StartJdwp(); }

它先根據action卸載或轉載用於跨平台橋接的庫,然後啟動gc堆的線程池,並透過StartSignalCatcher設置信號處理handler(代碼在 signal_catcher.cc 中)。

ZygoteHooks.postForkCommon

後置處理 ZygoteHooks.postForkCommon:

  public void postForkCommon() { Daemons.start(); }

postForkCommon轉調 Daemons.start,以初始化虛擬機中引用隊列、終接器與gc的守護線程。

  public static void start() { ReferenceQueueDaemon.INSTANCE.start(); FinalizerDaemon.INSTANCE.start(); FinalizerWatchdogDaemon.INSTANCE.start(); HeapTrimmerDaemon.INSTANCE.start(); GCDaemon.INSTANCE.start(); }

forkAndSpecialize

Zygote.forkAndSpecialize 方法:

  public static int forkAndSpecialize(int uid, int gid, int[] gids, int debugFlags, int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose, String instructionSet, String appDataDir) { long startTime = SystemClock.elapsedRealtime(); VM_HOOKS.preFork(); checkTime(startTime, "Zygote.preFork"); int pid = nativeForkAndSpecialize( uid, gid, gids, debugFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose, instructionSet, appDataDir); checkTime(startTime, "Zygote.nativeForkAndSpecialize"); VM_HOOKS.postForkCommon(); checkTime(startTime, "Zygote.postForkCommon"); return pid; }

前置與後置處理與 forkSystemServer 相同,此處不再贅述。本地方法 nativeForkAndSpecialize 實現在 framework/base/core/jni/com_android_internal_os_Zygote.cpp 中:

 static jint com_android_internal_os_Zygote_nativeForkAndSpecialize( JNIEnv* env, jclass, jint uid, jint gid, jintArray gids, jint debug_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring se_name, jintArray fdsToClose, jstring instructionSet, jstring appDataDir) { // Grant CAP_WAKE_ALARM to the Bluetooth process. jlong capabilities = 0; if (uid == AID_BLUETOOTH) { capabilities |= (1LL << CAP_WAKE_ALARM); } return ForkAndSpecializeCommon(env, uid, gid, gids, debug_flags, rlimits, capabilities, capabilities, mount_external, se_info, se_name, false, fdsToClose, instructionSet, appDataDir); }

這個函數與 com_android_internal_os_Zygote_nativeForkSystemServer 非常類似,只是少了「確保子進程創建成功」這一步。

總結:Zygote是所有應用進程的孵化器和根進程,它透過預加載資源並採用copy-on-write方式fork子進程來提升啟動效率;SystemServer作為它fork出的第一個進程,負責拉起各類核心系統服務,並進入Looper消息循環,支撐起整個Android框架的運行。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved