7月 072020
本文基于Android8.1系统进行研究
一、启动zygote
在Linux内核启动完成后,首先启动系统的第一个进程init进程
init进程会读取init.rc中的配置文件
其中有Zygote的配置,init进程将启动zygote进程
zygote的入口在app_main.cpp中的main函数中
二、解析传入参数,调用AndroidRuntime的start方法
在app_main.cpp中的main函数中,首先解析传入的相关参数,并通过如下代码进入ZygoteInit的main函数中
1 2 3 |
if (zygote) { runtime.start("com.android.internal.os.ZygoteInit", args, zygote); } |
runtime是AppRuntime的一个实例,AppRuntim继承自AndroidRuntime
start函数定义在AndroidRuntime中,下面是start函数的注释
1 2 3 4 5 6 7 8 9 10 11 |
/* * Start the Android runtime. This involves starting the virtual machine * and calling the "static void main(String[] args)" method in the class * named by "className". * * Passes the main function two arguments, the class name and the specified * options string. * * 翻译: * 启动Android运行时,包括启动虚拟机,调用className参数对应的main函数 */ |
start函数中的这段代码切入到了startVm函数中
1 2 3 4 5 6 7 8 |
/* start the virtual machine */ JniInvocation jni_invocation; jni_invocation.Init(NULL); JNIEnv* env; if (startVm(&mJavaVM, &env, zygote) != 0) { return; } onVmCreated(env); |
三、startVm函数
这个函数前边也是一堆处理Vm启动参数的逻辑
在函数的最好调用JNI_CreateJavaVM函数通过c++层的库创建虚拟机
四、JNI_CreateJavaVM函数
JNI_CreateJavaVM函数是在art/runtime/java_vm_ext.cc中实现的,代码如下:
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 |
// JNI Invocation interface. extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) { ScopedTrace trace(__FUNCTION__); const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args); if (JavaVMExt::IsBadJniVersion(args->version)) { LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version; return JNI_EVERSION; } RuntimeOptions options; for (int i = 0; i < args->nOptions; ++i) { JavaVMOption* option = &args->options[i]; options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo)); } bool ignore_unrecognized = args->ignoreUnrecognized; if (!Runtime::Create(options, ignore_unrecognized)) { return JNI_ERR; } // Initialize native loader. This step makes sure we have // everything set up before we start using JNI. android::InitializeNativeLoader(); Runtime* runtime = Runtime::Current(); bool started = runtime->Start(); if (!started) { delete Thread::Current()->GetJniEnv(); delete runtime->GetJavaVM(); LOG(WARNING) << "CreateJavaVM failed"; return JNI_ERR; } *p_env = Thread::Current()->GetJniEnv(); *p_vm = runtime->GetJavaVM(); return JNI_OK; } |
Runtime是在art/runtime/runtime.h中定义的类
Runtime::Current()返回一个静态的Runtime实例,代码如下:
1 |
static Runtime* instance_; |
runtime-Start()启动虚拟机
五、其他参考文章
Android ART运行时无缝替换Dalvik虚拟机的过程分析
https://blog.csdn.net/zhu929033262/article/details/77053640
Android虚拟机art流程:从zygote开始梳理art的启动(1)
Sorry, the comment form is closed at this time.