回顾Android系统启动流程4—init进程的工作流程
zygote是受精卵的意思,它是Android中的一个非常重要的守护进程服务(Daem Service),所有的其他Dalvik虚拟机进程都是通过zygote孵化(fork)出来的
。Android应用程序是由Java语言编写的,运行在各自独立的Dalvik虚拟机中。如果每个应用程序在启动之时都需要单独运行和初始化一个虚拟机,会大大降低系统性能,因此Android首先创建一个zygote虚拟机,然后通过它孵化出其他的虚拟机进程,进而共享虚拟机内存和框架层资源,这样大幅度提高应用程序的启动和运行速度。
Zygote是Android中非常重要的一个进程,和Init进程,SystemServer进程是支撑Android世界的三极。Zygote进程在Init进程中以service的方式启动的。
Zygote(孵化器),系统中DVM、ART、应用程序进程和SystemServer进程都是由Zygote创建,其中SystemServer是应用层开发经常碰到的,因为应用层APP的进程是通过SystemServer进程创建出来的。
在启动init进程的过程中,会去解析init.rc,然后启动zygote进程
引入init.zygote.xx.rc,自Android8.0后,init.rc文件被分成了四种格式,通过import语句引入,如下所示
import /init.${ro.zygote}.rc
自Android5.0后,开始支持64位程序,通过系统的ro.zygote属性来控制使用不同的Zygote启动脚本,启动不同的脚本文件(四种中的一种),解析文件中init.zygote.xx.rc中service语句,如下所示:
\system\core\rootdir\init.zygote32.rc
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
class main
priority -20
user root
group root readproc
socket zygote stream 660 root system
onrestart write /sys/android_power/request_state wake
....
writepid /dev/cpuset/foreground/tasks
\system\core\rootdir\init.zygote32_64.rc
service zygote /system/bin/app_process32 -Xzygote /system/bin --zygote --start-system-server --socket-name=zygote
class main
priority -20
user root
group root readproc
.....
writepid /dev/cpuset/foreground/tasks
service zygote_secondary /system/bin/app_process64 -Xzygote /system/bin --zygote --socket-name=zygote_secondary
class main
priority -20
user root
group root readproc
socket zygote_secondary stream 660 root system
onrestart restart zygote
writepid /dev/cpuset/foreground/tasks
以上是init.zygote32.rc、init.zygote32_64.rc的部分源码,其他两种init.zygote64.rc和init.zygote64_32.rc基本类似,脚本文件主要解析如下:
frameworks\base\cmds\app_process\app_main.cpp
int main(int argc, char* const argv[])
{
while (i < argc) {
const char* arg = argv[i++];
if (strcmp(arg, "--zygote") == 0) {
zygote = true;//如果当前运行Zygote进程中,则变量zygote设置为true
niceName = ZYGOTE_NICE_NAME;
} else if (strcmp(arg, "--start-system-server") == 0) {
startSystemServer = true;//如果当前运行SystemServer进程中,则变量startSystemServer 设置为true
} else if (strcmp(arg, "--application") == 0) {
application = true;//当前为应用的进程,则变量 application设置为true
}
..
}
if (zygote) {//如果运行在Zygote中,则启动该进程
runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
}
}
源码分析如下:
Everything up to ‘–’ or first non ‘-’ arg goes to the vm.
…
// --zygote : Start in zygote mode
// --start-system-server : Start the system server.
// --application : Start in application (stand alone, non zygote) mode.
// --nice-name : The nice name for this process.
通过判断arg中是否包含“–zygote”、“–start-system-server”、“–application”或其他参数,来判断当前运行的是那种进程。
runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
AndroidRuntime::start
startVm(&mJavaVM, &env, zygote) != 0 //创建虚拟机
\frameworks\base\core\jni\AndroidRuntime.cpp
int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv, bool zygote)
{
...
/* 1 start the virtual machine */
JniInvocation jni_invocation;
jni_invocation.Init(NULL);
JNIEnv* env;
if (startVm(&mJavaVM, &env, zygote) != 0) {
return;
}
onVmCreated(env);
/** 2 Register android functions.*/
if (startReg(env) < 0) {
ALOGE("Unable to register all android natives\n");
return;
}
}
...
//3 获取类名信息
classNameStr = env->NewStringUTF(className);
...
//4 className的“.”转为“/”
char* slashClassName = toSlashClassName(className != NULL ? className : "");
//5 找到ZygoteInit
jclass startClass = env->FindClass(slashClassName);
if (startClass == NULL) {
ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
/* keep going */
} else {
//6.找到ZygoteInit的main方法
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 {
//7. 通过JNI调用ZygoteInit的main方法,由于当前是在Native中,ZygoteInit是java编写。
env->CallStaticVoidMethod(startClass, startMeth, strArray);
#if 0
if (env->ExceptionCheck())
threadExitUncaughtException(env);
#endif
}
}
free(slashClassName);
ALOGD("Shutting down VM\n");
if (mJavaVM->DetachCurrentThread() != JNI_OK)
ALOGW("Warning: unable to detach main thread\n");
if (mJavaVM->DestroyJavaVM() != 0)
ALOGW("Warning: VM did not shut down cleanly\n");
源码分析:
ZygoteInit.java
frameworks\base\core\java\com\android\internal\os\ZygoteInit.java
public static void main(String argv[]) {
...
//1.新建一个ZygoteServer对象
ZygoteServer zygoteServer = new ZygoteServer();
...
//2.创建一个server端的socket,且名称为zygote
zygoteServer.registerServerSocket(socketName);
//3.预加载类和资源
preload(bootTimingsTraceLog);
...
//4.启动SystemServer进程
if (startSystemServer) {
Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
// {@code r == null} in the parent (zygote) process, and {@code r != null} in the
// child (system_server) process.
if (r != null) {
r.run();
return;
}
}
Log.i(TAG, "Accepting command socket connections");
//5.等待AMS请求
caller = zygoteServer.runSelectLoop(abiList);
} catch (Throwable ex) {
Log.e(TAG, "System zygote died with exception", ex);
throw ex;
} finally {
zygoteServer.closeServerSocket();
}
}
...
ZygoteInit的main方法主要做了如下几件事:
1.registerServerSocket
frameworks\base\core\java\com\android\internal\os\ZygoteServer.java
void registerServerSocket(String socketName) {
if (mServerSocket == null) {
int fileDesc;
//1.拼接Socket的名称
final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
try {
//2.得到Soket的环境变量值:ANDROID_SOCKET_zygote
String env = System.getenv(fullSocketName);
fileDesc = Integer.parseInt(env);
} catch (RuntimeException ex) {
throw new RuntimeException(fullSocketName + " unset or invalid", ex);
}
try {
//3.通过fileDesc创建文件描述符:fd
FileDescriptor fd = new FileDescriptor();
fd.setInt$(fileDesc);
//4.创建服务端的Socket
mServerSocket = new LocalServerSocket(fd);
} catch (IOException ex) {
throw new RuntimeException(
"Error binding to local socket '" + fileDesc + "'", ex);
}
}
}
2.预加载类和资源
frameworks\base\core\java\com\android\internal\os\ZygoteInit.java
static void preload(TimingsTraceLog bootTimingsTraceLog) {
...
//1.预加载位于/system/etc/preloaded-classes文件中的类
preloadClasses();
...
2.预加载drawble和color的资源信息
preloadResources();
...
//3.通过JNI调用,预加载底层相关的资源
nativePreloadAppProcessHALs();
...
//4.预加载OpenGL资源
preloadOpenGL();
...
//5.预加载共享库:"android","compiler_rt","jnigraphics"
preloadSharedLibraries();
//6.预加载文本连接符资源
preloadTextResources();
...
//7.zygote中,内存共享进程
warmUpJcaProviders();
...
}
3.启动SystemServer进程
frameworks\base\core\java\com\android\internal\os\ZygoteServer.java
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
...
//1.创建数组,保存启动SystemServer的参数
String args[] = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1032,3001,3002,3003,3006,3007,3009,3010",
"--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_server",
"--runtime-args",
"com.android.server.SystemServer",
};
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
parsedArgs = new ZygoteConnection.Arguments(args);
ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
/* Request to fork the system server process */
//2.创建SystemServer进程
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
//3.如果pid为0,表示运行在新的子进程中
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
zygoteServer.closeServerSocket();
//4.处理SystemServer进程
return handleSystemServerProcess(parsedArgs);
}
return null;
}
4.runSelectLoop()
frameworks\base\core\java\com\android\internal\os\ZygoteServer.java
/**
* Runs the zygote process's select loop. Accepts new connections as
* they happen, and reads commands from connections one spawn-request's
* worth at a time.
* 运行在Zygote进程中,等待新的连接,并读取请求数据
*/
Runnable runSelectLoop(String abiList) {
ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
//1.将ServerSocket添加到集合中
fds.add(mServerSocket.getFileDescriptor());
peers.add(null);
2.开启死循环,不断的等待AMS的请求
while (true) {
//3.通过遍历fds存储信息,添加至 pollFds数组中
StructPollfd[] pollFds = new StructPollfd[fds.size()];
for (int i = 0; i < pollFds.length; ++i) {
pollFds[i] = new StructPollfd();
pollFds[i].fd = fds.get(i);
pollFds[i].events = (short) POLLIN;
}
try {
Os.poll(pollFds, -1);
} catch (ErrnoException ex) {
throw new RuntimeException("poll failed", ex);
}
//4. 通过遍历pollFds信息
for (int i = pollFds.length - 1; i >= 0; --i) {
if ((pollFds[i].revents & POLLIN) == 0) {
continue;
}
//5.如果pid为0,表明已经连接socket,
if (i == 0) {
ZygoteConnection newPeer = acceptCommandPeer(abiList);
peers.add(newPeer);
fds.add(newPeer.getFileDesciptor());
}else{
/6.如果不等于0 ,AMS向Zyogte进程创建一个新的进程的请求
ZygoteConnection connection = peers.get(i);
final Runnable command = connection.processOneCommand(this);
}
...
}