Android系统 init--> zygote-->system server进程启动流程分析

Android系统启动过程大概可以分为5步:

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

Boot ROM: 当手机处于关机状态时,长按电源键开机,引导芯片开始从固化在ROM里的预设出代码开始执行,然后加载引导程序到RAM
Boot Loader:这是启动Android系统之前的引导程序,主要是检查RAM,初始化硬件参数等功能

  • Kernel

Kernel层是指Android内核层, 到这里才刚刚开始进入Android系统,启动Kernel的swapper进程(pid=0):该进程又称为idle进程, 系统初始化过程Kernel由无到有开创的第一个进程, 用于初始化进程管理、内存管理,加载Display,Camera Driver,Binder Driver等相关工作,启动kthreadd进程(pid=2):是Linux系统的内核进程,会创建内核工作线程kworkder,软中断线程ksoftirqd,thermal等内核守护进程。kthreadd进程是所有内核进程的鼻祖

  • Native

这里的Native层主要包括init孵化来的用户空间的守护进程、HAL层以及开机动画等。启动init进程(pid=1),是Linux系统的用户进程,init进程是所有用户进程的鼻祖,init进程会孵化出ueventd、logd、healthd、installd、adbd、lmkd等用户守护进程,init进程还启动servicemanager(binder服务管家)、bootanim(开机动画)等重要服务,init进程孵化出Zygote进程,Zygote进程是Android系统的第一个Java进程(即虚拟机进程),Zygote是所有Java进程的父进程

  • Framework

Zygote进程启动后,加载ZygoteInit类,注册Zygote Socket服务端套接字;加载虚拟机;加载类,加载系统资源,System Server进程,是由Zygote进程fork而来,System Server是Zygote孵化的第一个进程,System Server负责启动和管理整个Java framework,包含ActivityManager,PowerManager等服务, Media Server进程,是由init进程fork而来,负责启动和管理整个C++ framework,包含AudioFlinger,Camera Service等服务

  • Application

    Zygote进程孵化出的第一个App进程是Launcher,即手机桌面APP,没错,手机桌面就是跟我们平时使用的APP一样,它也是一个应用,所有APP进程都是由zygote进程fork出来的

这些层之间,有的并不能直接交流,比如Native与Kernel之间要经过系统调用才能访问,Java层和Native层需要通过JNI进行调用,严格来说,Android系统实际上是运行于Linux内核上的一系列服务进程,这些进程是维持设备正常运行的关键,当内核启动完成后,就会创建用户空间的第一个进程,即init进程,当init进程启动后会调用/system/core/init/Init.cpp的main()方法,分析和运行所有的init.rc文件,通过rc文件创建设备驱动节点,提供属性服务等操作,Android系统是基于Linux内核的,而在Linux系统中,所有的进程都是init进程的子进程,所有的进程都是直接或者间接地由init进程fork出来的。Zygote进程也是,它是在系统启动的过程,由init进程创建的。在系统启动脚本system/core/rootdir/init.xxx.rc文件中,init.zygote32.rc文件表示当前的手机只配置有32位的Zygote,init.zygote32_64.rc文件表示当前的Zygote同时配置有32位和64位,而且以32位为主Zygote,64位为次Zygote,主次是怎么区分的呢?就是从配置文件中的--socket-name属性来区分的。另外两个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进程创建一个名为"zygote"的进程,这个zygote进程要执行的程序是/system/bin/app_process64,还创建了一个名为zygote的unix domain socket,类型是stream,这个socket是为了后面IPC所用;上面可以看到还有一个zygote_secondary的进程,其实这是为了适配不同的abi型号
app_main.cpp文件中的main函数,作为Zygote进行的启动入口。app_main.cpp文件的目录路径为:frameworks\base\cmds\app_process64\app_main.cpp,它的main函数的源码如下:

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(env->NewGlobalRef(mClass));
}

virtual void onStarted()
{
    sp 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 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 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(argv[0]);
uintptr_t end = reinterpret_cast(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(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 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++的全部代码,这个方法首先创建一个AppRuntime对象,然后解析启动参数argc、argv[],接着while循环,如果配置的启动参数为--zygote,表示要启动Zygote进程,如果为--start-system-server表示要启动SystemServer进程,如果为--application就表示是普通的应用进程。我们当前的场景中就是第一个,参数解析完成后,此时的局部变量zygote的值为true,最后的if/else分支就会执行runtime.start("com.android.internal.os.ZygoteInit", args, zygote)来继续完成Zygote进行的启动,AppRuntime是AndroidRuntime类的子类,构造方法中没有任何逻辑。那我们接着来看看继续分析app_main文件中的main函数的最后一句runtime.start("com.android.internal.os.ZygoteInit", args, zygote)来看看Zygote进行是如何启动起来的。runtime对象就是AppRuntime,它没有重写start方法,所以会执行父类AndroidRuntime类的start方法,frameworks\base\core\jni\AndroidRuntime.cpp。

void AndroidRuntime::start(const char* className, const Vector& 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");
}

这个方法的第一个参数是启动类的类路径全名即com.android.internal.os.ZygoteInit,第二个参数options就是之前解析好的启动参数,第三个zygote则是否要启动Zygote进程,此时值为true,接下来就调用startVm启动虚拟机,然后执行onVmCreated方法:

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

此方法在AndroidRuntime类中的实现为空,
接下来就执行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;
}

调用register_jni_procs方法把AndroidRuntime.cpp文件中定义的RegJNIRec gRegJNI[]数组中的所有方法都注册 :

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)

...

}

总结一下Zygote native 进程做了哪些事情:

  • 创建虚拟机–startVM
  • 注册JNI函数–startReg
  • 通过JNI知道Java层的com.android.internal.os.ZygoteInit 类,调用main 函数,接下来从native层回调到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());
                
              // 预加载类和资源
            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;
    }
    }

构造一个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就可以作为服务端,不断的获取其它进程发送过来的请求

ZygoteInit.preload预加载资源

   static void preload(TimingsTraceLog bootTimingsTraceLog) {
    Log.d(TAG, "begin preload");
    bootTimingsTraceLog.traceBegin("BeginIcuCachePinning");
    beginIcuCachePinning();
    bootTimingsTraceLog.traceEnd(); // BeginIcuCachePinning
    bootTimingsTraceLog.traceBegin("PreloadClasses");
     //预加载位于/system/etc/preloaded-classes文件中的类
    preloadClasses();
    bootTimingsTraceLog.traceEnd(); // PreloadClasses
    bootTimingsTraceLog.traceBegin("PreloadResources");
    //预加载资源,包含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进程,用于内存共享的进程
    WebViewFactory.prepareWebViewInZygote();
    endIcuCachePinning();
    warmUpJcaProviders();
    Log.d(TAG, "end preload");

    sPreloadComplete = true;
}

执行Zygote进程的初始化,对于类加载,采用反射机制Class.forName()方法来加载。对于资源加载,主要是 com.android.internal.R.array.preloaded_drawables和com.android.internal.R.array.preloaded_color_state_lists,在应用程序中以com.android.internal.R.xxx开头的资源,便是此时由Zygote加载到内存的,

ZygoteInit.runSelectLoop

 Runnable runSelectLoop(String abiList) {
    ArrayList fds = new ArrayList();
    ArrayList peers = new ArrayList();

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

调用runSelectLoop()无限轮询来等待Activity管理服务ActivityManagerService请求ZygoteConnection.processOneCommand(this)创建新的应用程序进程:

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

接收客户端发送过来的connect()操作,Zygote作为服务端执行accept()操作。 再后面客户端调用write()写数据,Zygote进程调用read()读数据。没有连接请求时会进入休眠状态,当有创建新进程的连接请求时,唤醒Zygote进程,创建Socket通道ZygoteConnection,然后执行ZygoteConnection的processOneCommand()方法。

Zygote总结:

解析init.zygote.rc中的参数,创建AppRuntime并调用AppRuntime.start()方法
调用AndroidRuntime的startVM()方法创建虚拟机,再调用startReg()注册JNI函数
通过JNI方式调用ZygoteInit.main(),第一次进入Java世界
registerZygoteSocket()建立socket通道,zygote作为通信的服务端,用于响应客户端请求
preload()预加载通用类、drawable和color资源、openGL以及共享库以及WebView,用于提高app启动效率
通过startSystemServer(),fork得力帮手system_server进程,
调用runSelectLoop(),随时待命,当接收到请求创建新进程请求时立即唤醒并执行相应工作

System Server 进程

巴拉巴拉一大堆,通过调用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();
    
     // 调用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),调用com_android_internal_os_Zygote.cpp中的register_com_android_internal_os_Zygote()方法建立native方法的映射关系,接下来进入如下方法

    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 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技术,这是linux创建进程的标准方法,调用一次,返回两次,返回值有3种类型

  • 父进程中,fork返回新创建的子进程的pid;
  • 子进程中,fork返回0;
  • 当出现错误时,fork返回负数。(当进程数超过上限或者系统内存不足时会出错)

主要工作是寻找空闲的进程号pid,然后从父进程拷贝进程信息,例如数据段和代码段,fork()后子进程要执行的代码等。 Zygote进程是所有Android进程的母体,包括system_server和各个App进程。zygote利用fork()方法生成新进程,对于新进程A复用Zygote进程本身的资源,再加上新进程A相关的资源,构成新的应用进程A ,fork之后,操作系统会复制一个与父进程完全相同的子进程,虽说是父子关系,但是在操作系统看来,他们更像兄弟关系,这2个进程共享代码空间,但是数据空间是互相独立的,子进程数据空间中的内容是父进程的完整拷贝,指令指针也完全相同,子进程拥有父进程当前运行到的位置(两进程的程序计数器pc值相同,也就是说,子进程是从fork返回处开始执行的),但有一点不同,如果fork成功,子进程中fork的返回值是0,父进程中fork的返回值是子进程的进程号,如果fork不成功,父进程会返回错误。
可以这样想象,2个进程一直同时运行,而且步调一致,在fork之后,他们就开始分别作不同的工作,正如fork原意【分支】一样

system_server进程已完成了创建,接下来开始了system_server进程的工作。执行完forkSystemServer()后,新创建system_server进程便进入handleSystemServerProcess()
首先会关闭Zygote的socket,并设置SystemServer进程的一些参数,然后调用RuntimeInit.java中的ZygoteInit函数。

   /**
 * 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 */
}

调用 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
    // // 调用com.android.server.SystemServer类的main函数
    invokeStaticMain(args.startClass, args.startArgs, classLoader);
}

通过反射机制调用的是SystemServer.main()方法,SystemServer.run函数中初始化各种服务

// 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进程总结:

zygote进程通过Zygote.forkSystemServer —> fork.fork()创建system server进程
调用ZygoteInit.handleSystemServerProcess方法设置当前进程名为"system_server",执行dex优化操作,一些属性的初始化,设置binder线程
通过抛出MethodAndArgsCaller异常,回到ZygoteInit.main(),在try catch中执行MethodAndArgsCaller.run;在这里通过反射执行SystemServer.main()方法
在SystemServer.run方法中做一些设置,比如初始化系统上下文 ,创建SystemServiceManager,启动引导服务,启动核心服务,启动其他服务
最后调用Looper.loop(),轮询从消息队列取出消息处理。

你可能感兴趣的:(Android系统 init--> zygote-->system server进程启动流程分析)