本系列主要介紹Android系統(tǒng)啟動過程中涉及到的init、Zygote、SystemServer和Launcher。
文本分析的源碼時(shí)基于Android8.0源碼。
Zygote(孵化器),系統(tǒng)中DVM、ART、應(yīng)用程序進(jìn)程和SystemServer進(jìn)程都是由Zygote創(chuàng)建,其中SystemServer是應(yīng)用層開發(fā)經(jīng)常碰到的,因?yàn)閼?yīng)用層APP的進(jìn)程是通過SystemServer進(jìn)程創(chuàng)建出來的。
一、Zygote啟動腳本
在Android 8.0系統(tǒng)啟動流程_init(一)中講解到了init啟動Zygote的過程,init.cpp通過解析init.rc中配置信息,該過程稱之為Zygote的啟動腳本,其流程包括如下:
- 引入init.zygote.xx.rc:在Android 8.0系統(tǒng)啟動流程_init(一)中init函數(shù)解析部分,講解了init.rc配置文件的五種語法格式,其中包括為了擴(kuò)展配置配置文件而引入的import語句,自Android8.0后,init.rc文件被分成了四種格式,通過import語句引入,如下所示
import /init.${ro.zygote}.rc
- 自Android5.0后,開始支持64位程序,通過系統(tǒng)的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基本類似,腳本文件主要解析如下:
- service:在init.rc通過“service”說明該語句是service,啟動一個(gè)service進(jìn)程;
- zygote:進(jìn)程名稱為zygote;
- /system/bin:通過應(yīng)用程序/system/bin/app_process來啟動它,這也驗(yàn)證了zygote剛開始時(shí)不叫zygote,而是app_procress,Zygote進(jìn)程啟動后,Linux系統(tǒng)將其更改為zygote;
- --zygote、--start--system--server:啟動Zygote的參數(shù),后續(xù)app_main.cpp中main函數(shù)中判斷使用;
- -socket-name=zygote:建立socket的名稱為zygote;
- class main:將Zygote聲明為主要服務(wù),在init啟動Zygote中,F(xiàn)orEachServiceInClass函數(shù)就是通過查找classname為main的Zygote進(jìn)程;
- socket xxx:表示需要為此服務(wù)創(chuàng)建一個(gè)socket;
- onrestart xxx:當(dāng)Zygote服務(wù)重啟時(shí),需要執(zhí)行的命令
二、Zygote進(jìn)程啟動過程介紹
下面通過Zygote進(jìn)程的時(shí)序圖,按照時(shí)序運(yùn)行涉及到的類,來進(jìn)行分析。
2.1 app_main.cpp
在Android 8.0系統(tǒng)啟動流程_init(一)中第四部分講到init啟動Zygote的流程知道最終調(diào)用到frameworks\base\cmds\app_process\app_main.cpp下的main方法,如下所示:
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;//如果當(dāng)前運(yùn)行Zygote進(jìn)程中,則變量zygote設(shè)置為true
niceName = ZYGOTE_NICE_NAME;
} else if (strcmp(arg, "--start-system-server") == 0) {
startSystemServer = true;//如果當(dāng)前運(yùn)行SystemServer進(jìn)程中,則變量startSystemServer 設(shè)置為true
} else if (strcmp(arg, "--application") == 0) {
application = true;//當(dāng)前為應(yīng)用的進(jìn)程,則變量 application設(shè)置為true
}
..
}
if (zygote) {//如果運(yùn)行在Zygote中,則啟動該進(jìn)程
runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
}
}
源碼分析如下:
- 判斷當(dāng)前進(jìn)程:Zyogte及其子進(jìn)程都是通過fork自身來創(chuàng)建子進(jìn)程的,這樣Zygote及其子進(jìn)程都可以進(jìn)入app_main.cpp的main函數(shù)中,此時(shí)需要通過argd的參數(shù)來區(qū)分是當(dāng)前運(yùn)行的是那個(gè)進(jìn)程?在main函數(shù)源碼解析中有如下注釋,如果是以“--”或不是以“-”開頭的arg則進(jìn)入該函數(shù)中,以此作為簡單的判斷。
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”或其他參數(shù),來判斷當(dāng)前運(yùn)行的是那種進(jìn)程。
-
啟動進(jìn)程:
如果變量zygote為true,則會調(diào)用如下方法,啟動Zygote進(jìn)程。
runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
2.2 AndroidRuntime.cpp
\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的“.”轉(zhuǎn)為“/”
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調(diào)用ZygoteInit的main方法,由于當(dāng)前是在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");
源碼分析:
- 啟動準(zhǔn)備:在注釋1和2中,通過startVm創(chuàng)建Java虛擬機(jī)和startReg為Java虛擬機(jī)注冊JNI方法;
- 找到ZygoteInit類:在注釋3、4、5和6將com.android.os.ZygoteInit轉(zhuǎn)為com/android/os/ZygoteInit并賦值給slashClassName,通過slashClassName找到ZygoteInit的main方法;
- 調(diào)用ZygoteInit類:找到該類后,通過注釋7的JNI方法調(diào)用ZygoteInit的main方法,進(jìn)入Java層的運(yùn)行環(huán)境中。
2.3 ZygoteInit.java
frameworks\base\core\java\com\android\internal\os\ZygoteInit.java
public static void main(String argv[]) {
...
//1.新建一個(gè)ZygoteServer對象
ZygoteServer zygoteServer = new ZygoteServer();
...
//2.創(chuàng)建一個(gè)server端的socket,且名稱為zygote
zygoteServer.registerServerSocket(socketName);
//3.預(yù)加載類和資源
preload(bootTimingsTraceLog);
...
//4.啟動SystemServer進(jìn)程
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、創(chuàng)建一個(gè)name為“zygote”的Socket服務(wù)端,用于等待AMS的請求Zygote來創(chuàng)建新的進(jìn)程;
2、預(yù)加載類和資源,包括drawable、color、OpenGL和文本連接符資源等,保存到Resources一個(gè)全局靜態(tài)變量中,下次讀取系統(tǒng)資源的時(shí)候優(yōu)先從靜態(tài)變量中查找;
3、啟動SystemServer進(jìn)程;
4、通過runSelectLoop()方法,等待AMS的請求創(chuàng)建新的應(yīng)用程序進(jìn)程。
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的環(huán)境變量值: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創(chuàng)建文件描述符:fd
FileDescriptor fd = new FileDescriptor();
fd.setInt$(fileDesc);
//4.創(chuàng)建服務(wù)端的Socket
mServerSocket = new LocalServerSocket(fd);
} catch (IOException ex) {
throw new RuntimeException(
"Error binding to local socket '" + fileDesc + "'", ex);
}
}
}
2.預(yù)加載類和資源
frameworks\base\core\java\com\android\internal\os\ZygoteInit.java
static void preload(TimingsTraceLog bootTimingsTraceLog) {
...
//1.預(yù)加載位于/system/etc/preloaded-classes文件中的類
preloadClasses();
...
2.預(yù)加載drawble和color的資源信息
preloadResources();
...
//3.通過JNI調(diào)用,預(yù)加載底層相關(guān)的資源
nativePreloadAppProcessHALs();
...
//4.預(yù)加載OpenGL資源
preloadOpenGL();
...
//5.預(yù)加載共享庫:"android","compiler_rt","jnigraphics"
preloadSharedLibraries();
//6.預(yù)加載文本連接符資源
preloadTextResources();
...
//7.zygote中,內(nèi)存共享進(jìn)程
warmUpJcaProviders();
...
}
3.啟動SystemServer進(jìn)程
frameworks\base\core\java\com\android\internal\os\ZygoteServer.java
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
...
//1.創(chuàng)建數(shù)組,保存啟動SystemServer的參數(shù)
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.創(chuàng)建SystemServer進(jìn)程
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,表示運(yùn)行在新的子進(jìn)程中
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
zygoteServer.closeServerSocket();
//4.處理SystemServer進(jìn)程
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.
* 運(yùn)行在Zygote進(jìn)程中,等待新的連接,并讀取請求數(shù)據(jù)
*/
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.開啟死循環(huán),不斷的等待AMS的請求
while (true) {
//3.通過遍歷fds存儲信息,添加至 pollFds數(shù)組中
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,表明已經(jīng)連接socket,
if (i == 0) {
ZygoteConnection newPeer = acceptCommandPeer(abiList);
peers.add(newPeer);
fds.add(newPeer.getFileDesciptor());
}else{
/6.如果不等于0 ,AMS向Zyogte進(jìn)程創(chuàng)建一個(gè)新的進(jìn)程的請求
ZygoteConnection connection = peers.get(i);
final Runnable command = connection.processOneCommand(this);
}
...
}