本文基于 AOSP android-10.0.0_r41 版别讲解

前面咱们说到,init 进程会解析 init.rc 文件,履行对应的指令,其中一个重要的任务便是发动 Zygote 进程。接下来咱们就来剖析 Zygote 进程的发动和履行进程。

上一节最终咱们剖析到调用 runtime.start() 发动 ZygoteInit Java 类:

// AppRuntime 的初始化
AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
// 发动 ZygoteInit 类
runtime.start("com.android.internal.os.ZygoteInit", args, zygote);

这儿初始化一个 AppRuntime 目标,然后经过这个目标的 start 办法发动一个 ZygoteInit Java 类。

AppRuntime 直译的话叫做使用运转时,开发时,咱们写好 Java/Kotlin 代码,经过对应的编译器将代码编译为字节码,AppRuntime 的作用便是创建一个能够履行字节码的环境,这个环境主要由两部分内容构成:

  • 一部分担任目标的创建与收回,比如类的加载器,垃圾收回器等
  • 一部分担任程序逻辑的运转,比如即时编译体系,解说器等

咱们先看下 AppRuntime 类的完成:

class AppRuntime : public AndroidRuntime
{
public:
    AppRuntime(char* argBlockStart, const size_t argBlockLength)
        : AndroidRuntime(argBlockStart, argBlockLength)
        , mClass(NULL)
    {
    }
    //......
    // 省掉一些代码
    String8 mClassName;
    Vector<String8> mArgs;
    jclass mClass;
};

先看 AppRuntime 的结构函数,调用父类 AndroidRuntime 结构函数:

// AndroidRuntime 类在一个进程中只有一个实例目标,保存在全局变量 gCurRuntime 中。
static AndroidRuntime* gCurRuntime = NULL;
AndroidRuntime::AndroidRuntime(char* argBlockStart, const size_t argBlockLength) :
        mExitWithoutCleanup(false),
        mArgBlockStart(argBlockStart),
        mArgBlockLength(argBlockLength)
{
    // 初始化 skia 图形体系
    SkGraphics::Init();
    // Pre-allocate enough space to hold a fair number of options.
    mOptions.setCapacity(20);
    // 只能被初始化一次
    assert(gCurRuntime == NULL);        // one per process
    // 全局 static 变量
    gCurRuntime = this;
}

结构函数中主要初始化 skia 图形体系,然后把 AndroidRuntime 保存到全局变量 gCurRuntime 中。

初始化完成后,就会调用 start 函数发动虚拟机:

// 发动 ZygoteInit 类
runtime.start("com.android.internal.os.ZygoteInit", args, zygote);

这个函数比较长,咱们逐步剖析:

//详细完成
void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
{   
    // 打印发动 log
    ALOGD(">>>>>> START %s uid %d <<<<<<n",
            className != NULL ? className : "(unknown)", getuid());

当这个 Log 打印时,标志着 Java 的运转时开始发动,假如 Android 的体系 log 中反复呈现这段内容,而输出 ID都是Zygote,则说明体系或许呈现问题,Zygote进程在不断地重启.

    static const String8 startSystemServer("start-system-server");
    /*
     * 'startSystemServer == true' means runtime is obsolete and not run from
     * init.rc anymore, so we print out the boot start event here.
     */
    for (size_t i = 0; i < options.size(); ++i) {
        if (options[i] == startSystemServer) {
           /* track our progress through the boot sequence */
           const int LOG_BOOT_PROGRESS_START = 3000;
           LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START,  ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
        }
    }

这儿处理参数的反常,关于前期版别的 Runtime,才需要 startSystemServer == true 这样的参数,假如这儿呈现了这样的参数,打印一些 Log 告诉开发人员。

    const char* rootDir = getenv("ANDROID_ROOT");
    if (rootDir == NULL) {
        rootDir = "/system";
        if (!hasDir("/system")) {
            LOG_FATAL("No root directory specified, and /system does not exist.");
            return;
        }
        setenv("ANDROID_ROOT", rootDir, 1);
    }

这儿从环境变量 ANDROID_ROOT 中读取到根目录,假如没有读到,则默认设置为 /system,假如 /system 目录不存在,直接退出。

    const char* runtimeRootDir = getenv("ANDROID_RUNTIME_ROOT");
    if (runtimeRootDir == NULL) {
        LOG_FATAL("No runtime directory specified with ANDROID_RUNTIME_ROOT environment variable.");
        return;
    }
    const char* tzdataRootDir = getenv("ANDROID_TZDATA_ROOT");
    if (tzdataRootDir == NULL) {
        LOG_FATAL("No tz data directory specified with ANDROID_TZDATA_ROOT environment variable.");
        return;
    }

这儿接着读取环境遍历。

    //const char* kernelHack = getenv("LD_ASSUME_KERNEL");
    //ALOGD("Found LD_ASSUME_KERNEL='%s'n", kernelHack);
    /* start the virtual machine */
    JniInvocation jni_invocation;
    jni_invocation.Init(NULL);
    JNIEnv* env;
    if (startVm(&mJavaVM, &env, zygote) != 0) {
        return;
    }

这儿调用 startVm 发动虚拟机。

    onVmCreated(env);

onVmCreated 是一个虚函数,实际上调用的是子类 AppRuntime 中的重载函数:

    virtual void onVmCreated(JNIEnv* env)
    {
        if (mClassName.isEmpty()) {
            return; // Zygote. Nothing to do here.
        }
        char* slashClassName = toSlashClassName(mClassName.string());
        mClass = env->FindClass(slashClassName);
        if (mClass == NULL) {
            ALOGE("ERROR: could not find class '%s'n", mClassName.string());
        }
        free(slashClassName);
        mClass = reinterpret_cast<jclass>(env->NewGlobalRef(mClass));
    }

假如是 Zygote 进程,变量 mClassName 的值会为 null,会立刻回来。假如是一个一般 Java 类的调用, mClassName 中会存放类的称号,toSlashClassName(mClassName.string()) 的作用是将类名转换为类的全限定名,接着回去到类对应的 jclass 目标。

接着看 start 函数的后续部分:

    /*
     * Register android functions.
     */
    if (startReg(env) < 0) {
        ALOGE("Unable to register all android nativesn");
        return;
    }

startReg 的详细完成如下:

/*static*/ int AndroidRuntime::startReg(JNIEnv* env)
{
    ATRACE_NAME("RegisterAndroidNatives");
    /*
     * This hook causes all future threads created in this process to be
     * attached to the JavaVM.  (This needs to go away in favor of JNI
     * Attach calls.)
     */
    androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);
    ALOGV("--- registering native functions ---n");
    /*
     * Every "register" function calls one or more things that return
     * a local reference (e.g. FindClass).  Because we haven't really
     * started the VM yet, they're all getting stored in the base frame
     * and never released.  Use Push/Pop to manage the storage.
     */
    env->PushLocalFrame(200);
    if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
        env->PopLocalFrame(NULL);
        return -1;
    }
    env->PopLocalFrame(NULL);
    //createJavaThread("fubar", quickTest, (void*) "hello");
    return 0;
}
// 进一步调用 register_jni_procs
static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
{
    for (size_t i = 0; i < count; i++) {
        if (array[i].mProc(env) < 0) {
#ifndef NDEBUG
            ALOGD("----------!!! %s failed to loadn", array[i].mName);
#endif
            return -1;
        }
    }
    return 0;
}
static const RegJNIRec gRegJNI[] = {
    REG_JNI(register_com_android_internal_os_RuntimeInit),
    REG_JNI(register_com_android_internal_os_ZygoteInit_nativeZygoteInit),
    REG_JNI(register_android_os_SystemClock),
    REG_JNI(register_android_util_EventLog),
    REG_JNI(register_android_util_Log),
    REG_JNI(register_android_util_MemoryIntArray),
    REG_JNI(register_android_util_PathParser),
    REG_JNI(register_android_util_StatsLog),
    REG_JNI(register_android_util_StatsLogInternal),
    REG_JNI(register_android_app_admin_SecurityLog),
    REG_JNI(register_android_content_AssetManager),
    REG_JNI(register_android_content_StringBlock),
    REG_JNI(register_android_content_XmlBlock),
    REG_JNI(register_android_content_res_ApkAssets),
    REG_JNI(register_android_text_AndroidCharacter),
    REG_JNI(register_android_text_Hyphenator),
    REG_JNI(register_android_view_InputDevice),
    REG_JNI(register_android_view_KeyCharacterMap),
    REG_JNI(register_android_os_Process),
    REG_JNI(register_android_os_SystemProperties),
    REG_JNI(register_android_os_Binder),
    REG_JNI(register_android_os_Parcel),
    REG_JNI(register_android_os_HidlSupport),
    REG_JNI(register_android_os_HwBinder),
    REG_JNI(register_android_os_HwBlob),
    REG_JNI(register_android_os_HwParcel),
    REG_JNI(register_android_os_HwRemoteBinder),
    REG_JNI(register_android_os_NativeHandle),
    // ...... 省掉大部分
};

startReg 经过调用 register_jni_procs 函数将全局数组 gRegJNI 中的 JNI 本地函数注册到虚拟机中。咱们在 Java 层中调用的许多 Native 办法便是在这儿注册的。

接着看 start 函数的后续部分:

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

这儿主要是预备履行 Java 类的参数。这些参数保存在 strArray 中。


    /*
     * Start VM.  This thread becomes the main thread of the VM, and will
     * not return until the VM exits.
     */
    char* slashClassName = toSlashClassName(className != NULL ? className : "");
    jclass startClass = env->FindClass(slashClassName);
    if (startClass == NULL) {
        ALOGE("JavaVM unable to locate class '%s'n", slashClassName);
        /* keep going */
    } else {
        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);
#if 0
            if (env->ExceptionCheck())
                threadExitUncaughtException(env);
#endif
        }
    }
    free(slashClassName);
    ALOGD("Shutting down VMn");
    if (mJavaVM->DetachCurrentThread() != JNI_OK)
        ALOGW("Warning: unable to detach main threadn");
    if (mJavaVM->DestroyJavaVM() != 0)
        ALOGW("Warning: VM did not shut down cleanlyn");
}

先找到 ZygoteInit 类对应的 jclass, 然后经过 GetStaticMethodID 获得ZygoteInit 类中 main 办法的 ID,接着调用 CallStaticVoidMethod 函数 main 函数。至此,整个 start 函数就剖析完了,Zygote进程的初始化进程将转到Java层了。

参考资料