ART虚拟机启动的流程非常复杂,这里先将涉及到的各个模块列个提纲。后续再详细分析各个子模块。
总之,看虚拟机的启动流程,紧紧抓住下面这条主线即可。
init
init.rc
-
source
- system/core/rootdir/init.rc
-
import zygote的资源文件
... ... import /init.${ro.zygote}.rc ... ...
-
angler board的值如下
- ${ro.zygote}在build/target/product/core_64_bit.mk中定义
# Set the zygote property to select the 64-bit primary, 32-bit secondary script # This line must be parsed before the one in core_minimal.mk PRODUCT_DEFAULT_PROPERTY_OVERRIDES += ro.zygote=zygote64_32
- 获取ro.zygote属性
angler:/ # getprop ro.zygote zygote64_32
- ${ro.zygote}在build/target/product/core_64_bit.mk中定义
init.zygote*.rc
- source
- system/core/rootdir/init.zygote64_32.rc
- 内容
service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server --socket-name=zygote class main priority -20 user root group root readproc socket zygote stream 660 root system onrestart write /sys/android_power/request_state wake onrestart write /sys/power/state on onrestart restart audioserver onrestart restart cameraserver onrestart restart media onrestart restart netd onrestart restart wificond writepid /dev/cpuset/foreground/tasks service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin --zygote --socket-name=zygote_secondary --enable-lazy-preload class main priority -20 user root group root readproc socket zygote_secondary stream 660 root system onrestart restart zygote writepid /dev/cpuset/foreground/tasks
app_process
source
- frameworks/base/cmds/app_process/app_main.cpp
- Android.mk
LOCAL_MODULE:= app_process LOCAL_MULTILIB := both LOCAL_MODULE_STEM_32 := app_process32 LOCAL_MODULE_STEM_64 := app_process64
流程
- 创建AppRuntime对象
AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
- 解析参数
- runtime.start
- runtime.start("com.android.internal.os.ZygoteInit", args, zygote)
- runtime.start("com.android.internal.os.RuntimeInit", args, zygote)
AndroidRuntime
source
- frameworks/base/core/jni/include/android_runtime/AndroidRuntime.h
- frameworks/base/core/jni/AndroidRuntime.cpp
AndroidRuntime::start()流程
-
初始化JNI
JniInvocation jni_invocation; jni_invocation.Init(NULL);
-
startVm(&mJavaVM, &env, zygote)
- 构造ART VM参数(dalvik property)
- JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs)
- 通过JNI创建ART虚拟机
-
onVmCreated()
- AppRuntime::onVmCreated()
-
startReg()
- androidSetCreateThreadFunc()
- env->PushLocalFrame(200)
- register_jni_procs()
- register_com_android_internal_os_RuntimeInit()
- register_com_android_internal_os_ZygoteInit()
- ... ...
- env->PopLocalFrame(NULL)
-
进入Java main()
- env->FindClass(slashClassName)
- env->GetStaticMethodID()
- env->CallStaticVoidMethod(startClass, startMeth, strArray);
libnativehelper
source
- libnativehelper/include/nativehelper/jni.h
- libnativehelper/include/nativehelper/JniInvocation.h
- libnativehelper/JniInvocation.cpp
代码
-
JniInvocation::Init()
- dlopen("libart.so")
- JniInvocation::FindSymbol()
- JNI_GetDefaultJavaVMInitArgs_(JNI_GetDefaultJavaVMInitArgs)
- JNI_CreateJavaVM_(JNI_CreateJavaVM)
- JNI_GetCreatedJavaVMs_(JNI_GetCreatedJavaVMs)
-
JniInvocation::JNI_CreateJavaVM
jint JniInvocation::JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) { return JNI_CreateJavaVM_(p_vm, p_env, vm_args); }
ART
source
- art/runtime/java_vm_ext.cc
- art/runtime/runtime.cc
流程
art::JNI_CreateJavaVM()
Runtime::Create()
-
Runtime::ParseOptions()
- ParsedOptions::Parse()
- ParsedOptions::Parse()
- ParsedOptions::DoParse()
- ParsedOptions::ProcessSpecialOptions()
- parser->Parse(argv_list)
- 设置BootClassPath/Image等
- ParsedOptions::DoParse()
- ParsedOptions::Parse()
- ParsedOptions::Parse()
-
Runtime::Create()
- instance_ = new Runtime()
- Runtime::Init()
- MemMap::Init()
- QuasiAtomic::Startup()
- oat_file_manager_ = new OatFileManager
- monitor相关
- Monitor::Init()
- monitor_list_ = new MonitorList
- monitor_pool_ = MonitorPool::Create()
- thread_list_ = new ThreadList()
- intern_table_ = new InternTable
- heap_ = new gc::Heap()
- jit_options_.reset()
- fault_manager
- BlockSignals()
- InitPlatformSignalHandlers()
- fault_manager.Init()
- new StackOverflowHandler(&fault_manager)
- new NullPointerHandler(&fault_manager)
- java_vm_ = JavaVMExt::Create()
- Thread::Startup()
- Thread::Attach("main")
- class_linker_
- class_linker_ = new ClassLinker(intern_table_)
- GetHeap()->HasBootImageSpace()
- InitFromBootImage()
- InitWithoutImage()
- verifier::MethodVerifier::Init()
- plugin.Load()
- agent.Load()
-
Thread::Attach()
- new Thread()
- Thread::Init()
- JNIEnvExt::Create()
- new JNIEnvExt()
- GetFunctionTable()
- GetJniNativeInterface()
- gJniNativeInterface
- JNI::FindClass()
- JNI::RegisterNatives()
- ... ...
- gJniNativeInterface
- new JNIEnvExt()
- JNIEnvExt::Create()
- self->InitStringEntryPoints()
- SetState(kNative)
Runtime::Start()
self->TransitionFromRunnableToSuspended(kNative)
-
InitNativeMethods()
- JniConstants::init(env)
- RegisterRuntimeNativeMethods(env)
- register_dalvik_system_DexFile(env)
- register_dalvik_system_VMRuntime(env)
- register_dalvik_system_ZygoteHooks(env)
- ... ...
- WellKnownClasses::Init(env)
- CacheClass()
- CacheMethod()
- CacheField()
- CachePrimitiveBoxingMethod()
- java_vm_->LoadNativeLibrary("libjavacore.so")
- java_vm_->LoadNativeLibrary("libopenjdk.so")
- WellKnownClasses::LateInit(env)
InitThreadGroups(self)
Thread::FinishStartup()
-
!IsZygote()
- T: CreateJit()
- F: jit::Jit::LoadCompilerLibrary(&error_msg)
system_class_loader_ = CreateSystemClassLoader(this);
-
!is_zygote_
- InitNonZygoteOrPostFork()
-
StartDaemonThreads()
- env->CallStaticVoidMethod()
- ReferenceQueueDaemon.INSTANCE.start()
- FinalizerDaemon.INSTANCE.start()
- FinalizerWatchdogDaemon.INSTANCE.start()
- HeapTaskDaemon.INSTANCE.start()
- env->CallStaticVoidMethod()
Runtime::InitNonZygoteOrPostFork()
非Zygote或zygote fork后的子进程,走到这里会创建和启动jit/signalcatcher/jdwp三个线程。
- Runtime::InitNonZygoteOrPostFork()
- Heap::CreateThreadPool()
- Heap::ResetGcPerformanceInfo()
- CreateJit()
- StartSignalCatcher()
- Dbg::StartJdwp()
ZygoteInit
source
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
frameworks/base/core/java/com/android/internal/os/ZygoteServer.java
frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java
frameworks/base/core/java/com/android/internal/os/Zygote.java
frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
-
libcore/dalvik/src/main/java/dalvik/system/ZygoteHooks.java
ZygoteInit最终会编译到framework.jar
main()
new ZygoteServer()
registerZygoteSocket()
-
preload()
beginIcuCachePinning()
-
preloadClasses()
- 主要是预加载preloaded-classes
- preloaded-classes在代码库的位置:frameworks/base/preloaded-classes
- preloaded-classes在手机中的位置:/system/etc/preloaded-classes
- Android 8.1版本在frameworks/base/config/preloaded-classes
- new FileInputStream(PRELOADED_CLASSES)
- new BufferedReader(new InputStreamReader(is), 256)
- line = br.readLine()
- Class.forName(line, true, null)
- classForName()
- art::Class_classForName()
- ClassLinker::FindClass()
- art::Class_classForName()
- classForName()
- 主要是预加载preloaded-classes
preloadResources()
preloadOpenGL()
preloadSharedLibraries()
preloadTextResources()
-
startSystemServer()
-
Zygote.forkSystemServer()
-
VM_HOOKS.preFork()
- Daemons.stop()
- waitUntilAllThreadsStopped()
- nativePreFork()
- nativeForkSystemServer()
- com_android_internal_os_Zygote_nativeForkSystemServer()
- ForkAndSpecializeCommon()
- com_android_internal_os_Zygote_nativeForkSystemServer()
-
VM_HOOKS.postForkCommon()
- Daemons.startPostZygoteFork()
- ReferenceQueueDaemon.INSTANCE.startPostZygoteFork()
- FinalizerDaemon.INSTANCE.startPostZygoteFork()
- FinalizerWatchdogDaemon.INSTANCE.startPostZygoteFork()
- HeapTaskDaemon.INSTANCE.startPostZygoteFork()
- Daemons.startPostZygoteFork()
-
VM_HOOKS.preFork()
-
handleSystemServerProcess()
- performSystemServerDexOpt()
- ZygoteInit.zygoteInit()
- RuntimeInit.commonInit()
- ZygoteInit.nativeZygoteInit()
- com_android_internal_os_ZygoteInit_nativeZygoteInit()
- AppRuntime::onZygoteInit()
- ProcessState::self()
- startThreadPool()
- AppRuntime::onZygoteInit()
- com_android_internal_os_ZygoteInit_nativeZygoteInit()
- RuntimeInit.applicationInit()
- invokeStaticMain()
- 获取指定类的main()方法
- throw new Zygote.MethodAndArgsCaller(m, argv)
- caller.run()
- mMethod.invoke()
- invokeStaticMain()
-
-
zygoteServer.runSelectLoop()
- runOnce()
-
Zygote.forkAndSpecialize()
- VM_HOOKS.preFork()
- nativeForkAndSpecialize()
- com_android_internal_os_Zygote_nativeForkAndSpecialize()
- ForkAndSpecializeCommon()
- com_android_internal_os_Zygote_nativeForkAndSpecialize()
VM_HOOKS.postForkCommon()
-
子进程: handleChildProc()
这里和前面system_server的处理类似。
- closeSocket()
- ZygoteInit.zygoteInit()
父进程: handleParentProc()
-
- runOnce()
ForkAndSpecializeCommon()
- ForkAndSpecializeCommon()
- fork()
子进程
- UnsetSigChldHandler()
- env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, ...)
- callPostForkChildHooks()
- VM_HOOKS.postForkChild()
- nativePostForkChild()
- ZygoteHooks_nativePostForkChild()
- Runtime::InitNonZygoteOrPostFork()
- ZygoteHooks_nativePostForkChild()
- nativePostForkChild()
- VM_HOOKS.postForkChild()
- callPostForkChildHooks()
父进程
- sigprocmask(SIG_UNBLOCK, &sigchld, nullptr)