Vector<String8> args; // 如果是zygote,则className为空,所以此处实际上是判断是否为zygote的进程 if (!className.isEmpty()) { // 判断非zygote模式时,只需要传递application的参数 // We're not in zygote mode, the only argument we need to pass // to RuntimeInit is the application argument. // // The Remainder of args get passed to startup class main(). Make // copies of them before we overwrite them with the process name. args.add(application ? String8("application") : String8("tool")); runtime.setClassNameAndArgs(className, argc - i, argv + i);
if (!LOG_NDEBUG) { String8 restOfArgs; char* const* argv_new = argv + i; int argc_new = argc - i; for (int k = 0; k < argc_new; ++k) { restOfArgs.append("\""); restOfArgs.append(argv_new[k]); restOfArgs.append("\" "); } ALOGV("Class name = %s, args = %s", className.string(), restOfArgs.string()); } } else { // We're in zygote mode. maybeCreateDalvikCache(); // classname为空,当前为zygote模式。如果startSystemServer为true.则增加启动SystemServer的参数 if (startSystemServer) { args.add(String8("start-system-server")); }
char prop[PROP_VALUE_MAX]; // 获取支持的CPU指令集 if (property_get(ABI_LIST_PROPERTY, prop, NULL) == 0) { LOG_ALWAYS_FATAL("app_process: Unable to determine ABI list from property %s.", ABI_LIST_PROPERTY); return11; } // 此处为zygote模式,需要把所有参数都传递过去 String8 abiFlag("--abi-list="); abiFlag.append(prop); args.add(abiFlag);
// In zygote mode, pass all remaining arguments to the zygote // main() method. for (; i < argc; ++i) { args.add(String8(argv[i])); } } // niceName不为空,说明是zygote模式 if (!niceName.isEmpty()) { runtime.setArgv0(niceName.string(), true/* setProcName */); } // 如果是zygote模式 if (zygote) { // 调用zygoteInit函数,并把当前的参数传递过去 // 这里调用runtime的start函数来启动zygote进程, // 并将args传入,这样启动zygote进程后,zygote进程会将SystemServer进程启动。 runtime.start("com.android.internal.os.ZygoteInit", args, zygote); } elseif (!className.isEmpty()) { // 如果是非zygote模式 //调用RuntimeInit函数 runtime.start("com.android.internal.os.RuntimeInit", args, zygote); } else { fprintf(stderr, "Error: no class name or --zygote supplied.\n"); app_usage(); LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied."); } }
/* * 代码位于:frameworks/base/core/jni/AndroidRuntime.cpp * Start the Android runtime. This involves starting the virtual machine * and calling the "static void main(String[] args)" method in the class * named by "className". * * Passes the main function two arguments, the class name and the specified * options string. */ voidAndroidRuntime::start(constchar* className, const Vector<String8>& options, bool zygote) { ALOGD(">>>>>> START %s uid %d <<<<<<\n", className != NULL ? className : "(unknown)", getuid());
staticconst String8 startSystemServer("start-system-server"); // Whether this is the primary zygote, meaning the zygote which will fork system server. // 判断这个是否是主zygote,即是否需要进行fork system server bool primary_zygote = false;
/* * '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) { primary_zygote = true; /* track our progress through the boot sequence */ constint LOG_BOOT_PROGRESS_START = 3000; LOG_EVENT_LONG(LOG_BOOT_PROGRESS_START, ns2ms(systemTime(SYSTEM_TIME_MONOTONIC))); } }
constchar* rootDir = getenv("ANDROID_ROOT"); if (rootDir == NULL) { rootDir = "/system"; if (!hasDir("/system")) { LOG_FATAL("No root directory specified, and /system does not exist."); return; } setenv("ANDROID_ROOT", rootDir, 1); }
constchar* artRootDir = getenv("ANDROID_ART_ROOT"); if (artRootDir == NULL) { LOG_FATAL("No ART directory specified with ANDROID_ART_ROOT environment variable."); return; }
constchar* i18nRootDir = getenv("ANDROID_I18N_ROOT"); if (i18nRootDir == NULL) { LOG_FATAL("No runtime directory specified with ANDROID_I18N_ROOT environment variable."); return; }
constchar* tzdataRootDir = getenv("ANDROID_TZDATA_ROOT"); if (tzdataRootDir == NULL) { LOG_FATAL("No tz data directory specified with ANDROID_TZDATA_ROOT environment variable."); return; }
/* start the virtual machine */ // 调用startVm函数来创建JavaVm(DVM) JniInvocation jni_invocation; // TODO jni环境的初始化?? jni_invocation.Init(NULL); JNIEnv* env; if (startVm(&mJavaVM, &env, zygote, primary_zygote) != 0) { return; } onVmCreated(env);
/* * Register android functions. * 调用startReg函数用来为DVM注册JNI */ if (startReg(env) < 0) { ALOGE("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;
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); }
/* * 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 : ""); jclass startClass = env->FindClass(slashClassName); if (startClass == NULL) { ALOGE("JavaVM unable to locate class '%s'\n", slashClassName); /* keep going */ } else { //找到ZygoteInit的main函数 //其中startClass从app_main的main函数得知为com.android.internal.os.ZygoteInit 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 { //通过JNI调用ZygoteInit的main函数 // 注释4处通过JNI调用ZygoteInit的main函数,因为ZygoteInit的main函数是Java编写的,因此需要通过JNI调用。 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"); }
/** * 代码位于:/framework/base/core/java/com/android/internal/os/ZygoteInit.java * This is the entry point for a Zygote process. It creates the Zygote server, loads resources, * and handles other tasks related to preparing the process for forking into applications. * * This process is started with a nice value of -20 (highest priority). All paths that flow * into new processes are required to either set the priority to the default value or terminate * before executing any non-system code. The native side of this occurs in SpecializeCommon, * while the Java Language priority is changed in ZygoteInit.handleSystemServerProcess, * ZygoteConnection.handleChildProc, and Zygote.usapMain. * * @param argv Command line arguments used to specify the Zygote's configuration. */ @UnsupportedAppUsage publicstaticvoidmain(String argv[]) { //用来管理和子进程通信的socket服务端 ZygoteServerzygoteServer=null;
// Mark zygote start. This ensures that thread creation will throw // an error. //这里其实只是设置一个标志位,为创建Java线程时做判断处理,如果是zygote进程,则不需要开启线程 ZygoteHooks.startZygoteNoThreadCreation();
// Zygote goes into its own process group. try { //为zygote进程设置pgid(Process Group ID), // 详见:`https://stackoverflow.com/questions/41498383/what-do-the-identifiers-pid-ppid-sid-pgid-uid-euid-mean` Os.setpgid(0, 0); } catch (ErrnoException ex) { thrownewRuntimeException("Failed to setpgid(0,0)", ex); }
finalbooleanisPrimaryZygote= zygoteSocketName.equals(Zygote.PRIMARY_SOCKET_NAME); if (!isRuntimeRestarted) { if (isPrimaryZygote) { FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED, BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__ZYGOTE_INIT_START, startTime); } elseif (zygoteSocketName.equals(Zygote.SECONDARY_SOCKET_NAME)) { FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED, BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SECONDARY_ZYGOTE_INIT_START, startTime); } } //如果支持架构为空,直接抛出异常 if (abiList == null) { thrownewRuntimeException("No ABI list supplied."); }
// 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 }
// Do an initial gc to clean up after startup bootTimingsTraceLog.traceBegin("PostZygoteInitGC"); //调用ZygoteHooks.gcAndFinalize()进行垃圾回收 gcAndFinalize(); bootTimingsTraceLog.traceEnd(); // PostZygoteInitGC
//判断是否需要startSystemServer if (startSystemServer) { //通过fork的方式开启zygote的子进程,systemServer,并返回一个Runnale对象 Runnabler= forkSystemServer(abiList, zygoteSocketName, zygoteServer);
// {@code r == null} in the parent (zygote) process, and {@code r != null} in the // child (system_server) process. //如果是zygote进程,则r==null,如果不是zygote进程,也就是systemServer进程,则执行下面的代码 if (r != null) { r.run(); return; } }
// The select loop returns early in the child process after a fork and // loops forever in the zygote. // zygote进程进入死循环中,来获取子进程发送的消息 caller = zygoteServer.runSelectLoop(abiList); } catch (Throwable ex) { //如果发生异常,则说明zygote初始化失败,zygoteServer也需要关闭 Log.e(TAG, "System zygote died with exception", ex); throw ex; } finally { //如果发生异常,则说明zygote初始化失败,zygoteServer也需要关闭 if (zygoteServer != null) { zygoteServer.closeServerSocket(); } }
// We're in the child process and have exited the select loop. Proceed to execute the // command. if (caller != null) { caller.run(); } }
if (Zygote.nativeSupportsTaggedPointers()) { /* Enable pointer tagging in the system server. Hardware support for this is present * in all ARMv8 CPUs. */ parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_TBI; }
/* Enable gwp-asan on the system server with a small probability. This is the same * policy as applied to native processes and system apps. */ parsedArgs.mRuntimeFlags |= Zygote.GWP_ASAN_LEVEL_LOTTERY;
if (shouldProfileSystemServer()) { parsedArgs.mRuntimeFlags |= Zygote.PROFILE_SYSTEM_SERVER; } //fork创建SystemServer /* Request to fork the system server process */ pid = Zygote.forkSystemServer( parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids, parsedArgs.mRuntimeFlags, null, parsedArgs.mPermittedCapabilities, parsedArgs.mEffectiveCapabilities); } catch (IllegalArgumentException ex) { thrownewRuntimeException(ex); } //pid为0,则说明是zygote进程,进行最后的收尾工作 /* For child process */ if (pid == 0) { if (hasSecondZygote(abiList)) { waitForSecondaryZygote(socketName); }
if (gUsapPoolEventFD != -1) { fds_to_close.push_back(gUsapPoolEventFD); fds_to_ignore.push_back(gUsapPoolEventFD); }
if (gSystemServerSocketFd != -1) { fds_to_close.push_back(gSystemServerSocketFd); fds_to_ignore.push_back(gSystemServerSocketFd); } //从zygote进程fork出子进程,并返回processId pid_t pid = ForkCommon(env, true, fds_to_close, fds_to_ignore, true); if (pid == 0) { // System server prcoess does not need data isolation so no need to // know pkg_data_info_list. SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits, permitted_capabilities, effective_capabilities, MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true, false, nullptr, nullptr, /* is_top_app= */false, /* pkg_data_info_list */nullptr, /* whitelisted_data_info_list */nullptr, false, false); } elseif (pid > 0) { // The zygote process checks whether the child process has died or not. ALOGI("System server process %d has been created", pid); gSystemServerPid = pid; // There is a slight window that the system server process has crashed // but it went unnoticed because we haven't published its pid yet. So // we recheck here just to make sure that all is well. int status; if (waitpid(pid, &status, WNOHANG) == pid) { ALOGE("System server process %d has died. Restarting Zygote!", pid); RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!"); }
if (UsePerAppMemcg()) { // Assign system_server to the correct memory cgroup. // Not all devices mount memcg so check if it is mounted first // to avoid unnecessarily printing errors and denials in the logs. if (!SetTaskProfiles(pid, std::vector<std::string>{"SystemMemoryProcess"})) { ALOGE("couldn't add process %d into system memcg group", pid); } } } return pid; }