Android4.0.3源码分析——开机流程之Zygote


Zygote


Zygote启动是从

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

中的main()函数开始的。


启动JavaVM:

main()函数中有启动VM

if(zygote) {

runtime.start("com.android.internal.os.ZygoteInit",

startSystemServer? "start-system-server" : "");

runtimeAppRuntime的对象,同样在main()中:

AppRuntimeruntime;

appRuntimeAndroidRuntime的子类,它的定义就在app_main.cpp中:

classAppRuntime : public AndroidRuntime

所以,这里的runtime.start()其实调用的是AndroidRuntime::start().


下面对AndroidRuntime::start()进行分析:

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

start()函数中启动VM

    /* start the virtual machine */
    JNIEnv* env;
    if (startVm(&mJavaVM, &env) != 0) {
        return;
    }
    onVmCreated(env);
其中startVm()函数和onVmCreated()函数也都在AndroidRuntime.cpp中。
startVm()函数中通过有如下代码调用JNI创建JavaVM:
/*
* Initialize the VM.
*
* The JavaVM* is essentially per-process, and the JNIEnv* is per-thread.
* If this call succeeds, the VM is ready, and we can start issuing
* JNI calls.
*/
if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) < 0) {
LOGE("JNI_CreateJavaVM failed\n");
goto bail;
}
onVmCreated()函数其实是个空函数。
void AndroidRuntime::onVmCreated(JNIEnv* env)
{
// If AndroidRuntime had anything to do here, we'd have done it in 'start'.
}
同时在start()函数中调用startReg()函数注册JNI接口:
    if (startReg(env) < 0) {
        LOGE("Unable to register all android natives\n");
        return;
    }

然后在start()函数中:

env->CallStaticVoidMethod(startClass,startMeth, strArray);

调用com.android.internal.os.ZygoteInit中的main()函数。


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

main()调用了:

registerZygoteSocket();//来注册SocketListen端口,用来接受请求。

preload();

startSystemServer();//启动SystemServer

其中preload()函数定义如下:

static void preload() {
    preloadClasses();
    preloadResources();
}

它主要进行预加载类和资源,以加快启动速度。preloadclass列表保存在/frameworks/base/preloaded-classes文件中。

经过以上步骤,Zygote就建立完成。


原文地址:https://www.cnblogs.com/ainima/p/6332020.html