Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

dalvik - Understanding Android: Zygote and DalvikVM

I am trying to understand how Android launches applications. The question is how (and why) does the Zygote fork a new Dalvik VM? I do not understand why it is not possible to run multiple applications in the same Dalvik VM.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Q. how does zygote exactly fork Dalvik VM?

Short Answer: The Zygote process cold boots a Java VM on system start up. It then listens to a socket for incoming commands. Other processes (e.g. ActivityManagerService) write commands to this socket whenever a new process is needed for an application. These commands are read by the Zygote process which calls fork() as necessary. Child processes get a pre-warmed VM in which to run. This is how Zygote forks the Dalvik VM.

Long answer: After the kernel is loaded, init.rc is parsed and native services are started. Then /system/bin/app_process) is run. This eventually calls AndroidRuntime.start(), passing it the parameters com.android.internal.os.ZygoteInit and start-system-server.

The AndroidRuntime.start() starts a Java VM then calls ZygoteInit.main(), passing it the parameter start-system-server.

ZygoteInit.main() registers the Zygote socket (which the Zygote process listens to for incoming commands, and on receiving new command, spawns a new process as requested). It then preloads a lot of classes (as listed in frameworks/base/preloaded-classes, over 4500 in Android 8.0) and all the system-wide resources like drawables, xmls, etc. Then it calls startSystemServer() which forks a new process for com.android.server.SystemServer. This fork is special and is not done in the same manner as the usual forks the Zygote performs on behalf of requesting processes.

After SystemServer is forked the runSelectLoopMode() function is called. This is a while(true) loop which establishes a ZygoteConnection with the Zygote socket and waits for commands on it. When a command is received, ZygoteConnection.runOnce() is called.

ZygoteConnection.runOnce() then calls Zygote.forkAndSpecialize() which then calls a native function to do the actual fork. Thus, like in the case of SystemServer, a child process is created which inherits a pre-warmed Dalvik VM for itself.

Q. why it is not possible to run multiple applications in the same Dalvik VM?

This is a design decision as far as I know. The Android guys just decided to fork a new VM per process for security via sandboxing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...