Java 世界的盤古和女媧 —— Zygote

本文基於 Android 9.0 , 代碼倉庫地址 : android_9.0.0_r45

文中源碼鏈接:

Zygote.java

ZygoteInit.java

ZygoteServer.java

ZygoteConnection.java

RuntimeInit.java

仔細看看下面這張 Android 體系圖,找一下 Zygote 在什麼地方。

上圖來自 Gityuan 博客

縱觀整個 Android 體系結構,底層內核空間以 Linux Kernel 爲核心,上層用戶空間以 C++/Java 組成的 Framework 層組成,通過系統調用來連接用戶空間和內核空間。而用戶空間又分爲 Native 世界和 Java 世界,通過 JNI 技術進行連接。Native 世界的 init 進程是所有用戶進程的祖先,其 pid 爲 1 。init 進程通過解析 init.rc 文件創建出 Zygote 進程,Zygote 進程人如其名,翻譯成中文就是 受精卵 的意思。它是 Java 世界的中的第一個進程,也是 Android 系統中的第一個 Java 進程,頗有盤古開天闢地之勢。

Zygote 創建的第一個進程就是 System ServerSystem Server 負責管理和啓動整個 Java Framework 層。創建完 System Server 之後,Zygote 就會完全進入受精卵的角色,等待進行無性繁殖,創建應用進程。所有的應用進程都是由 Zygote 進程 fork 而來的,稱之爲 Java 世界的女媧也不足爲過。

Zygote 的啓動過程是從 Native 層開始的,這裏不會 Native 層作過多分析,直接進入其在 Java 世界的入口 ZygoteInit.main() :

public static void main(String argv[]) {
    ZygoteServer zygoteServer = new ZygoteServer();

    // Mark zygote start. This ensures that thread creation will throw
    // an error.
    ZygoteHooks.startZygoteNoThreadCreation();

    // Zygote goes into its own process group.
    // 設置進程組 ID
    // pid 爲 0 表示設置當前進程的進程組 ID
    // gid 爲 0 表示使用當前進程的 PID 作爲進程組 ID
    try {
        Os.setpgid(0, 0);
    } catch (ErrnoException ex) {
        throw new RuntimeException("Failed to setpgid(0,0)", ex);
    }

    final Runnable caller;
    try {
        ......
        RuntimeInit.enableDdms(); // 啓用 DDMS

        boolean startSystemServer = false;
        String socketName = "zygote";
        String abiList = null;
        boolean enableLazyPreload = false;
        for (int i = 1; i < argv.length; i++) { // 參數解析
            if ("start-system-server".equals(argv[i])) {
                startSystemServer = true;
            } else if ("--enable-lazy-preload".equals(argv[i])) {
                enableLazyPreload = true;
            } else if (argv[i].startsWith(ABI_LIST_ARG)) {
                abiList = argv[i].substring(ABI_LIST_ARG.length());
            } else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
                socketName = argv[i].substring(SOCKET_NAME_ARG.length());
            } else {
                throw new RuntimeException("Unknown command line argument: " + argv[i]);
            }
        }

        if (abiList == null) {
            throw new RuntimeException("No ABI list supplied.");
        }

        // 1. 註冊服務端 socket,這裏的 IPC 不是 Binder 通信
        zygoteServer.registerServerSocketFromEnv(socketName); 
        // In some configurations, we avoid preloading resources and classes eagerly.
        // In such cases, we will preload things prior to our first fork.
        if (!enableLazyPreload) {
            bootTimingsTraceLog.traceBegin("ZygotePreload");
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
                SystemClock.uptimeMillis());
            preload(bootTimingsTraceLog); // 2. 預加載操作
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
                SystemClock.uptimeMillis());
            bootTimingsTraceLog.traceEnd(); // ZygotePreload
        } else {
            Zygote.resetNicePriority(); // 設置線程優先級爲 NORM_PRIORITY (5)
        }

        // Do an initial gc to clean up after startup
        gcAndFinalize(); // 3. 強制進行一次垃圾收集

        Zygote.nativeSecurityInit();

        // Zygote process unmounts root storage spaces.
        Zygote.nativeUnmountStorageOnInit();

        ZygoteHooks.stopZygoteNoThreadCreation();

        if (startSystemServer) {
            // 4. 啓動SystemServer 進程
            Runnable r = forkSystemServer(abiList, socketName, zygoteServer); 

            // {@code r == null} in the parent (zygote) process, and {@code r != null} in the
            // child (system_server) process.
            if (r != null) {
                r.run(); // 由 RuntimeInit.java 中的 MethodAndArgsCaller 反射調用SystemServer 的 main() 方法
                return;
            }
        }

        Log.i(TAG, "Accepting command socket connections");

        // The select loop returns early in the child process after a fork and
        // loops forever in the zygote.
        // 5. 循環等待處理客戶端請求
        caller = zygoteServer.runSelectLoop(abiList);
    } catch (Throwable ex) {
        Log.e(TAG, "System zygote died with exception", ex);
        throw ex;
    } finally {
        zygoteServer.closeServerSocket(); // 關閉並釋放 socket 連接
    }

    // We're in the child process and have exited the select loop. Proceed to execute the
    // command.
    if (caller != null) {
        caller.run();
    }
}

省去部分不是那麼重要的代碼,ZygoteInit.main() 方法大致可以分爲以下五個步驟:

  1. registerServerSocketFromEnv, 註冊服務端 socket,用於跨進程通信,這裏並沒有使用 Binder 通信。
  2. preload(),進行預加載操作
  3. gcAndFinalize(),在 forkSystemServer 之前主動進行一次垃圾回收
  4. forkSystemServer(),創建 SystemServer 進程
  5. runSelectLoop(),循環等待處理客戶端發來的 socket 請求

上面基本上就是 Zygote 的全部使命了,下面按照這個流程來詳細分析。

registerServerSocketFromEnv

> ZygoteServer.java

void registerServerSocketFromEnv(String socketName) {
    if (mServerSocket == null) {
        int fileDesc;
        final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
        try {
            // 從環境變量中獲取 socket 的 fd
            String env = System.getenv(fullSocketName);
            fileDesc = Integer.parseInt(env);
        } catch (RuntimeException ex) {
            throw new RuntimeException(fullSocketName + " unset or invalid", ex);
        }

        try {
            FileDescriptor fd = new FileDescriptor();
            fd.setInt$(fileDesc); // 設置文件描述符
            mServerSocket = new LocalServerSocket(fd); // 創建服務端 socket
            mCloseSocketFd = true;
        } catch (IOException ex) {
            throw new RuntimeException(
                    "Error binding to local socket '" + fileDesc + "'", ex);
        }
    }
}

首先從環境變量中獲取 socket 的文件描述符 fd,然後根據 fd 創建服務端 LocalServerSocket,用於 IPC 通信。這裏的環境變量是在 init 進程創建 Zygote 進程時設置的。

preload()

> ZygoteInit.java

static void preload(TimingsTraceLog bootTimingsTraceLog) {
        ......
        preloadClasses(); // 預加載並初始化 /system/etc/preloaded-classes 中的類
        ......
        preloadResources(); // 預加載系統資源
        ......
        nativePreloadAppProcessHALs(); // HAL?
        ......
        preloadOpenGL(); // 預加載 OpenGL
        ......
        preloadSharedLibraries(); // 預加載 共享庫,包括 android、compiler_rt、jnigraphics 這三個庫
        preloadTextResources(); // 預加載文字資源
        // Ask the WebViewFactory to do any initialization that must run in the zygote process,
        // for memory sharing purposes.
        // WebViewFactory 中一些必須在 zygote 進程中進行的初始化工作,用於共享內存
        WebViewFactory.prepareWebViewInZygote();
        warmUpJcaProviders();

        sPreloadComplete = true;
    }

preload() 方法主要進行一些類,資源,共享庫的預加載工作,以提升運行時效率。下面依次來看一下都預加載了哪些內容。

preloadClasses()

> ZygoteInit.java

private static void preloadClasses() {
    ......
    InputStream is;
    try {
        // /system/etc/preloaded-classes
        is = new FileInputStream(PRELOADED_CLASSES);
    } catch (FileNotFoundException e) {
        Log.e(TAG, "Couldn't find " + PRELOADED_CLASSES + ".");
        return;
    }

    try {
        BufferedReader br
            = new BufferedReader(new InputStreamReader(is), 256);

        int count = 0;
        String line;
        while ((line = br.readLine()) != null) {
            // Skip comments and blank lines.
            line = line.trim();
            if (line.startsWith("#") || line.equals("")) {
                continue;
            }

            try {
                // Load and explicitly initialize the given class. Use
                // Class.forName(String, boolean, ClassLoader) to avoid repeated stack lookups
                // (to derive the caller's class-loader). Use true to force initialization, and
                // null for the boot classpath class-loader (could as well cache the
                // class-loader of this class in a variable).
                Class.forName(line, true, null);
                count++;
            } catch (ClassNotFoundException e) {
                Log.w(TAG, "Class not found for preloading: " + line);
            } catch (UnsatisfiedLinkError e) {
                Log.w(TAG, "Problem preloading " + line + ": " + e);
            } catch (Throwable t) {
                ......
            }
        }
    } catch (IOException e) {
        Log.e(TAG, "Error reading " + PRELOADED_CLASSES + ".", e);
    } finally {
        IoUtils.closeQuietly(is);
        ......
    }
}

只保留了核心邏輯代碼。讀取 /system/etc/preloaded-classes 文件,並通過 Class.forName() 方法逐行加載文件中聲明的類。提前預加載系統常用的類無疑可以提升運行時效率,但是這個預加載常用類的工作通常都會很重。搜索整個源碼庫,在 /frameworks/base/config 目錄下發現一份 preloaded-classes 文件,打開這個文件,一共 6558 行,這就意味着要提前加載數千個類,這無疑會消耗很長時間,以增加 Android 系統啓動時間的代價提升了運行時的效率。

preloadResources()

> ZygoteInit.java

private static void preloadResources() {
    final VMRuntime runtime = VMRuntime.getRuntime();

    try {
        mResources = Resources.getSystem();
        mResources.startPreloading();
        if (PRELOAD_RESOURCES) {
            TypedArray ar = mResources.obtainTypedArray(
                    com.android.internal.R.array.preloaded_drawables);
            int N = preloadDrawables(ar);
            ar.recycle();
            ......
            ar = mResources.obtainTypedArray(
                    com.android.internal.R.array.preloaded_color_state_lists);
            N = preloadColorStateLists(ar);
            ar.recycle();

            if (mResources.getBoolean(
                    com.android.internal.R.bool.config_freeformWindowManagement)) {
                ar = mResources.obtainTypedArray(
                    com.android.internal.R.array.preloaded_freeform_multi_window_drawables);
                N = preloadDrawables(ar);
                ar.recycle();
            }
        }
        mResources.finishPreloading();
    } catch (RuntimeException e) {
        Log.w(TAG, "Failure preloading resources", e);
    }
}

從源碼中可知,主要加載的資源有:

com.android.internal.R.array.preloaded_drawables

com.android.internal.R.array.preloaded_color_state_lists

com.android.internal.R.array.preloaded_freeform_multi_window_drawables

preloadSharedLibraries()

> ZygoteInit.java

private static void preloadSharedLibraries() {
    Log.i(TAG, "Preloading shared libraries...");
    System.loadLibrary("android");
    System.loadLibrary("compiler_rt");
    System.loadLibrary("jnigraphics");
}

預加載了三個共享庫,libandroid.solibcompiler_rt.solibjnigraphics.so

gcAndFinalize()

> ZygoteInit.java

static void gcAndFinalize() {
    final VMRuntime runtime = VMRuntime.getRuntime();

    /* runFinalizationSync() lets finalizers be called in Zygote,
     * which doesn't have a HeapWorker thread.
     */
    System.gc();
    runtime.runFinalizationSync();
    System.gc();
}

forkSystemServer() 之前會主動進行一次 GC 操作。

forkSystemServer()

主動調用 GC 之後,Zygote 就要去做它的大事 —— fork SystemServer 進程了。

> ZygoteInit.java

private static Runnable forkSystemServer(String abiList, String socketName,
    
    ......
    
    /* 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,1021,1023,1024,1032,1065,3001,3002,3003,3006,3007,3009,3010",
        "--capabilities=" + capabilities + "," + capabilities,
        "--nice-name=system_server", // 進程名
        "--runtime-args",
        "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
        "com.android.server.SystemServer", // 加載類名
    };
    ZygoteConnection.Arguments parsedArgs = null;

    int pid;

    try {
        parsedArgs = new ZygoteConnection.Arguments(args);
        ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
        ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

        boolean profileSystemServer = SystemProperties.getBoolean(
                "dalvik.vm.profilesystemserver", false);
        if (profileSystemServer) {
            parsedArgs.runtimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
        }

        /* Request to fork the system server process
         * fork system_server 進程
         */
        pid = Zygote.forkSystemServer(
                parsedArgs.uid, parsedArgs.gid,
                parsedArgs.gids,
                parsedArgs.runtimeFlags,
                null,
                parsedArgs.permittedCapabilities,
                parsedArgs.effectiveCapabilities);
    } catch (IllegalArgumentException ex) {
        throw new RuntimeException(ex);
    }

    /* For child process */
    // pid == 0 表示子進程,從這裏開始進入 system_server 進程
    if (pid == 0) {
        if (hasSecondZygote(abiList)) { // 如果有第二個 Zygote
            waitForSecondaryZygote(socketName);
        }

        zygoteServer.closeServerSocket(); // 關閉並釋放從 Zygote copy 過來的 socket
        return handleSystemServerProcess(parsedArgs); // 完成新創建的 system_server 進程的剩餘工作
    }

    /**
     * 注意 fork() 函數式一次執行,兩次返回(兩個進程對同一程序的兩次執行)。
     * pid > 0  說明還是父進程。pid = 0 說明進入了子進程
     * 所以這裏的 return null 依舊會執行 
     */
    return null;
}

從上面的啓動參數可以看到,SystemServer 進程的 uidgid 都是 1000,進程名是 system_server ,其最後要加載的類名是 com.android.server.SystemServer 。準備好一系列參數之後通過 ZygoteConnection.Arguments() 拼接,接着調用 Zygote.forkSystemServer() 方法真正的 fork 出子進程 system_server

> Zygote.java

public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
        int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
    VM_HOOKS.preFork();
    // Resets nice priority for zygote process.
    resetNicePriority();
    int pid = nativeForkSystemServer(
            uid, gid, gids, runtimeFlags, rlimits, permittedCapabilities, effectiveCapabilities);
    // Enable tracing as soon as we enter the system_server.
    if (pid == 0) {
        Trace.setTracingEnabled(true, runtimeFlags);
    }
    VM_HOOKS.postForkCommon();
    return pid;
}

native private static int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
        int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);

最後的 fork() 操作是在 native 層完成的。再回到 ZygoteInit.forkSystemServer() 中執行 fork() 之後的邏輯處理:

if(pid == 0){
    ......
    return handleSystemServerProcess(parsedArgs);
}

return null;

按正常邏輯思維,這兩處 return 只會執行一次,其實不然。fork() 函數是一次執行,兩次返回。說的更嚴謹一點是 兩個進程對用一個程序的兩次執行。當 pid == 0 時,說明現在處於子進程,當 pid > 0 時,說明處於父進程。在剛 fork 出子進程的時候,父子進程的數據結構基本是一樣的,但是之後就分道揚鑣了,各自執行各自的邏輯。所以上面的代碼段中會有兩次返回值,子進程 (system_server) 中會返回執行 handleSystemServerProcess(parsedArgs) 的結果,父進程 (zygote) 會返回 null。對於兩個不同的返回值又會分別做什麼處理呢?我們回到 ZygoteInit.main() 中:

if (startSystemServer) {
        Runnable r = forkSystemServer(abiList, socketName, zygoteServer);

        // {@code r == null} in the parent (zygote) process, and {@code r != null} in the
        // child (system_server) process.
        // r == null 說明是在 zygote 進程
        // r != null 說明是在 system_server 進程
        if (r != null) {
            r.run(); 
            return;
        }
    }
    
    // 循環等待處理客戶端請求
    caller = zygoteServer.runSelectLoop(abiList);

子進程 system_server 返回的是一個 Runnable,執行 r.run(),然後就直接 return 了。而父進程 zygote 返回的是 null,所以不滿足 if 的判斷條件,繼續往下執行 runSelectLoop 。父子進程就此分道揚鑣,各幹各的事。

下面就來分析 runSelectLoop()handleSystemServerProcess() 這兩個方法,看看 ZygoteSystemServer 這對父子進程繼續做了些什麼工作。

handleSystemServerProcess

到這裏其實已經脫離 Zygote 的範疇了,本準備放在下一篇 SystemServer 源碼解析中再介紹,可是這裏不寫又覺得 Zygote 介紹的不完整,索性就一併說了。

> ZygoteInit.java

private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) {
    // set umask to 0077 so new files and directories will default to owner-only permissions.
    // umask一般是用在你初始創建一個目錄或者文件的時候賦予他們的權限
    Os.umask(S_IRWXG | S_IRWXO);

    // 設置當前進程名爲 "system_server"
    if (parsedArgs.niceName != null) { 
        Process.setArgV0(parsedArgs.niceName);
    }

    final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
    if (systemServerClasspath != null) {
        // dex 優化操作
        performSystemServerDexOpt(systemServerClasspath);
        // Capturing profiles is only supported for debug or eng builds since selinux normally
        // prevents it.
        boolean profileSystemServer = SystemProperties.getBoolean(
                "dalvik.vm.profilesystemserver", false);
        if (profileSystemServer && (Build.IS_USERDEBUG || Build.IS_ENG)) {
            try {
                prepareSystemServerProfile(systemServerClasspath);
            } catch (Exception e) {
                Log.wtf(TAG, "Failed to set up system server profile", e);
            }
        }
    }

    if (parsedArgs.invokeWith != null) { // invokeWith 一般爲空
        String[] args = parsedArgs.remainingArgs;
        // If we have a non-null system server class path, we'll have to duplicate the
        // existing arguments and append the classpath to it. ART will handle the classpath
        // correctly when we exec a new process.
        if (systemServerClasspath != null) {
            String[] amendedArgs = new String[args.length + 2];
            amendedArgs[0] = "-cp";
            amendedArgs[1] = systemServerClasspath;
            System.arraycopy(args, 0, amendedArgs, 2, args.length);
            args = amendedArgs;
        }

        WrapperInit.execApplication(parsedArgs.invokeWith,
                parsedArgs.niceName, parsedArgs.targetSdkVersion,
                VMRuntime.getCurrentInstructionSet(), null, args);

        throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
    } else {
        ClassLoader cl = null;
        if (systemServerClasspath != null) {
            // 創建類加載器,並賦給當前線程
            cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);
                
            Thread.currentThread().setContextClassLoader(cl);
        }

        /*
         * Pass the remaining arguments to SystemServer.
         */
        return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
    }

    /* should never reach here */
}

設置進程名爲 system_server,執行 dex 優化,給當前線程設置類加載器,最後調用 ZygoteInit.zygoteInit() 繼續處理剩餘參數。

public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
    ......
    // Redirect System.out and System.err to the Android log.
    // 重定向 System.out 和 System.err 到 Android log
    RuntimeInit.redirectLogStreams();

    RuntimeInit.commonInit(); // 一些初始化工作
    ZygoteInit.nativeZygoteInit(); // native 層初始化
    return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader); // 調用入口函數
}

重定向 Log,進行一些初始化工作。這部分不細說了,點擊文章開頭給出的源碼鏈接,大部分都做了註釋。最後調用 RuntimeInit.applicationInit() ,繼續追進去看看。

> RuntimeInit.java

protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
        ClassLoader classLoader) {
        
    ......
    final Arguments args = new Arguments(argv); // 解析參數

    ......
    // 尋找 startClass 的 main() 方法。這裏的 startClass 是 com.android.server.SystemServer
    return findStaticMain(args.startClass, args.startArgs, classLoader);
}

這裏的 startClass 參數是 com.android.server.SystemServerfindStaticMain() 方法看名字就能知道它的作用是找到 main() 函數,這裏是要找到 com.android.server.SystemServer 類的 main() 方法。

protected static Runnable findStaticMain(String className, String[] argv,
        ClassLoader classLoader) {
    Class<?> cl;

    try {
        cl = Class.forName(className, true, classLoader);
    } catch (ClassNotFoundException ex) {
        throw new RuntimeException(
                "Missing class when invoking static main " + className,
                ex);
    }

    Method m;
    try {
        // 尋找 main() 方法
        m = cl.getMethod("main", new Class[] { String[].class });
    } catch (NoSuchMethodException ex) {
        throw new RuntimeException(
                "Missing static main on " + className, ex);
    } catch (SecurityException ex) {
        throw new RuntimeException(
                "Problem getting static main on " + className, ex);
    }

    int modifiers = m.getModifiers();
    if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
        throw new RuntimeException(
                "Main method is not public and static on " + className);
    }

    /*
     * 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.
     * 返回一個 Runnable,在 Zygote 的 main() 方法中執行器 run() 方法
     * 之前的版本是拋出一個異常,在 main() 方法中捕獲
     */
    return new MethodAndArgsCaller(m, argv);
}

找到 main() 方法並構建一個 Runnable 對象 MethodAndArgsCaller 。這裏返回的 Runnable 對象會在哪裏執行呢?又要回到文章開頭的 ZygoteInit.main() 函數了,在 forkSystemServer() 之後,子進程執行 handleSystemServerProcess() 並返回一個 Runnable 對象,在 ZygoteInit.main() 中會執行其 run() 方法。

再來看看 MethodAndArgsCallerrun() 方法吧!

static class MethodAndArgsCaller implements Runnable {
    /** method to call */
    private final Method mMethod;

    /** argument array */
    private final String[] mArgs;

    public MethodAndArgsCaller(Method method, String[] args) {
        mMethod = method;
        mArgs = args;
    }

    public void run() {
        try {
            mMethod.invoke(null, new Object[] { mArgs });
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex);
        } catch (InvocationTargetException ex) {
            Throwable cause = ex.getCause();
            if (cause instanceof RuntimeException) {
                throw (RuntimeException) cause;
            } else if (cause instanceof Error) {
                throw (Error) cause;
            }
            throw new RuntimeException(ex);
        }
    }
}

就一件事,執行參數中的 method。這裏的 method 就是 com.android.server.SystemServermain() 方法。到這裏,SystemServer 就要正式工作了。

其實在老版本的 Android 源碼中,並不是通過這種方法執行 SystemServer.main() 的。老版本的 MethodAndArgsCallerException 的子類,在這裏會直接拋出異常,然後在 ZygoteInit.main() 方法中進行捕獲,捕獲之後執行其 run() 方法。

SystemServer 的具體分析就放到下篇文章吧,本篇的主角還是 Zygote

看到這裏,Zygote 已經完成了一件人生大事,孵化出了 SystemServer 進程。但是作爲 “女媧” ,造人的任務還是停不下來,任何一個應用進程的創建還是離不開它的。ZygoteServer.runSlectLoop() 給它搭好了和客戶端之前的橋樑。

runSelectLoop

> ZygoteServer.java

Runnable runSelectLoop(String abiList) {
    ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
    ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();

    // mServerSocket 是之前在 Zygote 中創建的
    fds.add(mServerSocket.getFileDescriptor());
    peers.add(null);

    while (true) {
        StructPollfd[] pollFds = new StructPollfd[fds.size()];
        for (int i = 0; i < pollFds.length; ++i) {
            pollFds[i] = new StructPollfd();
            pollFds[i].fd = fds.get(i);
            pollFds[i].events = (short) POLLIN;
        }
        try {
            // 有事件來時往下執行,沒有時就阻塞
            Os.poll(pollFds, -1);
        } catch (ErrnoException ex) {
            throw new RuntimeException("poll failed", ex);
        }
        for (int i = pollFds.length - 1; i >= 0; --i) {
            if ((pollFds[i].revents & POLLIN) == 0) {
                continue;
            }

            if (i == 0) { // 有新客戶端連接
                ZygoteConnection newPeer = acceptCommandPeer(abiList);
                peers.add(newPeer);
                fds.add(newPeer.getFileDesciptor());
            } else { // 處理客戶端請求
                try {
                    ZygoteConnection connection = peers.get(i);
                    final Runnable command = connection.processOneCommand(this);

                    ......
                } catch (Exception e) {
                   ......
            }
        }
    }
}

mServerSocketZygoteInit.main() 中一開始就建立的服務端 socket,用於處理客戶端請求。一看到 while(true) 就肯定會有阻塞操作。Os.poll() 在有事件來時往下執行,否則就阻塞。當有客戶端請求過來時,調用 ZygoteConnection.processOneCommand() 方法來處理。

processOneCommand() 源碼很長,這裏就貼一下關鍵部分:

......
pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
        parsedArgs.runtimeFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
        parsedArgs.niceName, fdsToClose, fdsToIgnore, parsedArgs.startChildZygote,
        parsedArgs.instructionSet, parsedArgs.appDataDir);

try {
    if (pid == 0) {
        // in child 進入子進程
        zygoteServer.setForkChild();

        zygoteServer.closeServerSocket();
        IoUtils.closeQuietly(serverPipeFd);
        serverPipeFd = null;

        return handleChildProc(parsedArgs, descriptors, childPipeFd,
                parsedArgs.startChildZygote);
    } else {
        // In the parent. A pid < 0 indicates a failure and will be handled in
        // handleParentProc.
        IoUtils.closeQuietly(childPipeFd);
        childPipeFd = null;
        handleParentProc(pid, descriptors, serverPipeFd);
        return null;
    }
} finally {
            IoUtils.closeQuietly(childPipeFd);
            IoUtils.closeQuietly(serverPipeFd);
}

乍一看是不是感覺有點眼熟?沒錯,這一塊的邏輯和 forkSystemServer() 很相似,只是這裏 fork 的是普通應用進程,調用的是 forkAndSpecialize() 方法。中間的代碼調用就不在這詳細分析了,最後還是會調用到 findStaticMain() 執行應用進程的對應 main() 方法,感興趣的同學可以到我的源碼項目 android_9.0.0_r45 閱讀相關文件,註釋還是比較多的。

還有一個問題,上面只分析了 Zygote 接收到客戶端請求並響應,那麼這個客戶端可能是誰呢?具體又是如何與 Zygote 通信的呢?關於這個問題,後續文章中肯定會寫到,關注我的 Github 倉庫 android_9.0.0_r45,所有文章都會第一時間同步過去。

總結

來一張時序圖總結全文 :

最後想說說如何閱讀 AOSP 源碼和開源項目源碼。我的看法是,不要上來就拼命死磕,一行一行的非要全部看懂。首先要理清脈絡,能大致的理出來一個時序圖,然後再分層細讀。這個細讀的過程中碰到不懂的知識點就得自己去挖掘,比如文中遇到的 forkSystemServer() 爲什麼會返回兩次?當然,對於實在超出自己知識範疇的內容,也可以選擇性的暫時跳過,日後再戰。最後的最後,來篇技術博客吧!理清,看懂,表達,都會逐步加深你對源碼的瞭解程度,還能分享知識,反饋社區,何樂而不爲呢?

下篇文章會具體說說 SystemServer 進程具體都幹了些什麼。

文章首發微信公衆號: 秉心說 , 專注 Java 、 Android 原創知識分享,LeetCode 題解。

更多最新原創文章,掃碼關注我吧!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章