Android P zygote 啓動過程
Zygote 概述
在Android系統中,DVM,ART應用程序進程以及運行系統的關鍵服務System_server 進程都是由Zygote進程來創建的。我們將其稱之爲孵化器。它通過fork的形式創建應用程序進程和system_server 進程。由於zygote進程在啓動的時候會創建DVM或者ART,因此通過fork而創建的應用程序進程或者system_server進程可以在內部獲得一個dvm或者art的實例副本,不需要單獨爲每一個進程創建dvm或者art。
我們知道zygote進程是在init進程裏面啓動的,起初zygote進程的名字並不是叫做zygote,而是叫做app_process,這個名稱是在Android.mk文件裏面定義的,zygote進程其啓動之後,Linux系統下的pctrl系統會調用app_process,將其名稱換成了zygote。
Zygote啓動腳本
在init.rc文件中採用import的方式引入zygote腳本。而zygote啓動腳本都是通過Android初始化語言(Android Init Language)進行編寫的。
import的位置:
android-9.0.0_r3/system/core/rootdir/init.rc
11 import /init.usb.configfs.rc
12 import /init.${ro.zygote}.rc ->根據系統屬性 ro.zygote 進行定性
從上面的import語句,我們知道在啓動zygote的時候,系統屬性服務是已經啓動起來了。
爲什麼要通過 系統屬性 ro.zygote 來進行定位zygote啓動文件呢,因爲從Android 5.0 開始,Android 系統開始支持64位程序。Zygote 也就會有32位和64位的區別。所以利用系統屬性 ro.zygote 來進行控制使用不同的腳本。ro.zygote 屬性值有如下四種:
init.zygote32
init.zygote32_64
init.zygote64
init.zygote64_32
由此可以看出代碼中會存在如下幾個zygote文件:
/android-9.0.0_r3/system/core/rootdir/
init.zygote32.rc H A D 12-一月-2019 511
init.zygote32_64.rc H A D 12-一月-2019 853
init.zygote64.rc H A D 12-一月-2019 513
init.zygote64_32.rc H A D 12-一月-2019 875
比如我自己編譯的aosp代碼的 ro.zygote 的值爲:
generic_x86_64:/ $ getprop ro.zygote zygote64_32
Android 初始化語音的service類型語句格式如下:
service
init.zygote32.rc
表示支持純32位程序,文件內容如下:
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
class main
priority -20
user root
group root readproc reserved_disk
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進程名稱爲zygote,執行程序爲app_process ,class name爲main。當zygote服務重啓的時候,會重啓 audioserver,cameraserver,media,netd,wificond
init.zygote32_64.rc
表示既支持32位應用程序,也支持64位應用程序。其內容如下:
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 reserved_disk
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_process64 -Xzygote /system/bin --zygote --socket-name=zygote_secondary
class main
priority -20
user root
group root readproc reserved_disk
socket zygote_secondary stream 660 root system
onrestart restart zygote
writepid /dev/cpuset/foreground/tasks
這段代碼中有兩個service,則表明會啓動兩個zygote進程,一個爲zygote 執行程序爲 app_process32,作爲主模式。另一個 zygote_secondary 執行的主程序爲 app_process64 ,作爲從/輔模式。
init.zygote64.rc
service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
class main
priority -20
user root
group root readproc reserved_disk
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
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 reserved_disk
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 reserved_disk
socket zygote_secondary stream 660 root system
onrestart restart zygote
writepid /dev/cpuset/foreground/tasks
Zygote進程的啓動過程
從上面的service 的class我們知道,當在init進程啓動class 爲 main 的service的時候,就會啓動zygote進程了。
而zygote進程其實際上是執行 app_process64/app_process32 的main函數。其最終是執行:frameworks/base/cmds/app_process/app_main.cpp 的main函數。
android-9.0.0_r3/frameworks/base/cmds/app_process/app_main.cpp
179 #if defined(__LP64__)
180 static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist64";
181 static const char ZYGOTE_NICE_NAME[] = "zygote64";
182 #else
183 static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist32";
184 static const char ZYGOTE_NICE_NAME[] = "zygote";
185 #endif
186
187 int main(int argc, char* const argv[])
...
278 while (i < argc) {
279 const char* arg = argv[i++];
280 if (strcmp(arg, "--zygote") == 0) { //1
281 zygote = true;
282 niceName = ZYGOTE_NICE_NAME;
283 } else if (strcmp(arg, "--start-system-server") == 0) { //2
284 startSystemServer = true;
285 } else if (strcmp(arg, "--application") == 0) {
286 application = true;
287 } else if (strncmp(arg, "--nice-name=", 12) == 0) {
288 niceName.setTo(arg + 12);
289 } else if (strncmp(arg, "--", 2) != 0) {
290 className.setTo(arg);
291 break;
292 } else {
293 --i;
294 break;
295 }
296 }
...
323 if (startSystemServer) { //3
324 args.add(String8("start-system-server"));
325 }
...
345 if (!niceName.isEmpty()) {
346 runtime.setArgv0(niceName.string(), true /* setProcName */);
//調用 AndroidRuntime.cpp 的 start 函數。
347 }
348
349 if (zygote) { //4
350 runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
351 } else if (className) {
352 runtime.start("com.android.internal.os.RuntimeInit", args, zygote);
353 } else {
354 fprintf(stderr, "Error: no class name or --zygote supplied.\n");
355 app_usage();
356 LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
357 }
zygote都是通過fork自身來孵化新的進程的,比如system_server , 應用程序等,都是通過zygote fork孵化而來,所以在zygote的子進程中,都是可以進入到app_main.cpp 的main函數中來的。因此main函數中爲了區分運行在哪個進程,對參數做了簡要的區分,在註釋1處判斷參數中是否包含了–zygote,如果包含了則說明main函數是運行在zygote進程中的,並且將 zygote 設置爲true。而註釋2處則爲了標明需要啓動system_server,同時在註釋3處將 start-system-server 添加到args中,以傳遞給runtime。
android-9.0.0_r3/frameworks/base/core/jni/AndroidRuntime.cpp
void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
{
ALOGD(">>>>>> START %s uid %d <<<<<<\n",
className != NULL ? className : "(unknown)", getuid());
static const String8 startSystemServer("start-system-server");
/*
* 'startSystemServer == true' means runtime is obsolete and not run from
* init.rc anymore, so we print out the boot start event here.
*/
for (size_t i = 0; i < options.size(); ++i) {
if (options[i] == startSystemServer) { //參照上面給runtime傳遞的start-system-server 參數
/* track our progress through the boot sequence */
const int LOG_BOOT_PROGRESS_START = 3000;
LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START, ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
}
}
...
/* start the virtual machine */
JniInvocation jni_invocation;
jni_invocation.Init(NULL);
JNIEnv* env;
if (startVm(&mJavaVM, &env, zygote) != 0) { //啓動java虛擬機
return;
}
onVmCreated(env);
/*
* Register android functions.
*/
if (startReg(env) < 0) { //爲java虛擬機註冊jni方法。
ALOGE("Unable to register all android natives\n");
return;
}
...
classNameStr = env->NewStringUTF(className);
//從上面的分析中可以知道此處的 className 爲com.android.internal.os.ZygoteInit
assert(classNameStr != NULL);
env->SetObjectArrayElement(strArray, 0, classNameStr);
for (size_t i = 0; i < options.size(); ++i) {
jstring optionsStr = env->NewStringUTF(options.itemAt(i).string());
assert(optionsStr != NULL);
env->SetObjectArrayElement(strArray, i + 1, optionsStr);
//將傳遞過來的參數全部再次組裝以傳遞爲java框架層
}
/*
* Start VM. This thread becomes the main thread of the VM, and will
* not return until the VM exits.
*/
char* slashClassName = toSlashClassName(className != NULL ? className : "");
//對className 進行重新組裝,將classname中的 "." 換成 "/"
jclass startClass = env->FindClass(slashClassName);
// 通過 JNIEnv 找到對應的class。
if (startClass == NULL) {
ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
/* keep going */
} else {
jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
"([Ljava/lang/String;)V");
//找到 zygote 的main方法
if (startMeth == NULL) {
ALOGE("JavaVM unable to find main() in '%s'\n", className);
/* keep going */
} else {
env->CallStaticVoidMethod(startClass, startMeth, strArray);
//調用 ZygoteInit中的main方法。
#if 0
if (env->ExceptionCheck())
threadExitUncaughtException(env);
#endif
}
}
free(slashClassName);
我們通過jni調用ZygoteInit的main方法後,Zygote便進入到了Java框架層裏面了。在此前是還沒有代碼進入到Java框架層的。換一個說法是zygote開創了java框架層。
android-9.0.0_r3/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public static void main(String argv[]) {
ZygoteServer zygoteServer = new ZygoteServer();
// Mark zygote start. This ensures that thread creation will throw
// an error.
ZygoteHooks.startZygoteNoThreadCreation();
// Zygote goes into its own process group.
try {
Os.setpgid(0, 0);
} catch (ErrnoException ex) {
throw new RuntimeException("Failed to setpgid(0,0)", ex);
}
...
for (int i = 1; i < argv.length; i++) {
if ("start-system-server".equals(argv[i])) {
startSystemServer = true;
//參數中有 start-system-server , 則需要啓動 system_server
} else if ("--enable-lazy-preload".equals(argv[i])) {
enableLazyPreload = true;
} else if (argv[i].startsWith(ABI_LIST_ARG)) {
abiList = argv[i].substring(ABI_LIST_ARG.length());
} else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
socketName = argv[i].substring(SOCKET_NAME_ARG.length());
// SOCKET_NAME_ARG == "--socket-name=", 在啓動zygote的service裏面有這樣的參數: --socket-name=zygote 以及: --socket-name=zygote_secondary
} else {
throw new RuntimeException("Unknown command line argument: " + argv[i]);
}
}
...
zygoteServer.registerServerSocketFromEnv(socketName);
//創建一個server斷的socket,此處如果是zygote線程,則 socketName 爲 zygote,如果爲 zygote_secondary 線程,則socketName爲zygote_secondary
// In some configurations, we avoid preloading resources and classes eagerly.
// In such cases, we will preload things prior to our first fork.
if (!enableLazyPreload) {
bootTimingsTraceLog.traceBegin("ZygotePreload");
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
SystemClock.uptimeMillis());
preload(bootTimingsTraceLog);
//預加載類和資源
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
SystemClock.uptimeMillis());
bootTimingsTraceLog.traceEnd(); // ZygotePreload
} else {
Zygote.resetNicePriority();
}
...
if (startSystemServer) {
Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
//啓動system_server 進程。
// {@code r == null} in the parent (zygote) process, and {@code r != null} in the
// child (system_server) process.
if (r != null) {
r.run();
return;
}
}
...
// The select loop returns early in the child process after a fork and
// loops forever in the zygote.
caller = zygoteServer.runSelectLoop(abiList);
//等待着system_server 中的AMS通過socket連接zygote,以響應AMS要求創建應用程序的需求。
由上面的分析,大致可以得出ZygoteInit的main函數幹了如下幾個重要的事情:
- 創建server端的socket
- 預加載了類和資源
- 啓動了system_server
- 等待AMS請求
啓動system_server 進程
android-9.0.0_r3/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
long capabilities = posixCapabilitiesAsBits(
OsConstants.CAP_IPC_LOCK,
OsConstants.CAP_KILL,
OsConstants.CAP_NET_ADMIN,
OsConstants.CAP_NET_BIND_SERVICE,
OsConstants.CAP_NET_BROADCAST,
OsConstants.CAP_NET_RAW,
OsConstants.CAP_SYS_MODULE,
OsConstants.CAP_SYS_NICE,
OsConstants.CAP_SYS_PTRACE,
OsConstants.CAP_SYS_TIME,
OsConstants.CAP_SYS_TTY_CONFIG,
OsConstants.CAP_WAKE_ALARM,
OsConstants.CAP_BLOCK_SUSPEND
);
/* Containers run without some capabilities, so drop any caps that are not available. */
StructCapUserHeader header = new StructCapUserHeader(
OsConstants._LINUX_CAPABILITY_VERSION_3, 0);
StructCapUserData[] data;
try {
data = Os.capget(header);
} catch (ErrnoException ex) {
throw new RuntimeException("Failed to capget()", ex);
}
capabilities &= ((long) data[0].effective) | (((long) data[1].effective) << 32);
/* Hardcoded command line to start the system server */
String args[] = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1024,1032,1065,3001,3002,3003,3006,3007,3009,3010",
"--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_server",
"--runtime-args",
"--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
"com.android.server.SystemServer",
};
//啓動 system_server 的參數,設置uid,gid爲1000
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
parsedArgs = new ZygoteConnection.Arguments(args);
ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
boolean profileSystemServer = SystemProperties.getBoolean(
"dalvik.vm.profilesystemserver", false);
if (profileSystemServer) {
parsedArgs.runtimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
}
/* Request to fork the system server process */
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.runtimeFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
zygoteServer.closeServerSocket();
return handleSystemServerProcess(parsedArgs);
//fork 函數會返回兩個值,如果 pid 爲0,則標識當前執行的是子進程。handleSystemServerProcess 處理 system_server 該處理的事物。
}
return null;
}
runSelectLoop
android-9.0.0_r3/frameworks/base/core/java/com/android/internal/os/ZygoteServer.java
Runnable runSelectLoop(String abiList) {
ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
fds.add(mServerSocket.getFileDescriptor());
//mServerSocket 則爲前面我們創建的zygote 服務端socket,通過getFileDescriptor主要得到socket的fd值,並將其添加到監聽列表fds中。
peers.add(null);
while (true) {
//無限循環等待AMS請求,
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);
}
for (int i = pollFds.length - 1; i >= 0; --i) {
if ((pollFds[i].revents & POLLIN) == 0) {
continue;
}
//代碼能夠運行到此處,說明zygote 與AMS之間已經有socket建立連接了。
if (i == 0) {
ZygoteConnection newPeer = acceptCommandPeer(abiList);
//通過 acceptCommandPeer 函數,得到ZygoteConnection 進程與AMS進程建立的連接,並添加到socket連接列表 peers 中,注意,這裏表明這是剛剛纔建立socket連接,還並未有更實質的數據通信,實際的通信則應該是 i != 0 的情況。
peers.add(newPeer);
fds.add(newPeer.getFileDesciptor());
} else {
//i不等於0的情況,說明AMS向zygote發送了一個創建應用程序的請求。通過processOneCommand 創建實際的應用程序。
try {
ZygoteConnection connection = peers.get(i);
final Runnable command = connection.processOneCommand(this);
//創建新的進程
if (mIsForkChild) {
// We're in the child. We should always have a command to run at this
// stage if processOneCommand hasn't called "exec".
if (command == null) {
throw new IllegalStateException("command == null");
}
return command;
} else {
// We're in the server - we should never have any commands to run.
if (command != null) {
throw new IllegalStateException("command != null");
}
// We don't know whether the remote side of the socket was closed or
// not until we attempt to read from it from processOneCommand. This shows up as
// a regular POLLIN event in our regular processing loop.
if (connection.isClosedByPeer()) {
connection.closeSocket();
peers.remove(i);
fds.remove(i);
}
//銷燬相關數據
}
} catch (Exception e) {
if (!mIsForkChild) {
// We're in the server so any exception here is one that has taken place
// pre-fork while processing commands or reading / writing from the
// control socket. Make a loud noise about any such exceptions so that
// we know exactly what failed and why.
Slog.e(TAG, "Exception executing zygote command: ", e);
// Make sure the socket is closed so that the other end knows immediately
// that something has gone wrong and doesn't time out waiting for a
// response.
ZygoteConnection conn = peers.remove(i);
conn.closeSocket();
fds.remove(i);
} else {
// We're in the child so any exception caught here has happened post
// fork and before we execute ActivityThread.main (or any other main()
// method). Log the details of the exception and bring down the process.
Log.e(TAG, "Caught post-fork exception in child process.", e);
throw e;
}
} finally {
// Reset the child flag, in the event that the child process is a child-
// zygote. The flag will not be consulted this loop pass after the Runnable
// is returned.
mIsForkChild = false;
}
}
}
}
}
此函數的內容不算多,邏輯也還算較清晰。
Zygote進程啓動的總結
zygote啓動做了大致如下幾個事務:
- 創建AndroidRuntime並調用其start方法,自動zygote進程。
- 創建java虛擬機,並且爲java虛擬機註冊JNI方法。
- 通過JNI調用ZygoteInit的main函數,進入到Zygote的Java框架層。
- 通過 registerServerSocketFromEnv 創建服務端的socket,並且通過 runSelectLoop 方法等待AMS的請求來創建新的應用程序
- 啓動System_server 進程。