zygote進程啓動

1.init.cpp —> main()

main()方法主要完成一下 6 件事:

  • klog_init() 將log寫入到/dev/kmsg中
  • process_kernel_cmdline()解析內核啓動參數
  • signal_handler_init()函數設置了信號處理函數
  • property_load_boot_defaults()函數導入了默認環境變量
  • property_init()和start_property_service()初始化和啓動屬性服務
  • init_parse_cinfig_file(“init.rc”)解析配置文件同時進入循環調用execute_one_command()函數啓動子進程

通過對init.rc文件的解析最終會調用linux系統的fork()函數創建處一個子進程,同時通過execve()函數啓動進程,最終進入到進程定義的main()方法中。

注意回頭看一下是怎麼調用到main()方法的

2.zygote進程的啓動

在zygote進程對應的文件是app_main.cpp文件,在app_main.cpp文件的main()方法中先解析了init.rc中配置的參數並根據配置的參數設置zygote的狀態。
在狀態設置階段主要做了:

  • 設置進程名稱爲zygote
  • 通過startSystemServer = true標示啓動的是systemServer
  • 調用runtime.start()方法

然後調用runtime.start()方法。runtime的類型是由AndroidRuntime派生類AppRunTime,start()方法定義在AndroidRunTime類中。在啓動zygote進程是start()方法接受的第一參數是com.android.internal.os.ZygoteInit,這個參數很重要。下面看一下AndroidRuntime——>start()方法的實現:

void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
{
    -----------------------------
    
    /* start the virtual machine */
    JniInvocation jni_invocation;
    jni_invocation.Init(NULL);
    JNIEnv* env;
    //啓動虛擬機
    if (startVm(&mJavaVM, &env, zygote) != 0) {
        return;
    }
    onVmCreated(env);

    /*
     * Register android functions.
     * 註冊JNI函數
     */
    if (startReg(env) < 0) {
        ALOGE("Unable to register all android natives\n");
        return;
    }

    /*
     * We want to call main() with a String array with arguments in it.
     * At present we have two arguments, the class name and an option string.
     * Create an array to hold them.
     */
    jclass stringClass;
    jobjectArray strArray;
    jstring classNameStr;

    stringClass = env->FindClass("java/lang/String");
    assert(stringClass != NULL);
    strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
    assert(strArray != NULL);
    classNameStr = env->NewStringUTF(className);
    assert(classNameStr != NULL);
    env->SetObjectArrayElement(strArray, 0, classNameStr);

    for (size_t i = 0; i < options.size(); ++i) {
        jstring optionsStr = env->NewStringUTF(options.itemAt(i).string());
        assert(optionsStr != NULL);
        env->SetObjectArrayElement(strArray, i + 1, optionsStr);
    }

    /*
     * Start VM.  This thread becomes the main thread of the VM, and will
     * not return until the VM exits.
     */
    char* slashClassName = toSlashClassName(className);
    jclass startClass = env->FindClass(slashClassName);
    if (startClass == NULL) {
        ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
        /* keep going */
    } else {
        //調用該類的main()方法
        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
            "([Ljava/lang/String;)V");
        if (startMeth == NULL) {
            ALOGE("JavaVM unable to find main() in '%s'\n", className);
            /* keep going */
        } else {
        
            env->CallStaticVoidMethod(startClass, startMeth, strArray);
            
            ----------------------
}

AndroidRuntime主要做了三件事兒:

  • 調用startVM()函數啓動虛擬機
  • 調用startReg()函數註冊jni方法
  • 通過調用的方法調用com.android.internal.os.ZygoteInit類main()方法。

startVM()方法多了大量的命令參數拼接最後通過JNI_CreateJavaVM()方法創建虛擬機。

startReg()方法註冊JNI方法,Android中java和Native層的交互需要通過JNI機制來完成,並且Android中大量使用JNI函數。

int AndroidRuntime::startReg(JNIEnv* env)
{
        ------------------------
    //註冊jni方法, gRegJNI是個數組,其中定義了要使用的JNI的方法
    if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
        env->PopLocalFrame(NULL);
        return -1;
    }
    env->PopLocalFrame(NULL);
    return 0;
}

static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
{
    for (size_t i = 0; i < count; i++) {
        //循環便利調用數組中的元素的mProc()方法完成方法的註冊
        if (array[i].mProc(env) < 0) {
#ifndef NDEBUG
            ALOGD("----------!!! %s failed to load\n", array[i].mName);
#endif
            return -1;
        }
    }
    return 0;
}

AndroidRuntime.start()的第一個參數是ZygoteInit類的文件路徑,所有最終會調用到ZygoteInit類的main()方法。終於到java中了

    public static void main(String argv[]) {
        try {
            RuntimeInit.enableDdms();
            // Start profiling the zygote initialization.
            SamplingProfilerIntegration.start();

            boolean startSystemServer = false;
            String socketName = "zygote";
            String abiList = null;
            for (int i = 1; i < argv.length; i++) {
                if ("start-system-server".equals(argv[i])) {
                    startSystemServer = 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.創建Zygote進程的socket接口
            registerZygoteSocket(socketName);
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
                SystemClock.uptimeMillis());
            //2.預加載類和資源
            preload();
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
                SystemClock.uptimeMillis());

            // Finish profiling the zygote initialization.
            SamplingProfilerIntegration.writeZygoteSnapshot();

            // Do an initial gc to clean up after startup
            //做一個初始化後的GC操作
            gcAndFinalize();

            // Disable tracing so that forked processes do not inherit stale tracing tags from
            // Zygote.
            Trace.setTracingEnabled(false);
            //3.啓動系統服務(SystemServer)
            if (startSystemServer) {
                startSystemServer(abiList, socketName);
            }

            Log.i(TAG, "Accepting command socket connections");
            //4.無限循環接受Socket接口的數據,等待AMS請求創建應用程序進程
            runSelectLoop(abiList);

            closeServerSocket();
        } catch (MethodAndArgsCaller caller) {
            //5.當啓動一個新進程的時候會拋出異常,然後執行caller.run()方法
            caller.run();
        } catch (RuntimeException ex) {
            Log.e(TAG, "Zygote died with exception", ex);
            closeServerSocket();
            throw ex;
        }
    }

ZygoteInit的main()方法主要做了5件事兒:

  • 通過registerZygoteSocket()函數創建了一個Zygote的socket接口用來和AMS進行通信。
  • 調用preload()預加載類和資源
  • 調用startSystemServer()方法啓動systemServer
  • 調用runSelectLoop()方法監聽socket接口
  • 通過捕獲一個MethodAndArgsCaller異常並調用捕獲的異常的run()方法。
        private static void registerZygoteSocket(String socketName) {
        if (sServerSocket == null) {
            int fileDesc;
            final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
            try {
                String env = System.getenv(fullSocketName);
                fileDesc = Integer.parseInt(env);
            } catch (RuntimeException ex) {
                throw new RuntimeException(fullSocketName + " unset or invalid", ex);
            }
            //通過文件描述符創建socket,這裏的文件描述符值得文件是 dev/socket/zygote。 這個地址是在init.rc文件中配置的
            try {
                FileDescriptor fd = new FileDescriptor();
                fd.setInt$(fileDesc);
                sServerSocket = new LocalServerSocket(fd);
            } catch (IOException ex) {
                throw new RuntimeException(
                        "Error binding to local socket '" + fileDesc + "'", ex);
            }
        }
    }

zygote的socket接口主要是通過/dev/socket/zygote文件的文件操作符進行通信。

preload()方法主要預先加載了framework中通用的類和資源(core/res/res/values/arrays.xml)、openGL、本地共享庫、webView的一些資源。
預先加載主要是爲了在啓動新應用程序時不用重複加載這些資源從而加快啓動速度。

private static void runSelectLoop(String abiList) throws MethodAndArgsCaller {
        ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
        ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();

        fds.add(sServerSocket.getFileDescriptor());
        peers.add(null);

        while (true) {
                if (i == 0) {
                    ZygoteConnection newPeer = acceptCommandPeer(abiList);
                    peers.add(newPeer);
                    fds.add(newPeer.getFileDesciptor());
                } else {
                    //調用zygoteConnection類的RunOnce()方法
                    boolean done = peers.get(i).runOnce();
                    if (done) {
                        peers.remove(i);
                        fds.remove(i);
                    }
                }
            }
        }
    }

在runSelectLoop()方法中通過調用ZygoteConnection.runOnce()方法來創建子進程。

我們知道Zygote進程啓動後啓動的第一個系統進程是SystemServer,SysetmServer用來管理Android系統中像AMS、WMS、PMS等重要的系統服務。

    private static boolean startSystemServer(String abiList, String socketName)
       
       -----------------參數處理--------------------

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

            /* Request to fork the system server process */
            //fork處一個SystemServer的進程,在Zygote.forkSystemServer()中調用了JNI方法nativeForkSystemServer()方法fork處一個進程。
            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);
            }
            //SystemServer進程創建成功之後做些處理
            handleSystemServerProcess(parsedArgs);
        }

        return true;
    }

在ZygoteInit–>startSystemServer()中通過ZygoteConnection對參數進行處理,然後通過Zygote.forkSystemServer()方法創建出一個SysetmServer進程。當返回的進程ID(Pid)等於 0時通過HandlerSystemServerprocess()來繼續處理。

private static void handleSystemServerProcess(
            ZygoteConnection.Arguments parsedArgs)
            throws ZygoteInit.MethodAndArgsCaller {
        //關閉socket通信
        closeServerSocket();

        // set umask to 0077 so new files and directories will default to owner-only permissions.
        //設置文件權限
        Os.umask(S_IRWXG | S_IRWXO);


        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);
        }

        /* should never reach here */
    }

在handdleSystemServerProcess()方法中首先關閉Zygote進程的socket接口,由於SystemServer有zygote進程fork而來且SystemServer不需要使用socket通信所以調用closeServerSocket()方法關閉socket接口。然後調用RuntimeInit.zygoteInit()方法:

/Volumes/android_source/source/aosp/frameworks/base/core/java/com/android/internal/os/RuntimeInit.java

    public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
            throws ZygoteInit.MethodAndArgsCaller {
        /**
         * 一些通用的應用程序初始化;如:默認異常處理、時區配置、LogManager、Http UserAgent等設置
         */
        commonInit();
        //native Binder驅動程序初始化
        nativeZygoteInit();
        //重要
        applicationInit(targetSdkVersion, argv, classLoader);
    }

在RuntimeInit–>zygoteInit()方法中通過CommonInit()方法主要做了一些應用的初始化操作(如:java的默認異常處理,時區HttpUerAgent的設置)。在nativeZygoteInit()方法中在nativie中啓動了Binder的驅動程序。最後調用applicationInit() 方法調用到SystemServer的main()方法中。

/Volumes/android_source/source/aosp/frameworks/base/core/jni/AndroidRuntime.cpp

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

---------------------------------------------
/Volumes/android_source/source/aosp/frameworks/base/cmds/app_process/app_main.cpp的內嵌類AppRuntime的onZygoteInit()方法

virtual void onZygoteInit()
    {
        sp<ProcessState> proc = ProcessState::self();
        ALOGV("App process: starting thread pool.\n");
        proc->startThreadPool();
    }

在RuntimeInit的natvieZygoteInit()方法中調用了AppRuntime的onZygoteInit()方法其中創建了一個sp對象並啓動了一個線程池。這部分涉及到Binder的啓動和通信機制在此不深究。

在RuntimeInit的zygoteInit()方法中在調用natvieZygoteInit()方法啓動Binder機制的驅動程序後還調用了applicationInit()方法;

/Volumes/android_source/source/aosp/frameworks/base/core/java/com/android/internal/os/RuntimeInit.java

    private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
            throws ZygoteInit.MethodAndArgsCaller {
            
                --------------------
                
        // Remaining arguments are passed to the start class's static main
        invokeStaticMain(args.startClass, args.startArgs, classLoader);
    }
    
    ---------------------------------------
    private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
            throws ZygoteInit.MethodAndArgsCaller {
        Class<?> cl;

        try {
        //這裏的className指的是SystemServer類的文件目錄
            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);
        }

        /*
         * 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.
         *在這裏拋出一個MethodAndArgsCaller異常,這個異常將在ZygoteInit的main()方法中捕獲。拋出異常的目的是清除當前棧中的棧幀
         */
        throw new ZygoteInit.MethodAndArgsCaller(m, argv);
    }

在RuntimeInit的applicationInit()方法中直接調用了他的invokeStaticMain()方法。在invokeStaticMain()方法中通過放射的技術查找了SystemServer的main()方法並拋出了一個MethodAndArgsCaller的異常,此異常將在ZygoteInit的main()方法中被捕獲,並在捕獲後調用他的run方法。


/Volumes/android_source/source/aosp/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java的內部類

        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 {
            //反射調用SystemServer的main()方法
                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);
            }
        }
    }
}

MethodAndArgsCaller的異常將在ZygoteInit的main()方法中捕獲並在捕獲後調用Caller的run()方法。通過上邊的run()方法我們可以發現其中通過反射調用了SystemServer的main方法。

這基本就是Zygote進程和SystemServer進程啓動的全過程

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