SystemServer

版權(quán)說明:本文為 開開向前沖 原創(chuàng)文章,轉(zhuǎn)載請(qǐng)注明出處;
注:限于作者水平有限,文中有不對(duì)的地方還請(qǐng)指教

如果你細(xì)心的話,前文Zygote-Java文章中有一個(gè)核心調(diào)用沒講——caller.run();
本章將會(huì)描述該核心調(diào)用在什么時(shí)候被調(diào)用;

SystemServer是從Zygote的嫡子,下面從Zygote開始看看SystemServer的誕生;

startSystemServer
/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java  

    /**
     * Prepare the arguments and fork for the system server process.
     */
    private static boolean startSystemServer(String abiList, String socketName)
            throws MethodAndArgsCaller, RuntimeException {
        ......
        /* Hardcoded command line to start the system server */
        String args[] = {
            "--setuid=1000",//設(shè)置UID,GID
            "--setgid=1000",
            "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,
                                    1018,1021,1032,3001,3002,3003,3006,3007",
            "--capabilities=" + capabilities + "," + capabilities,
            "--nice-name=system_server",//進(jìn)程名
            "--runtime-args",
            "com.android.server.SystemServer",//啟動(dòng)的類名
        };
        ZygoteConnection.Arguments parsedArgs = null;
        int pid;
        try {
            parsedArgs = new ZygoteConnection.Arguments(args);//參數(shù)轉(zhuǎn)換
            ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
            ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

            /* Request to fork the system server process */
            pid = Zygote.forkSystemServer( //Zygote fork出子進(jìn)程,這里會(huì)調(diào)到JNI中
            //com_android_internal_os_Zygote.cpp中的ForkAndSpecializeCommon,最終調(diào)用fork()創(chuàng)建SystemServer進(jìn)程
                    parsedArgs.gids,
                    parsedArgs.debugFlags,
                    null,
                    parsedArgs.permittedCapabilities,
                    parsedArgs.effectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }
        /* For child process */
        if (pid == 0) {//pid==0 代表新的進(jìn)程
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }
            handleSystemServerProcess(parsedArgs);//處理systemserver
        }
        return true;
    }

step1:forkSystemServer(Zygote.java)——>step2:nativeForkSystemServer(Zygote.java) ——> (step3)(JNI)com_android_internal_os_Zygote_nativeForkSystemServer(com_android_internal_os_Zygote.cpp)
——>(step4)ForkAndSpecializeCommon——>(step5)fork();
從Java世界到Native的fork();SystemServer進(jìn)程被創(chuàng)建出來了;

handleSystemServerProcess
/**
     * Finish remaining work for the newly forked system server process.
     */
    private static void handleSystemServerProcess(
            ZygoteConnection.Arguments parsedArgs)
            throws ZygoteInit.MethodAndArgsCaller {

        closeServerSocket();//關(guān)閉父進(jìn)程創(chuàng)建的socket

        // 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);//設(shè)置進(jìn)程名
        }
        final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");//adb shell進(jìn)終端,
                                                       //echo $SYSTEMSERVERCLASSPATH,有值輸出,不為空
        if (systemServerClasspath != null) {
            performSystemServerDexOpt(systemServerClasspath);//預(yù)優(yōu)化systemServerClasspath
        }
        if (parsedArgs.invokeWith != null) {
            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(parsedArgs.remainingArgs, 0, amendedArgs, 2, parsedArgs.remainingArgs.length);
            }
            WrapperInit.execApplication(parsedArgs.invokeWith,
                    parsedArgs.niceName, parsedArgs.targetSdkVersion,
                    VMRuntime.getCurrentInstructionSet(), null, args);
        } else {
            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);
            //最終會(huì)調(diào)用這里
        }
        /* should never reach here */
    }

Zygote進(jìn)程創(chuàng)建的子進(jìn)程會(huì)繼承Zygote進(jìn)程中創(chuàng)建的Socket文件描述符,再加上子進(jìn)程又不會(huì)使用,所以這里就調(diào)用closeServerSocket函數(shù)來關(guān)閉。這里最終會(huì)調(diào)用
RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
Zygote-Java中講到Zygote進(jìn)程監(jiān)聽?wèi)?yīng)用程序啟動(dòng)時(shí)也會(huì)執(zhí)行RuntimeInit.zygoteInit步驟:

/frameworks/base/core/java/com/android/internal/os/RuntimeInit.java

    public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
            throws ZygoteInit.MethodAndArgsCaller {
        if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from zygote");

        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "RuntimeInit");
        redirectLogStreams();//重定向System.out和System.err到Android Log
        commonInit();//初始化UA,時(shí)區(qū)等
        nativeZygoteInit();//native初始化,在/frameworks/base/core/jni/AndroidRuntime.cpp中實(shí)現(xiàn)
        applicationInit(targetSdkVersion, argv, classLoader);
    }

/frameworks/base/core/jni/AndroidRuntime.cpp


static AndroidRuntime* gCurRuntime = NULL;//靜態(tài)變量
AndroidRuntime::AndroidRuntime(char* argBlockStart, const size_t argBlockLength)
......
{  
      ......
      gCurRuntime = this;
}
static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
    gCurRuntime->onZygoteInit();
}
/*
 * JNI registration.
 */
static JNINativeMethod gMethods[] = {
    { "nativeFinishInit", "()V",
        (void*) com_android_internal_os_RuntimeInit_nativeFinishInit },
    { "nativeZygoteInit", "()V",
        (void*) com_android_internal_os_RuntimeInit_nativeZygoteInit },
    { "nativeSetExitWithoutCleanup", "(Z)V",
        (void*) com_android_internal_os_RuntimeInit_nativeSetExitWithoutCleanup },
};

gCurRuntime 在AndroidRuntime的構(gòu)造函數(shù)中被初始化為this指針,而AndroidRuntime在Zygote進(jìn)程的app_main.cpp中被AppRuntime繼承并構(gòu)造,所以此時(shí)的gCurRuntime指向AppRuntime ,所以nativeZygoteInit最終會(huì)調(diào)調(diào)到app_main.cpp中AppRuntime的onZygoteInit方法。

/frameworks/base/cmds/app_process/app_main.cpp

    virtual void onZygoteInit()
    {
        sp<ProcessState> proc = ProcessState::self();//單列獲取SystemServer的進(jìn)程對(duì)象
        ALOGV("App process: starting thread pool.\n");
        proc->startThreadPool();//開啟Binder線程池
    }

這里創(chuàng)建了ProcessState對(duì)象,開啟線程池用于Binder通信,標(biāo)志這SystemServer具備了Binder通信的能力;因?yàn)楹罄m(xù)會(huì)提到的AMS,PMS,PowerMS都是運(yùn)行與SystemServer,ProcessState對(duì)象是單例對(duì)象,每個(gè)進(jìn)程僅有一個(gè),所以在這里初始化Binder,后續(xù)AMS,PMS等服務(wù)線程就可以直接使用。

再來看看/frameworks/base/core/java/com/android/internal/os/RuntimeInit.java 的applicationInit

applicationInit
private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
            throws ZygoteInit.MethodAndArgsCaller {
        // If the application calls System.exit(), terminate the process
        // immediately without running any shutdown hooks.  It is not possible to
        // shutdown an Android application gracefully.  Among other things, the
        // Android runtime shutdown hooks close the Binder driver, which can cause
        // leftover running threads to crash before the process actually exits.
        nativeSetExitWithoutCleanup(true);

        // We want to be fairly aggressive about heap utilization, to avoid
        // holding on to a lot of memory that isn't needed.
        VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
        VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);//設(shè)置SDK版本

        final Arguments args;
        try {
            args = new Arguments(argv);//構(gòu)造參數(shù)
        } catch (IllegalArgumentException ex) {
            Slog.e(TAG, ex.getMessage());
            // let the process exit
            return;
        }

        // The end of of the RuntimeInit event (see #zygoteInit).
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

        // Remaining arguments are passed to the start class's static main
        invokeStaticMain(args.startClass, args.startArgs, classLoader);//核心,args.startClass就
                                                  //是ZygoteInit.java中startSystemServer方法傳遞過來的參數(shù)
    }
invokeStaticMain
/**
     * Invokes a static "main(argv[]) method on class "className".
     * Converts various failing exceptions into RuntimeExceptions, with
     * the assumption that they will then cause the VM instance to exit.
     *
     * @param className Fully-qualified class name
     * @param argv Argument vector for main()
     * @param classLoader the classLoader to load {@className} with
     */
    private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
            throws ZygoteInit.MethodAndArgsCaller {
        Class<?> cl;

        try {
            cl = Class.forName(className, true, classLoader);//利用反射獲取得到SystemServer
        } 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 });//獲取SystemServer的main方法
        } 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))) {
        //判斷方法修飾符,必須是public和static
            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.
         */
        throw new ZygoteInit.MethodAndArgsCaller(m, argv);//核心就是在此了,故意拋出這個(gè)異常,
                                                          //需要注意這個(gè)異常的參數(shù)
    }

這里Method m=main(),argv從handleSystemServerProcess方法的parsedArgs.remainingArgs中傳遞過來;

這里拋出的異常在什么位置處理呢???這里源碼注釋也有講到,向上尋找,發(fā)現(xiàn)在調(diào)用startSystemServer的ZygoteInit的main方法中:

/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

main()——>>>>>>>>>
try {
  ...
  if (startSystemServer) {
       startSystemServer(abiList, socketName);//啟動(dòng)SystemServer
  }
  ...
} catch(MethodAndArgsCaller caller) {
       caller.run();          //核心調(diào)用,故意拋出異常來處理
}

沒錯(cuò),這就是文章開頭說Zygote-Java章節(jié)中沒有提到的—— caller.run()

caller——>MethodAndArgsCaller——>ZygoteInit.java
    /**
     * 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 {
        /** 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 });//利用反射調(diào)用SystemServer的main方法
            } 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);
            }
        }
    }

這里mMethod就是前面前面的Method m=main(),mArgs從handleSystemServerProcess方法的parsedArgs.remainingArgs中傳遞過來;利用反射調(diào)用SystemServer 類的main方法;下面我們直接到SystemServer.java 的main方法:

/frameworks/base/services/java/com/android/server/SystemServer.java

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

    public SystemServer() {
        // Check for factory test mode.
        mFactoryTestMode = FactoryTest.getMode();
    }

    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);
        }
        // If the system has "persist.sys.language" and friends set, replace them with
        // "persist.sys.locale". Note that the default locale at this point is calculated
        // using the "-Duser.locale" command line flag. That flag is usually populated by
        // AndroidRuntime using the same set of system properties, but only the system_server
        // and system apps are allowed to set them.
        //
        // NOTE: Most changes made here will need an equivalent change to
        // core/jni/AndroidRuntime.cpp
        if (!SystemProperties.get("persist.sys.language").isEmpty()) {
            final String languageTag = Locale.getDefault().toLanguageTag();
            SystemProperties.set("persist.sys.locale", languageTag);
            SystemProperties.set("persist.sys.language", "");
            SystemProperties.set("persist.sys.country", "");
            SystemProperties.set("persist.sys.localevar", "");
        }

        // 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. http://b/11463182
        SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
        //重新設(shè)置虛擬機(jī)

        // 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();//準(zhǔn)備Main Looper

        // Initialize native services.
        System.loadLibrary("android_servers");

        // Check whether we failed to shut down last time we tried.
        // This call may not return.
        performPendingShutdown();

        // Initialize the system context.
        createSystemContext();//創(chuàng)建System Context;

        // Create the system service manager.
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

        // Start services.
        try {
            startBootstrapServices();//核心:啟動(dòng)引導(dǎo)核心服務(wù)
            startCoreServices();     //核心:啟動(dòng)核心服務(wù)
            startOtherServices();    //核心:啟動(dòng)其他服務(wù)
        /**
        * 很多系統(tǒng)服務(wù)都是從這里啟動(dòng),什么AMS,PMS等等,都是從這里啟動(dòng);
        * 所以這些服務(wù)都是運(yùn)行在SystemServer進(jìn)程,只是不同的服務(wù)運(yùn)行于不同的線程;
        */
        } 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();//進(jìn)入無限循環(huán)
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

到這里SystemServer就啟動(dòng)完成,進(jìn)入無限循環(huán);對(duì)于系統(tǒng)服務(wù)的啟動(dòng)這里暫時(shí)不講,后續(xù)講到各個(gè)服務(wù)的時(shí)候會(huì)說道;這里我們知道Android 系統(tǒng)服務(wù)是如何啟動(dòng):

  1. Linux 啟動(dòng)Init進(jìn)程,Init進(jìn)程通過解析init.rc腳本創(chuàng)建Zygote進(jìn)程和相關(guān)服務(wù)端Socket;
  2. Zygote進(jìn)程負(fù)責(zé)啟動(dòng)SystemServer進(jìn)程和循環(huán)監(jiān)聽處理AMS啟動(dòng)應(yīng)用進(jìn)程的請(qǐng)求;
  3. SystemServer進(jìn)程啟動(dòng)系統(tǒng)服務(wù),如ActivityManagerService,PackageManagerService等;
  4. 啟動(dòng)Android應(yīng)用程序時(shí),ActivityManagerService會(huì)通過Socket向Zygote進(jìn)程發(fā)送數(shù)據(jù),由Zygote創(chuàng)建新的應(yīng)用進(jìn)程。
最后編輯于
?著作權(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)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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