本文基于Android8.0源码
Android8.0使用的java虚拟机为ART,在大名鼎鼎的zygote进程中启动java虚拟机。 首先看一下zygote的main函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 int main (int argc, char * const argv[]) { AppRuntime runtime (argv[0 ], computeArgBlockSize(argc, argv)) ; if (zygote) { runtime.start ("com.android.internal.os.ZygoteInit" , args, zygote); } else if (className) { runtime.start ("com.android.internal.os.RuntimeInit" , args, zygote); } else { fprintf (stderr, "Error: no class name or --zygote supplied.\n" ); app_usage (); LOG_ALWAYS_FATAL ("app_process: no class name or --zygote supplied." ); } }
runtime.start会调用父类的AndroidRuntime::start,看一下实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 void AndroidRuntime::start (const char * className, const Vector<String8>& options, bool zygote) { ...... JniInvocation jni_invocation; jni_invocation.Init (NULL ); JNIEnv* env; if (startVm (&mJavaVM, &env, zygote) != 0 ) { return ; } onVmCreated (env); if (startReg (env) < 0 ) { ALOGE ("Unable to register all android natives\n" ); return ; } ...... if (startClass == NULL ) { ALOGE ("JavaVM unable to locate class '%s'\n" , slashClassName); } else { jmethodID startMeth = env->GetStaticMethodID (startClass, "main" , "([Ljava/lang/String;)V" ); if (startMeth == NULL ) { ALOGE ("JavaVM unable to find main() in '%s'\n" , className); } else { env->CallStaticVoidMethod (startClass, startMeth, strArray); } } }
加载虚拟机动态库,并加载库函数符号
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 bool JniInvocation::Init (const char * library) { ...... library = GetLibrary (library, buffer); ...... handle_ = dlopen (library, kDlopenFlags); ...... if (!FindSymbol (reinterpret_cast <void **>(&JNI_GetDefaultJavaVMInitArgs_), "JNI_GetDefaultJavaVMInitArgs" )) { return false ; } if (!FindSymbol (reinterpret_cast <void **>(&JNI_CreateJavaVM_), "JNI_CreateJavaVM" )) { return false ; } if (!FindSymbol (reinterpret_cast <void **>(&JNI_GetCreatedJavaVMs_), "JNI_GetCreatedJavaVMs" )) { return false ; } return true ; } jint JniInvocation::JNI_CreateJavaVM (JavaVM** p_vm, JNIEnv** p_env, void * vm_args) { return JNI_CreateJavaVM_ (p_vm, p_env, vm_args); } extern "C" jint JNI_CreateJavaVM (JavaVM** p_vm, JNIEnv** p_env, void * vm_args) { return JniInvocation::GetJniInvocation ().JNI_CreateJavaVM (p_vm, p_env, vm_args); }
启动虚拟机
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 int AndroidRuntime::startVm (JavaVM** pJavaVM, JNIEnv** pEnv, bool zygote) { ...... if (JNI_CreateJavaVM (pJavaVM, pEnv, &initArgs) < 0 ) { ALOGE ("JNI_CreateJavaVM failed\n" ); return -1 ; } return 0 ; }