Android系統(tǒng) init--> zygote-->system server進程啟動流程分析

Android系統(tǒng)啟動過程大概可以分為5步:

 Loader --> Kernel --> Native --> Framework --> Application
  • Loader

Boot ROM: 當(dāng)手機處于關(guān)機狀態(tài)時,長按電源鍵開機,引導(dǎo)芯片開始從固化在ROM里的預(yù)設(shè)出代碼開始執(zhí)行,然后加載引導(dǎo)程序到RAM
Boot Loader:這是啟動Android系統(tǒng)之前的引導(dǎo)程序,主要是檢查RAM,初始化硬件參數(shù)等功能

  • Kernel

Kernel層是指Android內(nèi)核層, 到這里才剛剛開始進入Android系統(tǒng),啟動Kernel的swapper進程(pid=0):該進程又稱為idle進程, 系統(tǒng)初始化過程Kernel由無到有開創(chuàng)的第一個進程, 用于初始化進程管理、內(nèi)存管理,加載Display,Camera Driver,Binder Driver等相關(guān)工作,啟動kthreadd進程(pid=2):是Linux系統(tǒng)的內(nèi)核進程,會創(chuàng)建內(nèi)核工作線程kworkder,軟中斷線程ksoftirqd,thermal等內(nèi)核守護進程。kthreadd進程是所有內(nèi)核進程的鼻祖

  • Native

這里的Native層主要包括init孵化來的用戶空間的守護進程、HAL層以及開機動畫等。啟動init進程(pid=1),是Linux系統(tǒng)的用戶進程,init進程是所有用戶進程的鼻祖,init進程會孵化出ueventd、logd、healthd、installd、adbd、lmkd等用戶守護進程,init進程還啟動servicemanager(binder服務(wù)管家)、bootanim(開機動畫)等重要服務(wù),init進程孵化出Zygote進程,Zygote進程是Android系統(tǒng)的第一個Java進程(即虛擬機進程),Zygote是所有Java進程的父進程

  • Framework

Zygote進程啟動后,加載ZygoteInit類,注冊Zygote Socket服務(wù)端套接字;加載虛擬機;加載類,加載系統(tǒng)資源,System Server進程,是由Zygote進程fork而來,System Server是Zygote孵化的第一個進程,System Server負責(zé)啟動和管理整個Java framework,包含ActivityManager,PowerManager等服務(wù), Media Server進程,是由init進程fork而來,負責(zé)啟動和管理整個C++ framework,包含AudioFlinger,Camera Service等服務(wù)

  • Application

    Zygote進程孵化出的第一個App進程是Launcher,即手機桌面APP,沒錯,手機桌面就是跟我們平時使用的APP一樣,它也是一個應(yīng)用,所有APP進程都是由zygote進程fork出來的

這些層之間,有的并不能直接交流,比如Native與Kernel之間要經(jīng)過系統(tǒng)調(diào)用才能訪問,Java層和Native層需要通過JNI進行調(diào)用,嚴格來說,Android系統(tǒng)實際上是運行于Linux內(nèi)核上的一系列服務(wù)進程,這些進程是維持設(shè)備正常運行的關(guān)鍵,當(dāng)內(nèi)核啟動完成后,就會創(chuàng)建用戶空間的第一個進程,即init進程,當(dāng)init進程啟動后會調(diào)用/system/core/init/Init.cpp的main()方法,分析和運行所有的init.rc文件,通過rc文件創(chuàng)建設(shè)備驅(qū)動節(jié)點,提供屬性服務(wù)等操作,Android系統(tǒng)是基于Linux內(nèi)核的,而在Linux系統(tǒng)中,所有的進程都是init進程的子進程,所有的進程都是直接或者間接地由init進程fork出來的。Zygote進程也是,它是在系統(tǒng)啟動的過程,由init進程創(chuàng)建的。在系統(tǒng)啟動腳本system/core/rootdir/init.xxx.rc文件中,init.zygote32.rc文件表示當(dāng)前的手機只配置有32位的Zygote,init.zygote32_64.rc文件表示當(dāng)前的Zygote同時配置有32位和64位,而且以32位為主Zygote,64位為次Zygote,主次是怎么區(qū)分的呢?就是從配置文件中的--socket-name屬性來區(qū)分的。另外兩個init.zygote64.rc、init.zygote64_32.rc分別表示只支持64位的Zygote和同時兩個支持,但是以64位為主。以init.zygote64_32.rc為例,我們可以看到啟動Zygote進程的腳本命令:

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
   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
   socket zygote_secondary stream 660 root system
   onrestart restart zygote
   writepid /dev/cpuset/foreground/tasks

service告訴init進程創(chuàng)建一個名為"zygote"的進程,這個zygote進程要執(zhí)行的程序是/system/bin/app_process64,還創(chuàng)建了一個名為zygote的unix domain socket,類型是stream,這個socket是為了后面IPC所用;上面可以看到還有一個zygote_secondary的進程,其實這是為了適配不同的abi型號
app_main.cpp文件中的main函數(shù),作為Zygote進行的啟動入口。app_main.cpp文件的目錄路徑為:frameworks\base\cmds\app_process64\app_main.cpp,它的main函數(shù)的源碼如下:

namespace android {

static void app_usage()
{
     fprintf(stderr,
         "Usage: app_process [java-options] cmd-dir start-class-name [options]   \n");
}

class AppRuntime : public AndroidRuntime
{
public:
AppRuntime(char* argBlockStart, const size_t argBlockLength)
    : AndroidRuntime(argBlockStart, argBlockLength)
    , mClass(NULL)
{
}

void setClassNameAndArgs(const String8& className, int argc, char * const *argv) {
    mClassName = className;
    for (int i = 0; i < argc; ++i) {
         mArgs.add(String8(argv[i]));
    }
}

virtual void onVmCreated(JNIEnv* env)
{
    if (mClassName.isEmpty()) {
        return; // Zygote. Nothing to do here.
    }

    /*
     * This is a little awkward because the JNI FindClass call uses the
     * class loader associated with the native method we're executing in.
     * If called in onStarted (from RuntimeInit.finishInit because we're
     * launching "am", for example), FindClass would see that we're calling
     * from a boot class' native method, and so wouldn't look for the class
     * we're trying to look up in CLASSPATH. Unfortunately it needs to,
     * because the "am" classes are not boot classes.
     *
     * The easiest fix is to call FindClass here, early on before we start
     * executing boot class Java code and thereby deny ourselves access to
     * non-boot classes.
     */
    char* slashClassName = toSlashClassName(mClassName.string());
    mClass = env->FindClass(slashClassName);
    if (mClass == NULL) {
        ALOGE("ERROR: could not find class '%s'\n", mClassName.string());
    }
    free(slashClassName);

    mClass = reinterpret_cast<jclass>(env->NewGlobalRef(mClass));
}

virtual void onStarted()
{
    sp<ProcessState> proc = ProcessState::self();
    ALOGV("App process: starting thread pool.\n");
    proc->startThreadPool();

    AndroidRuntime* ar = AndroidRuntime::getRuntime();
    ar->callMain(mClassName, mClass, mArgs);

    IPCThreadState::self()->stopProcess();
    hardware::IPCThreadState::self()->stopProcess();
}

virtual void onZygoteInit()
{
    sp<ProcessState> proc = ProcessState::self();
    ALOGV("App process: starting thread pool.\n");
    proc->startThreadPool();
}

virtual void onExit(int code)
{
    if (mClassName.isEmpty()) {
        // if zygote
        IPCThreadState::self()->stopProcess();
        hardware::IPCThreadState::self()->stopProcess();
    }

    AndroidRuntime::onExit(code);
}


String8 mClassName;
Vector<String8> mArgs;
jclass mClass;
};

}

using namespace android;

static size_t computeArgBlockSize(int argc, char* const argv[]) {
// TODO: This assumes that all arguments are allocated in
// contiguous memory. There isn't any documented guarantee
// that this is the case, but this is how the kernel does it
// (see fs/exec.c).
//
// Also note that this is a constant for "normal" android apps.
// Since they're forked from zygote, the size of their command line
// is the size of the zygote command line.
//
// We change the process name of the process by over-writing
// the start of the argument block (argv[0]) with the new name of
// the process, so we'd mysteriously start getting truncated process
// names if the zygote command line decreases in size.
uintptr_t start = reinterpret_cast<uintptr_t>(argv[0]);
uintptr_t end = reinterpret_cast<uintptr_t>(argv[argc - 1]);
end += strlen(argv[argc - 1]) + 1;
return (end - start);
}

 static void maybeCreateDalvikCache() {
 #if defined(__aarch64__)
static const char kInstructionSet[] = "arm64";
#elif defined(__x86_64__)
static const char kInstructionSet[] = "x86_64";
#elif defined(__arm__)
static const char kInstructionSet[] = "arm";
#elif defined(__i386__)
static const char kInstructionSet[] = "x86";
#elif defined (__mips__) && !defined(__LP64__)
static const char kInstructionSet[] = "mips";
#elif defined (__mips__) && defined(__LP64__)
static const char kInstructionSet[] = "mips64";
#else
#error "Unknown instruction set"
#endif
const char* androidRoot = getenv("ANDROID_DATA");
LOG_ALWAYS_FATAL_IF(androidRoot == NULL, "ANDROID_DATA environment variable unset");

char dalvikCacheDir[PATH_MAX];
const int numChars = snprintf(dalvikCacheDir, PATH_MAX,
        "%s/dalvik-cache/%s", androidRoot, kInstructionSet);
LOG_ALWAYS_FATAL_IF((numChars >= PATH_MAX || numChars < 0),
        "Error constructing dalvik cache : %s", strerror(errno));

int result = mkdir(dalvikCacheDir, 0711);
LOG_ALWAYS_FATAL_IF((result < 0 && errno != EEXIST),
        "Error creating cache dir %s : %s", dalvikCacheDir, strerror(errno));

// We always perform these steps because the directory might
// already exist, with wider permissions and a different owner
// than we'd like.
result = chown(dalvikCacheDir, AID_ROOT, AID_ROOT);
LOG_ALWAYS_FATAL_IF((result < 0), "Error changing dalvik-cache ownership : %s", strerror(errno));

result = chmod(dalvikCacheDir, 0711);
LOG_ALWAYS_FATAL_IF((result < 0),
        "Error changing dalvik-cache permissions : %s", strerror(errno));
}

 #if defined(__LP64__)
 static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist64";
 static const char ZYGOTE_NICE_NAME[] = "zygote64";
 #else
 static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist32";
 static const char ZYGOTE_NICE_NAME[] = "zygote";
 #endif

 int main(int argc, char* const argv[])
 {
if (!LOG_NDEBUG) {
  String8 argv_String;
  for (int i = 0; i < argc; ++i) {
    argv_String.append("\"");
    argv_String.append(argv[i]);
    argv_String.append("\" ");
  }
  ALOGV("app_process main with argv: %s", argv_String.string());
}

AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
// Process command line arguments
// ignore argv[0]
argc--;
argv++;

// Everything up to '--' or first non '-' arg goes to the vm.
//
// The first argument after the VM args is the "parent dir", which
// is currently unused.
//
// After the parent dir, we expect one or more the following internal
// arguments :
//
// --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.
//
// For non zygote starts, these arguments will be followed by
// the main class name. All remaining arguments are passed to
// the main method of this class.
//
// For zygote starts, all remaining arguments are passed to the zygote.
// main function.
//
// Note that we must copy argument string values since we will rewrite the
// entire argument block when we apply the nice name to argv0.
//
// As an exception to the above rule, anything in "spaced commands"
// goes to the vm even though it has a space in it.
const char* spaced_commands[] = { "-cp", "-classpath" };
// Allow "spaced commands" to be succeeded by exactly 1 argument (regardless of -s).
bool known_command = false;

int i;
for (i = 0; i < argc; i++) {
    if (known_command == true) {
      runtime.addOption(strdup(argv[i]));
      ALOGV("app_process main add known option '%s'", argv[i]);
      known_command = false;
      continue;
    }

    for (int j = 0;
         j < static_cast<int>(sizeof(spaced_commands) / sizeof(spaced_commands[0]));
         ++j) {
      if (strcmp(argv[i], spaced_commands[j]) == 0) {
        known_command = true;
        ALOGV("app_process main found known command '%s'", argv[i]);
      }
    }

    if (argv[i][0] != '-') {
        break;
    }
    if (argv[i][1] == '-' && argv[i][2] == 0) {
        ++i; // Skip --.
        break;
    }

    runtime.addOption(strdup(argv[i]));
    ALOGV("app_process main add option '%s'", argv[i]);
}

// Parse runtime arguments.  Stop at first unrecognized option.
bool zygote = false;
bool startSystemServer = false;
bool application = false;
String8 niceName;
String8 className;

++i;  // Skip unused "parent dir" argument.
while (i < argc) {
    const char* arg = argv[i++];
    if (strcmp(arg, "--zygote") == 0) {
        zygote = true;
        niceName = ZYGOTE_NICE_NAME;
    } 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.setTo(arg + 12);
    } else if (strncmp(arg, "--", 2) != 0) {
        className.setTo(arg);
        break;
    } else {
        --i;
        break;
    }
}

Vector<String8> args;
if (!className.isEmpty()) {
    // 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();

    if (startSystemServer) {
        args.add(String8("start-system-server"));
    }

    char prop[PROP_VALUE_MAX];
    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);
        return 11;
    }

    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]));
    }
}

if (!niceName.isEmpty()) {
    runtime.setArgv0(niceName.string(), true /* setProcName */);
}

if (zygote) {
    runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
} else if (className) {
    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.");
}
}

這是app_main.cpp c++的全部代碼,這個方法首先創(chuàng)建一個AppRuntime對象,然后解析啟動參數(shù)argc、argv[],接著while循環(huán),如果配置的啟動參數(shù)為--zygote,表示要啟動Zygote進程,如果為--start-system-server表示要啟動SystemServer進程,如果為--application就表示是普通的應(yīng)用進程。我們當(dāng)前的場景中就是第一個,參數(shù)解析完成后,此時的局部變量zygote的值為true,最后的if/else分支就會執(zhí)行runtime.start("com.android.internal.os.ZygoteInit", args, zygote)來繼續(xù)完成Zygote進行的啟動,AppRuntime是AndroidRuntime類的子類,構(gòu)造方法中沒有任何邏輯。那我們接著來看看繼續(xù)分析app_main文件中的main函數(shù)的最后一句runtime.start("com.android.internal.os.ZygoteInit", args, zygote)來看看Zygote進行是如何啟動起來的。runtime對象就是AppRuntime,它沒有重寫start方法,所以會執(zhí)行父類AndroidRuntime類的start方法,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) {
       /* 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");
//ALOGD("Found LD_ASSUME_KERNEL='%s'\n", kernelHack);

/* start the virtual machine */
JniInvocation jni_invocation;
jni_invocation.Init(NULL);
JNIEnv* env;
if (startVm(&mJavaVM, &env, zygote) != 0) {
    return;
}
onVmCreated(env);

/*
 * Register android functions.
 */
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;

stringClass = env->FindClass("java/lang/String");
assert(stringClass != NULL);
strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
assert(strArray != NULL);
classNameStr = env->NewStringUTF(className);
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);
}

/*
 * 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) {
    ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
    /* keep going */
} else {
    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 {
        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");
}

這個方法的第一個參數(shù)是啟動類的類路徑全名即com.android.internal.os.ZygoteInit,第二個參數(shù)options就是之前解析好的啟動參數(shù),第三個zygote則是否要啟動Zygote進程,此時值為true,接下來就調(diào)用startVm啟動虛擬機,然后執(zhí)行onVmCreated方法:

 void AndroidRuntime::onVmCreated(JNIEnv* env)
{
// If AndroidRuntime had anything to do here, we'd have done it in 'start'.
}   

此方法在AndroidRuntime類中的實現(xiàn)為空,
接下來就執(zhí)行startReg方法,注冊android功能。

int AndroidRuntime::startReg(JNIEnv* env)
{
ATRACE_NAME("RegisterAndroidNatives");
/*
 * This hook causes all future threads created in this process to be
 * attached to the JavaVM.  (This needs to go away in favor of JNI
 * Attach calls.)
 */
androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);

ALOGV("--- registering native functions ---\n");

/*
 * Every "register" function calls one or more things that return
 * a local reference (e.g. FindClass).  Because we haven't really
 * started the VM yet, they're all getting stored in the base frame
 * and never released.  Use Push/Pop to manage the storage.
 */
env->PushLocalFrame(200);

if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
    env->PopLocalFrame(NULL);
    return -1;
}
env->PopLocalFrame(NULL);

//createJavaThread("fubar", quickTest, (void*) "hello");

return 0;
}

調(diào)用register_jni_procs方法把AndroidRuntime.cpp文件中定義的RegJNIRec gRegJNI[]數(shù)組中的所有方法都注冊 :

static const RegJNIRec gRegJNI[] = {

REG_JNI(register_com_android_internal_os_RuntimeInit),
REG_JNI(register_com_android_internal_os_ZygoteInit),
REG_JNI(register_android_os_SystemClock),
REG_JNI(register_android_util_EventLog),
REG_JNI(register_android_util_Log),
REG_JNI(register_android_util_MemoryIntArray),
REG_JNI(register_android_util_PathParser),
REG_JNI(register_android_app_admin_SecurityLog),
REG_JNI(register_android_content_AssetManager),
REG_JNI(register_android_content_StringBlock),
REG_JNI(register_android_content_XmlBlock),
REG_JNI(register_android_text_AndroidCharacter),
REG_JNI(register_android_text_StaticLayout),
REG_JNI(register_android_text_AndroidBidi),
REG_JNI(register_android_view_InputDevice),
REG_JNI(register_android_view_KeyCharacterMap),
REG_JNI(register_android_os_Process),
REG_JNI(register_android_os_SystemProperties)

...

}

總結(jié)一下Zygote native 進程做了哪些事情:

  • 創(chuàng)建虛擬機–startVM
  • 注冊JNI函數(shù)–startReg
  • 通過JNI知道Java層的com.android.internal.os.ZygoteInit 類,調(diào)用main 函數(shù),接下來從native層回調(diào)到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用的socket. 基于AF_UNIX類型,是一個本機socket
        zygoteServer.registerServerSocket(socketName);
        // 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());
                
              // 預(yù)加載類和資源
            preload(bootTimingsTraceLog);
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
                SystemClock.uptimeMillis());
            bootTimingsTraceLog.traceEnd(); // ZygotePreload
        } else {
            Zygote.resetNicePriority();
        

        // Finish profiling the zygote initialization.
        SamplingProfilerIntegration.writeZygoteSnapshot();

        // Do an initial gc to clean up after startup
        bootTimingsTraceLog.traceBegin("PostZygoteInitGC");
        gcAndFinalize();
        bootTimingsTraceLog.traceEnd(); // PostZygoteInitGC

        bootTimingsTraceLog.traceEnd(); // ZygoteInit
        // Disable tracing so that forked processes do not inherit stale tracing tags from
        // Zygote.
        Trace.setTracingEnabled(false);

        // Zygote process unmounts root storage spaces.
        Zygote.nativeUnmountStorageOnInit();

        // Set seccomp policy
        Seccomp.setPolicy();

        ZygoteHooks.stopZygoteNoThreadCreation();
       //請求 fork systemserver進程
        if (startSystemServer) {
            startSystemServer(abiList, socketName, zygoteServer);
        }

        Log.i(TAG, "Accepting command socket connections");
        zygoteServer.runSelectLoop(abiList);

        zygoteServer.closeServerSocket();
    } catch (Zygote.MethodAndArgsCaller caller) {
        caller.run();
    } catch (Throwable ex) {
        Log.e(TAG, "System zygote died with exception", ex);
        zygoteServer.closeServerSocket();
        throw ex;
    }
    }

構(gòu)造一個ZygoteServer對象,注冊zygote用的socket,

zygoteServer.registerServerSocket(socketName);

    void registerServerSocket(String socketName) {
      if (mServerSocket == null) {
          int fileDesc;
          final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
          try {
            String env = System.getenv(fullSocketName);
            fileDesc = Integer.parseInt(env);
          } catch (RuntimeException ex) {
            throw new RuntimeException(fullSocketName + " unset or invalid", ex);
          }

          try {
              FileDescriptor fd = new FileDescriptor();
              fd.setInt$(fileDesc);
              mServerSocket = new LocalServerSocket(fd);
          } catch (IOException ex) {
              throw new RuntimeException(
                      "Error binding to local socket '" + fileDesc + "'", ex);
          }
      }
    }

在這里實例化一個LocalServerSocket,zygote就可以作為服務(wù)端,不斷的獲取其它進程發(fā)送過來的請求

ZygoteInit.preload預(yù)加載資源

   static void preload(TimingsTraceLog bootTimingsTraceLog) {
    Log.d(TAG, "begin preload");
    bootTimingsTraceLog.traceBegin("BeginIcuCachePinning");
    beginIcuCachePinning();
    bootTimingsTraceLog.traceEnd(); // BeginIcuCachePinning
    bootTimingsTraceLog.traceBegin("PreloadClasses");
     //預(yù)加載位于/system/etc/preloaded-classes文件中的類
    preloadClasses();
    bootTimingsTraceLog.traceEnd(); // PreloadClasses
    bootTimingsTraceLog.traceBegin("PreloadResources");
    //預(yù)加載資源,包含drawable和color資源
    preloadResources();
    bootTimingsTraceLog.traceEnd(); // PreloadResources
    Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadAppProcessHALs");
    nativePreloadAppProcessHALs();
    Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
    Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadOpenGL");
    preloadOpenGL();
    Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
    preloadSharedLibraries();
    preloadTextResources();
    // Ask the WebViewFactory to do any initialization that must run in the zygote process,
    // for memory sharing purposes.
    //僅用于zygote進程,用于內(nèi)存共享的進程
    WebViewFactory.prepareWebViewInZygote();
    endIcuCachePinning();
    warmUpJcaProviders();
    Log.d(TAG, "end preload");

    sPreloadComplete = true;
}

執(zhí)行Zygote進程的初始化,對于類加載,采用反射機制Class.forName()方法來加載。對于資源加載,主要是 com.android.internal.R.array.preloaded_drawables和com.android.internal.R.array.preloaded_color_state_lists,在應(yīng)用程序中以com.android.internal.R.xxx開頭的資源,便是此時由Zygote加載到內(nèi)存的,

ZygoteInit.runSelectLoop

 Runnable runSelectLoop(String abiList) {
    ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
    ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();

    fds.add(mServerSocket.getFileDescriptor());
    peers.add(null);

    while (true) {
        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;
            }

            if (i == 0) {
                ZygoteConnection newPeer = acceptCommandPeer(abiList);
                peers.add(newPeer);
                fds.add(newPeer.getFileDesciptor());
            } else {
                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) {
                       
                        Slog.e(TAG, "Exception executing zygote command: ", e);

                        
                        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;
                    }
                }
            }
        }
    }
}

調(diào)用runSelectLoop()無限輪詢來等待Activity管理服務(wù)ActivityManagerService請求ZygoteConnection.processOneCommand(this)創(chuàng)建新的應(yīng)用程序進程:

      Runnable processOneCommand(ZygoteServer zygoteServer) {
    String args[];
    Arguments parsedArgs = null;
    FileDescriptor[] descriptors;

    try {
        args = readArgumentList();
        descriptors = mSocket.getAncillaryFileDescriptors();
    } catch (IOException ex) {
        throw new IllegalStateException("IOException on command socket", ex);
    }

    // readArgumentList returns null only when it has reached EOF with no available
    // data to read. This will only happen when the remote socket has disconnected.
    if (args == null) {
        isEof = true;
        return null;
    }

    int pid = -1;
    FileDescriptor childPipeFd = null;
    FileDescriptor serverPipeFd = null;

    parsedArgs = new Arguments(args);

    if (parsedArgs.abiListQuery) {
        handleAbiListQuery();
        return null;
    }

    if (parsedArgs.preloadDefault) {
        handlePreload();
        return null;
    }

    if (parsedArgs.preloadPackage != null) {
        handlePreloadPackage(parsedArgs.preloadPackage, parsedArgs.preloadPackageLibs,
                parsedArgs.preloadPackageCacheKey);
        return null;
    }

    if (parsedArgs.permittedCapabilities != 0 || parsedArgs.effectiveCapabilities != 0) {
        throw new ZygoteSecurityException("Client may not specify capabilities: " +
                "permitted=0x" + Long.toHexString(parsedArgs.permittedCapabilities) +
                ", effective=0x" + Long.toHexString(parsedArgs.effectiveCapabilities));
    }

    applyUidSecurityPolicy(parsedArgs, peer);
    applyInvokeWithSecurityPolicy(parsedArgs, peer);

    applyDebuggerSystemProperty(parsedArgs);
    applyInvokeWithSystemProperty(parsedArgs);

    int[][] rlimits = null;

    if (parsedArgs.rlimits != null) {
        rlimits = parsedArgs.rlimits.toArray(intArray2d);
    }

    int[] fdsToIgnore = null;

    if (parsedArgs.invokeWith != null) {
        try {
            FileDescriptor[] pipeFds = Os.pipe2(O_CLOEXEC);
            childPipeFd = pipeFds[1];
            serverPipeFd = pipeFds[0];
            Os.fcntlInt(childPipeFd, F_SETFD, 0);
            fdsToIgnore = new int[]{childPipeFd.getInt$(), serverPipeFd.getInt$()};
        } catch (ErrnoException errnoEx) {
            throw new IllegalStateException("Unable to set up pipe for invoke-with", errnoEx);
        }
    }

    /**
     * In order to avoid leaking descriptors to the Zygote child,
     * the native code must close the two Zygote socket descriptors
     * in the child process before it switches from Zygote-root to
     * the UID and privileges of the application being launched.
     *
     * In order to avoid "bad file descriptor" errors when the
     * two LocalSocket objects are closed, the Posix file
     * descriptors are released via a dup2() call which closes
     * the socket and substitutes an open descriptor to /dev/null.
     */

    int [] fdsToClose = { -1, -1 };

    FileDescriptor fd = mSocket.getFileDescriptor();

    if (fd != null) {
        fdsToClose[0] = fd.getInt$();
    }

    fd = zygoteServer.getServerSocketFileDescriptor();

    if (fd != null) {
        fdsToClose[1] = fd.getInt$();
    }

    fd = null;

    pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
            parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
            parsedArgs.niceName, fdsToClose, fdsToIgnore, parsedArgs.instructionSet,
            parsedArgs.appDataDir);

    try {
        if (pid == 0) {
            // in child
            zygoteServer.setForkChild();

            zygoteServer.closeServerSocket();
            IoUtils.closeQuietly(serverPipeFd);
            serverPipeFd = null;

            return handleChildProc(parsedArgs, descriptors, childPipeFd);
        } else {
            // In the parent. A pid < 0 indicates a failure and will be handled in
            // handleParentProc.
            IoUtils.closeQuietly(childPipeFd);
            childPipeFd = null;
            handleParentProc(pid, descriptors, serverPipeFd);
            return null;
        }
    } finally {
        IoUtils.closeQuietly(childPipeFd);
        IoUtils.closeQuietly(serverPipeFd);
    }
}

接收客戶端發(fā)送過來的connect()操作,Zygote作為服務(wù)端執(zhí)行accept()操作。 再后面客戶端調(diào)用write()寫數(shù)據(jù),Zygote進程調(diào)用read()讀數(shù)據(jù)。沒有連接請求時會進入休眠狀態(tài),當(dāng)有創(chuàng)建新進程的連接請求時,喚醒Zygote進程,創(chuàng)建Socket通道ZygoteConnection,然后執(zhí)行ZygoteConnection的processOneCommand()方法。

Zygote總結(jié):

解析init.zygote.rc中的參數(shù),創(chuàng)建AppRuntime并調(diào)用AppRuntime.start()方法
調(diào)用AndroidRuntime的startVM()方法創(chuàng)建虛擬機,再調(diào)用startReg()注冊JNI函數(shù)
通過JNI方式調(diào)用ZygoteInit.main(),第一次進入Java世界
registerZygoteSocket()建立socket通道,zygote作為通信的服務(wù)端,用于響應(yīng)客戶端請求
preload()預(yù)加載通用類、drawable和color資源、openGL以及共享庫以及WebView,用于提高app啟動效率
通過startSystemServer(),fork得力幫手system_server進程,
調(diào)用runSelectLoop(),隨時待命,當(dāng)接收到請求創(chuàng)建新進程請求時立即喚醒并執(zhí)行相應(yīng)工作

System Server 進程

巴拉巴拉一大堆,通過調(diào)用startSystemServer去fork system server process

  /**
 * Prepare the arguments and fork for the system server process.
 */
private static boolean startSystemServer(String abiList, String socketName, ZygoteServer zygoteServer)
        throws Zygote.MethodAndArgsCaller, RuntimeException {
    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
    );
    /* Containers run without this capability, so avoid setting it in that case */
    if (!SystemProperties.getBoolean(PROPERTY_RUNNING_IN_CONTAINER, false)) {
        capabilities |= posixCapabilitiesAsBits(OsConstants.CAP_BLOCK_SUSPEND);
    }
    /* 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,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 */
        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) {
        if (hasSecondZygote(abiList)) {
            waitForSecondaryZygote(socketName);
        }

        zygoteServer.closeServerSocket();
        handleSystemServerProcess(parsedArgs);
    }

    return true;
}   

Zygote.forkSystemServer

  public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags,
        int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
    VM_HOOKS.preFork();
    // Resets nice priority for zygote process.
    resetNicePriority();
    
     // 調(diào)用native方法fork system_server進程
    int pid = nativeForkSystemServer(
            uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);
    // Enable tracing as soon as we enter the system_server.
    if (pid == 0) {
        Trace.setTracingEnabled(true, debugFlags);
    }
    VM_HOOKS.postForkCommon();
    return pid;
}

nativeForkSystemServer()方法在AndroidRuntime.cpp中注冊的(com_android_internal_os_Zygote),調(diào)用com_android_internal_os_Zygote.cpp中的register_com_android_internal_os_Zygote()方法建立native方法的映射關(guān)系,接下來進入如下方法

    static jint com_android_internal_os_Zygote_nativeForkSystemServer(
    JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
    jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
    jlong effectiveCapabilities) {
   pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
                                  debug_flags, rlimits,
                                  permittedCapabilities, effectiveCapabilities,
                                  MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
                                  NULL, NULL, NULL);
 if (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!");
     }
  }
   return pid;
  }    


  
  
  
  
  
  
  
  // Utility routine to fork zygote and specialize the child process.
 static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
                                 jint debug_flags, jobjectArray javaRlimits,
                                 jlong permittedCapabilities, jlong effectiveCapabilities,
                                 jint mount_external,
                                 jstring java_se_info, jstring java_se_name,
                                 bool is_system_server, jintArray fdsToClose,
                                 jintArray fdsToIgnore,
                                 jstring instructionSet, jstring dataDir) {
 SetSigChldHandler();

 sigset_t sigchld;
 sigemptyset(&sigchld);
 sigaddset(&sigchld, SIGCHLD);

 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
 // log, which would result in the logging FDs we close being reopened.
 // This would cause failures because the FDs are not whitelisted.
//
 // Note that the zygote process is single threaded at this point.
 if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) {
ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno));
RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_BLOCK, { SIGCHLD }) failed.");
   }


  std::vector<int> fds_to_ignore;
   FillFileDescriptorVector(env, fdsToIgnore, &fds_to_ignore);
 if (gOpenFdTable == NULL) {
gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore);
if (gOpenFdTable == NULL) {
  RuntimeAbort(env, __LINE__, "Unable to construct file descriptor table.");
}
 } else if (!gOpenFdTable->Restat(fds_to_ignore)) {
RuntimeAbort(env, __LINE__, "Unable to restat file descriptor table.");
}

pid_t pid = fork();

if (pid == 0) {
// The child process.
gMallocLeakZygoteChild = 1;

// Set the jemalloc decay time to 1.
mallopt(M_DECAY_TIME, 1);

// Clean up any descriptors which must be closed immediately
DetachDescriptors(env, fdsToClose);

// Re-open all remaining open file descriptors so that they aren't shared
// with the zygote across a fork.
if (!gOpenFdTable->ReopenOrDetach()) {
  RuntimeAbort(env, __LINE__, "Unable to reopen whitelisted descriptors.");
}

if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
  ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno));
  RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_UNBLOCK, { SIGCHLD }) failed.");
}

// Keep capabilities across UID change, unless we're staying root.
if (uid != 0) {
  EnableKeepCapabilities(env);
}

SetInheritable(env, permittedCapabilities);
DropCapabilitiesBoundingSet(env);

bool use_native_bridge = !is_system_server && (instructionSet != NULL)
    && android::NativeBridgeAvailable();
if (use_native_bridge) {
  ScopedUtfChars isa_string(env, instructionSet);
  use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
}
if (use_native_bridge && dataDir == NULL) {
  // dataDir should never be null if we need to use a native bridge.
  // In general, dataDir will never be null for normal applications. It can only happen in
  // special cases (for isolated processes which are not associated with any app). These are
  // launched by the framework and should not be emulated anyway.
  use_native_bridge = false;
  ALOGW("Native bridge will not be used because dataDir == NULL.");
}

if (!MountEmulatedStorage(uid, mount_external, use_native_bridge)) {
  ALOGW("Failed to mount emulated storage: %s", strerror(errno));
  if (errno == ENOTCONN || errno == EROFS) {
    // When device is actively encrypting, we get ENOTCONN here
    // since FUSE was mounted before the framework restarted.
    // When encrypted device is booting, we get EROFS since
    // FUSE hasn't been created yet by init.
    // In either case, continue without external storage.
  } else {
    RuntimeAbort(env, __LINE__, "Cannot continue without emulated storage");
  }
}

if (!is_system_server) {
    int rc = createProcessGroup(uid, getpid());
    if (rc != 0) {
        if (rc == -EROFS) {
            ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
        } else {
            ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc));
        }
    }
}

SetGids(env, javaGids);

SetRLimits(env, javaRlimits);

if (use_native_bridge) {
  ScopedUtfChars isa_string(env, instructionSet);
  ScopedUtfChars data_dir(env, dataDir);
  android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
}

int rc = setresgid(gid, gid, gid);
if (rc == -1) {
  ALOGE("setresgid(%d) failed: %s", gid, strerror(errno));
  RuntimeAbort(env, __LINE__, "setresgid failed");
}

rc = setresuid(uid, uid, uid);
if (rc == -1) {
  ALOGE("setresuid(%d) failed: %s", uid, strerror(errno));
  RuntimeAbort(env, __LINE__, "setresuid failed");
}

if (NeedsNoRandomizeWorkaround()) {
    // Work around ARM kernel ASLR lossage (http://b/5817320).
    int old_personality = personality(0xffffffff);
    int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
    if (new_personality == -1) {
        ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
    }
}

SetCapabilities(env, permittedCapabilities, effectiveCapabilities, permittedCapabilities);

SetSchedulerPolicy(env);

const char* se_info_c_str = NULL;
ScopedUtfChars* se_info = NULL;
if (java_se_info != NULL) {
    se_info = new ScopedUtfChars(env, java_se_info);
    se_info_c_str = se_info->c_str();
    if (se_info_c_str == NULL) {
      RuntimeAbort(env, __LINE__, "se_info_c_str == NULL");
    }
}
const char* se_name_c_str = NULL;
ScopedUtfChars* se_name = NULL;
if (java_se_name != NULL) {
    se_name = new ScopedUtfChars(env, java_se_name);
    se_name_c_str = se_name->c_str();
    if (se_name_c_str == NULL) {
      RuntimeAbort(env, __LINE__, "se_name_c_str == NULL");
    }
}
rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
if (rc == -1) {
  ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
        is_system_server, se_info_c_str, se_name_c_str);
  RuntimeAbort(env, __LINE__, "selinux_android_setcontext failed");
}

// Make it easier to debug audit logs by setting the main thread's name to the
// nice name rather than "app_process".
if (se_info_c_str == NULL && is_system_server) {
  se_name_c_str = "system_server";
}
if (se_info_c_str != NULL) {
  SetThreadName(se_name_c_str);
}

delete se_info;
delete se_name;

UnsetSigChldHandler();

env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
                          is_system_server, instructionSet);
if (env->ExceptionCheck()) {
  RuntimeAbort(env, __LINE__, "Error calling post fork hooks.");
}
} else if (pid > 0) {
// the parent process

// We blocked SIGCHLD prior to a fork, we unblock it here.
if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) {
  ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno));
  RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_UNBLOCK, { SIGCHLD }) failed.");
 }
 }
  return pid;
   }
 }  // anonymous namespace    

fork()采用copy on write技術(shù),這是linux創(chuàng)建進程的標(biāo)準(zhǔn)方法,調(diào)用一次,返回兩次,返回值有3種類型

  • 父進程中,fork返回新創(chuàng)建的子進程的pid;
  • 子進程中,fork返回0;
  • 當(dāng)出現(xiàn)錯誤時,fork返回負數(shù)。(當(dāng)進程數(shù)超過上限或者系統(tǒng)內(nèi)存不足時會出錯)

主要工作是尋找空閑的進程號pid,然后從父進程拷貝進程信息,例如數(shù)據(jù)段和代碼段,fork()后子進程要執(zhí)行的代碼等。 Zygote進程是所有Android進程的母體,包括system_server和各個App進程。zygote利用fork()方法生成新進程,對于新進程A復(fù)用Zygote進程本身的資源,再加上新進程A相關(guān)的資源,構(gòu)成新的應(yīng)用進程A ,fork之后,操作系統(tǒng)會復(fù)制一個與父進程完全相同的子進程,雖說是父子關(guān)系,但是在操作系統(tǒng)看來,他們更像兄弟關(guān)系,這2個進程共享代碼空間,但是數(shù)據(jù)空間是互相獨立的,子進程數(shù)據(jù)空間中的內(nèi)容是父進程的完整拷貝,指令指針也完全相同,子進程擁有父進程當(dāng)前運行到的位置(兩進程的程序計數(shù)器pc值相同,也就是說,子進程是從fork返回處開始執(zhí)行的),但有一點不同,如果fork成功,子進程中fork的返回值是0,父進程中fork的返回值是子進程的進程號,如果fork不成功,父進程會返回錯誤。
可以這樣想象,2個進程一直同時運行,而且步調(diào)一致,在fork之后,他們就開始分別作不同的工作,正如fork原意【分支】一樣

system_server進程已完成了創(chuàng)建,接下來開始了system_server進程的工作。執(zhí)行完forkSystemServer()后,新創(chuàng)建system_server進程便進入handleSystemServerProcess()
首先會關(guān)閉Zygote的socket,并設(shè)置SystemServer進程的一些參數(shù),然后調(diào)用RuntimeInit.java中的ZygoteInit函數(shù)。

   /**
 * Finish remaining work for the newly forked system server process.
 */
private static void handleSystemServerProcess(
        ZygoteConnection.Arguments parsedArgs)
        throws Zygote.MethodAndArgsCaller {

    // set umask to 0077 so new files and directories will default to owner-only permissions.
    Os.umask(S_IRWXG | S_IRWXO);

    if (parsedArgs.niceName != null) {
        Process.setArgV0(parsedArgs.niceName);
    }

    final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
    if (systemServerClasspath != null) {
        performSystemServerDexOpt(systemServerClasspath);
        // Capturing profiles is only supported for debug or eng builds since selinux normally
        // prevents it.
        boolean profileSystemServer = SystemProperties.getBoolean(
                "dalvik.vm.profilesystemserver", false);
        if (profileSystemServer && (Build.IS_USERDEBUG || Build.IS_ENG)) {
            try {
                File profileDir = Environment.getDataProfilesDePackageDirectory(
                        Process.SYSTEM_UID, "system_server");
                File profile = new File(profileDir, "primary.prof");
                profile.getParentFile().mkdirs();
                profile.createNewFile();
                String[] codePaths = systemServerClasspath.split(":");
                VMRuntime.registerAppInfo(profile.getPath(), codePaths);
            } catch (Exception e) {
                Log.wtf(TAG, "Failed to set up system server profile", e);
            }
        }
    }

    if (parsedArgs.invokeWith != null) {
        String[] args = parsedArgs.remainingArgs;
        // If we have a non-null system server class path, we'll have to duplicate the
        // existing arguments and append the classpath to it. ART will handle the classpath
        // correctly when we exec a new process.
        if (systemServerClasspath != null) {
            String[] amendedArgs = new String[args.length + 2];
            amendedArgs[0] = "-cp";
            amendedArgs[1] = systemServerClasspath;
            System.arraycopy(args, 0, amendedArgs, 2, args.length);
            args = amendedArgs;
        }

        WrapperInit.execApplication(parsedArgs.invokeWith,
                parsedArgs.niceName, parsedArgs.targetSdkVersion,
                VMRuntime.getCurrentInstructionSet(), null, args);
    } else {
        ClassLoader cl = null;
        if (systemServerClasspath != null) {
            cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);

            Thread.currentThread().setContextClassLoader(cl);
        }

        /*
         * Pass the remaining arguments to SystemServer.
         */
        ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
    }

    /* should never reach here */
}

調(diào)用 ZygoteInit.zygoteInit方法

 public static final void zygoteInit(int targetSdkVersion, String[] argv,
        ClassLoader classLoader) throws Zygote.MethodAndArgsCaller {
    if (RuntimeInit.DEBUG) {
        Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
    }

    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
    RuntimeInit.redirectLogStreams();

    RuntimeInit.commonInit();
    ZygoteInit.nativeZygoteInit();
    RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}

最后看看 RuntimeInit.applicationInit;

  protected static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
        throws Zygote.MethodAndArgsCaller {
    // If the application calls System.exit(), terminate the process
    // immediately without running any shutdown hooks.  It is not possible to
    // shutdown an Android application gracefully.  Among other things, the
    // Android runtime shutdown hooks close the Binder driver, which can cause
    // leftover running threads to crash before the process actually exits.
    nativeSetExitWithoutCleanup(true);

    // We want to be fairly aggressive about heap utilization, to avoid
    // holding on to a lot of memory that isn't needed.
    VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
    VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);

    final Arguments args;
    try {
        args = new Arguments(argv);
    } catch (IllegalArgumentException ex) {
        Slog.e(TAG, ex.getMessage());
        // let the process exit
        return;
    }

    // The end of of the RuntimeInit event (see #zygoteInit).
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

    // Remaining arguments are passed to the start class's static main
    // // 調(diào)用com.android.server.SystemServer類的main函數(shù)
    invokeStaticMain(args.startClass, args.startArgs, classLoader);
}

通過反射機制調(diào)用的是SystemServer.main()方法,SystemServer.run函數(shù)中初始化各種服務(wù)

// Start services.
    try {
        traceBeginAndSlog("StartServices");
        startBootstrapServices();
        startCoreServices();
        startOtherServices();
        SystemServerInitThreadPool.shutdown();
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    } finally {
        traceEnd();
    }

system server進程總結(jié):

zygote進程通過Zygote.forkSystemServer —> fork.fork()創(chuàng)建system server進程
調(diào)用ZygoteInit.handleSystemServerProcess方法設(shè)置當(dāng)前進程名為"system_server",執(zhí)行dex優(yōu)化操作,一些屬性的初始化,設(shè)置binder線程
通過拋出MethodAndArgsCaller異常,回到ZygoteInit.main(),在try catch中執(zhí)行MethodAndArgsCaller.run;在這里通過反射執(zhí)行SystemServer.main()方法
在SystemServer.run方法中做一些設(shè)置,比如初始化系統(tǒng)上下文 ,創(chuàng)建SystemServiceManager,啟動引導(dǎo)服務(wù),啟動核心服務(wù),啟動其他服務(wù)
最后調(diào)用Looper.loop(),輪詢從消息隊列取出消息處理。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容