Zygote進(jìn)程對(duì)SystemServer進(jìn)程的啟動(dòng)

android源碼學(xué)習(xí)目錄

介紹

什么是SystemServer,簡(jiǎn)單來(lái)說(shuō)SystemServer就是Android系統(tǒng)啟動(dòng)各種Service的入口,同時(shí)也對(duì)各個(gè)service進(jìn)行了管理,其中包括AMS,PMS,WMS.

SystemServer是怎么啟動(dòng)的

上文我們知道,zygote孵化器進(jìn)程在他的main函數(shù)中調(diào)用startSystemServer函數(shù)啟動(dòng)了SystemServer進(jìn)程,通過(guò)對(duì)zygote孵化器的了解,我們能確定,SystemServer是通過(guò)zygote進(jìn)程fock自己來(lái)創(chuàng)建的一個(gè)新的子進(jìn)程。

 */
    //zygote進(jìn)程main函數(shù)調(diào)動(dòng) startSystemServer
    private static boolean startSystemServer(String abiList, String socketName, ZygoteServer zygoteServer)
            throws Zygote.MethodAndArgsCaller, RuntimeException {
        .....

        /* Hardcoded command line to start the system server */
        //這里構(gòu)建了啟動(dòng)SystemServer所需的參數(shù),
        String args[] = {
            "--setuid=1000",
            "--setgid=1000",
            "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1032,3001,3002,3003,3006,3007,3009,3010",
            "--capabilities=" + capabilities + "," + capabilities,
            "--nice-name=system_server",
            "--runtime-args",
            "com.android.server.SystemServer",
        };
        ZygoteConnection.Arguments parsedArgs = null;

        int pid;

        try {
            parsedArgs = new ZygoteConnection.Arguments(args);  //解析參數(shù)為一直德?tīng)栴?lèi)
            ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
            ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

            /* Request to fork the system server process */
              //這個(gè)重要,Zygote進(jìn)程fock自己的內(nèi)存地址,來(lái)創(chuàng)建新的子進(jìn)程
            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 */
        //上面已經(jīng)fock創(chuàng)建了SystemServer進(jìn)程,這里的代碼已經(jīng)運(yùn)行在SystemServer進(jìn)程里了
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }
             //關(guān)閉zygote進(jìn)程原有的socket請(qǐng)求
            zygoteServer.closeServerSocket();、
            //啟動(dòng)systemServer main函數(shù)
            handleSystemServerProcess(parsedArgs);
        }

        return true;
    }

從代碼中我們了解,startSystemServer首先構(gòu)建了啟動(dòng)SystemServer所需的參數(shù),之后Zynote進(jìn)程fock自己的內(nèi)存地址,因?yàn)閦ynote中有socket鏈接,SystemServer不需要所以關(guān)閉,之后在啟動(dòng)。
forkSystemServer用戶(hù)復(fù)制zynote進(jìn)程的內(nèi)存地址,也就是復(fù)制zynote進(jìn)程,后續(xù)的代碼就會(huì)執(zhí)行在這個(gè)這個(gè)新的進(jìn)程里,也就是SystemServer進(jìn)程。
\color{#ea4335}{注意:}forkSystemServer一執(zhí)行,后續(xù)的代碼執(zhí)行就是新的進(jìn)程了,因?yàn)樾逻M(jìn)程復(fù)制了zynote進(jìn)程,所有zynote進(jìn)程之前執(zhí)行的內(nèi)容也是存在的,只是之前的也復(fù)制到了新的進(jìn)程。

    private static void handleSystemServerProcess(
            ZygoteConnection.Arguments parsedArgs)
            throws Zygote.MethodAndArgsCaller {
 

        if (parsedArgs.invokeWith != null) {
            .....

        } else {
            ClassLoader cl = null;
            if (systemServerClasspath != null) {
                //創(chuàng)建path類(lèi)型的類(lèi)加載器
                cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);

                Thread.currentThread().setContextClassLoader(cl);
            }

            /*
             * Pass the remaining arguments to SystemServer.
             */
            //更具參數(shù)啟動(dòng)main函數(shù)
            ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
        }

        /* should never reach here */
    }

handleSystemServerProcess函數(shù)處理了很多參數(shù),我們需要了解的就是

  • 函數(shù)創(chuàng)建了path類(lèi)型類(lèi)加載器設(shè)置到了當(dāng)前線(xiàn)程。
  • zygoteInit函數(shù)啟動(dòng)了該類(lèi)的main函數(shù),參數(shù)中我們了解是 "com.android.server.SystemServer"類(lèi)的main函數(shù)
 public static final void zygoteInit(int targetSdkVersion, String[] argv,
            ClassLoader classLoader) throws Zygote.MethodAndArgsCaller {
        if (RuntimeInit.DEBUG) {
            Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
        }

        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
        RuntimeInit.redirectLogStreams();

        RuntimeInit.commonInit();
        //啟動(dòng)binder線(xiàn)程池
        ZygoteInit.nativeZygoteInit();
        //調(diào)用執(zhí)行main函數(shù)
        RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
    }

這一步也很重要,它里面包含了啟動(dòng)binder線(xiàn)程池,這是systemServer與其他進(jìn)程通信的基礎(chǔ),Binder,

   protected static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
            throws Zygote.MethodAndArgsCaller {
         .....

        // Remaining arguments are passed to the start class's static main
        invokeStaticMain(args.startClass, args.startArgs, classLoader);
    }

applicationInit函數(shù)對(duì)jvm進(jìn)行了一些參數(shù)設(shè)置,invokeStaticMain是最終執(zhí)行的函數(shù),它通過(guò)反射找到SystemServer的main方法,并拋出異常。

    private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
            throws Zygote.MethodAndArgsCaller {
        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 {
            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);
        }
        throw new Zygote.MethodAndArgsCaller(m, argv);
    }

這個(gè)函數(shù)分析了SystemServer類(lèi),并找到了該類(lèi)的main函數(shù),但這里并沒(méi)有進(jìn)行main函數(shù)的執(zhí)行,它爆出了異常 throw new Zygote.MethodAndArgsCaller, new Zygote.MethodAndArgsCaller類(lèi)是在/framework/core/base/java/com/android/internal/os/Zygote類(lèi)里面的,這是個(gè)異常類(lèi),到這里回憶ZynoteInit類(lèi)的main函數(shù)里

  public static void main(String argv[]) {
                ....

            if (startSystemServer) {
                startSystemServer(abiList, socketName, zygoteServer);
            }

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

            zygoteServer.closeServerSocket();
        } catch (Zygote.MethodAndArgsCaller caller) {  //Zygote.MethodAndArgsCaller異常捕獲
            caller.run();
        } catch (Throwable ex) {
            Log.e(TAG, "System zygote died with exception", ex);
            zygoteServer.closeServerSocket();
            throw ex;
        }
    }

zynote主線(xiàn)程進(jìn)行了異常捕獲,但SystemServer是復(fù)制的zynote進(jìn)程,所以zynote的能力和代碼它也有,同樣SystemServer主線(xiàn)程的異常也在這里捕獲,捕獲一樣后執(zhí)行caller.run方法,

public void run() {
            try {
                mMethod.invoke(null, new Object[] { mArgs });  //執(zhí)行方法帶參數(shù)
            } catch (IllegalAccessException ex) {
           .....
        }

invok方法是Java通過(guò)反射執(zhí)行類(lèi)方法,這里我們了解SystemServer拋出異常時(shí)已經(jīng)對(duì)這個(gè)方法進(jìn)行了反射,也就是SystemServer類(lèi)的main方法,也是是說(shuō)這里才是main方法最終開(kāi)始執(zhí)行的代碼。

\color{#ea4335}{注意:}

  1. google為什么采用這種異常捕獲的方式來(lái)反射執(zhí)行main方法,我不太了解,據(jù)說(shuō)是為了利用Java里的異常機(jī)制來(lái)清理新進(jìn)程的運(yùn)行環(huán)境,這里沒(méi)有研究,有研究的希望發(fā)文到專(zhuān)題。
  2. 到這里SystemServer進(jìn)程的準(zhǔn)備已經(jīng)完成了,這時(shí)就正式進(jìn)入SystemServer進(jìn)程的main函數(shù)了。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容