zygote
zygote进程启动
@init.rc
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
app_process的源码
@frameworks\base\cmds\app_process\app_main.cpp
int main(int argc, const char* const argv[]) { // These are global variables in ProcessState.cpp mArgC = argc; mArgV = argv;
mArgLen = 0; for (int i=0; i<argc; i++) { mArgLen += strlen(argv[i]) + 1; } mArgLen--;
AppRuntime runtime; const char* argv0 = argv[0];
// Process command line arguments // ignore argv[0] argc--; argv++;
// Everything up to '--' or first non '-' arg goes to the vm
int i = runtime.addVmArguments(argc, argv);
// Parse runtime arguments. Stop at first unrecognized option. bool zygote = false; bool startSystemServer = false; bool application = false; const char* parentDir = NULL; const char* niceName = NULL; const char* className = NULL; while (i < argc) { const char* arg = argv[i++]; if (!parentDir) { parentDir = arg; } else if (strcmp(arg, "--zygote") == 0) { zygote = true; niceName = "zygote"; } else if (strcmp(arg, "--start-system-server") == 0) { startSystemServer = true; } else if (strcmp(arg, "--application") == 0) { application = true; } else if (strncmp(arg, "--nice-name=", 12) == 0) { niceName = arg + 12; } else { className = arg; break; } }
if (niceName && *niceName) { setArgv0(argv0, niceName); set_process_name(niceName); }
runtime.mParentDir = parentDir;
if (zygote) { runtime.start("com.android.internal.os.ZygoteInit", startSystemServer ? "start-system-server" : ""); } else if (className) { // Remainder of args get passed to startup class main() runtime.mClassName = className; runtime.mArgC = argc - i; runtime.mArgV = argv + i; runtime.start("com.android.internal.os.RuntimeInit", application ? "application" : "tool"); } else { fprintf(stderr, "Error: no class name or --zygote supplied.\n"); app_usage(); LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied."); return 10; }
|
注:这里传入的参数:-Xzygote /system/bin --zygote --start-system-server所以 :
1.zygote = true;niceName = "zygote";startSystemServer = true;
2.set_process_name(niceName);进程的名字改成了zygote;
3.runtime.start();传入的参数是"com.android.internal.os.ZygoteInit"和"start-system-server"
AppRuntime::start()
@frameworks\base\core\jni\AndroidRuntime.cpp
void AndroidRuntime::start(const char* className, const char* options) { LOGD("\n>>>>>> AndroidRuntime START %s <<<<<<\n", className != NULL ? className : "(unknown)");
blockSigpipe();
/* * 'startSystemServer == true' means runtime is obsolete and not run from * init.rc anymore, so we print out the boot start event here. */ if (strcmp(options, "start-system-server") == 0) { /* 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))); }
const char* rootDir = getenv("ANDROID_ROOT"); if (rootDir == NULL) { rootDir = "/system"; if (!hasDir("/system")) { LOG_FATAL("No root directory specified, and /android does not exist."); return; } setenv("ANDROID_ROOT", rootDir, 1); }
//const char* kernelHack = getenv("LD_ASSUME_KERNEL"); //LOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);
/* start the virtual machine */ JNIEnv* env; if (startVm(&mJavaVM, &env) != 0) { return; } onVmCreated(env);
/* * Register android functions. */ if (startReg(env) < 0) { LOGE("Unable to register all android natives\n"); return; }
/* * We want to call main() with a String array with arguments in it. * At present we have two arguments, the class name and an option string. * Create an array to hold them. */ jclass stringClass; jobjectArray strArray; jstring classNameStr; jstring optionsStr;
stringClass = env->FindClass("java/lang/String"); assert(stringClass != NULL); strArray = env->NewObjectArray(2, stringClass, NULL); assert(strArray != NULL); classNameStr = env->NewStringUTF(className); assert(classNameStr != NULL); env->SetObjectArrayElement(strArray, 0, classNameStr); optionsStr = env->NewStringUTF(options); env->SetObjectArrayElement(strArray, 1, optionsStr);
/* * Start VM. This thread becomes the main thread of the VM, and will * not return until the VM exits. */ char* slashClassName = toSlashClassName(className); jclass startClass = env->FindClass(slashClassName); if (startClass == NULL) { LOGE("JavaVM unable to locate class '%s'\n", slashClassName); /* keep going */ } else { jmethodID startMeth = env->GetStaticMethodID(startClass, "main", "([Ljava/lang/String;)V"); if (startMeth == NULL) { LOGE("JavaVM unable to find main() in '%s'\n", className); /* keep going */ } else { env->CallStaticVoidMethod(startClass, startMeth, strArray);
#if 0 if (env->ExceptionCheck()) threadExitUncaughtException(env); #endif } } free(slashClassName);
LOGD("Shutting down VM\n"); if (mJavaVM->DetachCurrentThread() != JNI_OK) LOGW("Warning: unable to detach main thread\n"); if (mJavaVM->DestroyJavaVM() != 0) LOGW("Warning: VM did not shut down cleanly\n"); }
|
注:
1. startVm(&mJavaVM, &env),启动java虚拟机
2. startReg(env),注册android jni函数
3. env->CallStaticVoidMethod(startClass, startMeth, strArray); jni 调用 java 方法,类startClass 为参数className转化而来,startMeth是main方法,strArray为:env->SetObjectArrayElement(strArray, 0, classNameStr); env->SetObjectArrayElement(strArray, 1, optionsStr);
4. CallStaticVoidMethod就启动了com.android.internal.os.ZygoteInit中的main
ZygoteInit.main
@frameworks\base\core\java\com\android\internal\os\ZygoteInit.java
public static void main(String argv[]) { try { // Start profiling the zygote initialization. SamplingProfilerIntegration.start();
registerZygoteSocket(); EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START, SystemClock.uptimeMillis()); preload(); EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END, SystemClock.uptimeMillis());
// Finish profiling the zygote initialization. SamplingProfilerIntegration.writeZygoteSnapshot();
// Do an initial gc to clean up after startup gc();
// If requested, start system server directly from Zygote if (argv.length != 2) { throw new RuntimeException(argv[0] + USAGE_STRING); }
if (argv[1].equals("start-system-server")) { startSystemServer(); } else if (!argv[1].equals("")) { startSystemServer(); }else{ throw new RuntimeException(argv[0] + USAGE_STRING); }
Log.i(TAG, "Accepting command socket connections");
if (ZYGOTE_FORK_MODE) { runForkMode(); } else { runSelectLoopMode(); }
closeServerSocket(); } catch (MethodAndArgsCaller caller) { caller.run(); } catch (RuntimeException ex) { Log.e(TAG, "Zygote died with exception", ex); closeServerSocket(); throw ex; } } |
注:
1.传入的参数任然为app_main 传入runtime.start()的参数"com.android.internal.os.ZygoteInit"和"start-system-server"
2. preload();要预加载preloadClasses() 和 preloadResources()
3. startSystemServer();中会启动一个新的进程:system_server
4.最后会调用runSelectLoopMode(),进入while循环,由peers创建新的进程。
fork进程systemserver
@frameworks\base\core\java\com\android\internal\os\ZygoteInit.java
/** * Prepare the arguments and fork for the system server process. */ private static boolean startSystemServer() throws MethodAndArgsCaller, RuntimeException { /* 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,3001,3002,3003,3006,3007", "--capabilities=130104352,130104352", "--runtime-init", "--nice-name=system_server", "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 */ 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 */ if (pid == 0) { handleSystemServerProcess(parsedArgs); }
return true; } |
注:args命令行参数,包括:uid,gid,group,process_name,process class
Zygote.forkSystemServer返回的子进程 pid非0,在子进程中返回0