2025-02-10

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" : "");

而runtime是AppRuntime的對象,同樣在main()中:

AppRuntimeruntime;

而appRuntime是AndroidRuntime的子類,它的定義就在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();//來註冊Socket的Listen端口,用來接受請求。

preload();

startSystemServer();//啟動SystemServer。

其中preload()函數定義如下:

static void preload() {
    preloadClasses();
    preloadResources();
}
它主要進行預加載類和資源,以加快啟動速度。preload的class列表保存在/frameworks/base/preloaded-classes文件中。

經過以上步驟,Zygote就建立完成。

 

作者:snsn1984

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *