Zygote

了解了init进程和init.rc之后,来看一下zygote。

init.rc文件中

service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
    class main
    socket zygote stream 660 root system
    onrestart write /sys/android_power/request_state wake
    onrestart write /sys/power/state on
    onrestart restart media
    onrestart restart netd
/system/bin/app_process -Xzygote /system/bin --zygote --start-system-server 程序位置及参数
/system/bin/app_process代码在frameworks/base/cmds/app_process/目录下,入口主函数是app_main.cpp的main()函数。

根据代码,设置了参数--zygote --start-system-server,最终会调用

AppRuntime runtime;
runtime.start("com.android.internal.os.ZygoteInit", "start-system-server");
AppRuntime也在app_main.cpp文件中定义,继承了AndroidRuntime
class AppRuntime : public AndroidRuntime
AndroidRuntime类在frameworks/base/core/jni/AndroidRuntime.cpp文件中定义。
/*
 * Start the Android runtime.  This involves starting the virtual machine
 * and calling the "static void main(String[] args)" method in the class
 * named by "className".
 *
 * Passes the main function two arguments, the class name and the specified
 * options string.
 */
void AndroidRuntime::start(const char* className, const char* options)
{
    /* start the virtual machine */
    JniInvocation jni_invocation;
    jni_invocation.Init(NULL);
    JNIEnv* env;
    if (startVm(&mJavaVM, &env) != 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;
    jstring optionsStr;

    stringClass = env->FindClass("java/lang/String");
    assert(stringClass != NULL);
    strArray = env->NewObjectArray(2, stringClass, NULL);
    assert(strArray != NULL);
    classNameStr = env->NewStringUTF(className);
    assert(classNameStr != NULL);
    env->SetObjectArrayElement(strArray, 0, classNameStr);
    optionsStr = env->NewStringUTF(options);
    env->SetObjectArrayElement(strArray, 1, optionsStr);

    /*
     * Start VM.  This thread becomes the main thread of the VM, and will
     * not return until the VM exits.
     */
    char* slashClassName = toSlashClassName(className);
    jclass startClass = env->FindClass(slashClassName);
    if (startClass == NULL) {
        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);
        }
    }
    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");
}

这个函数的作用是启动Android系统运行时库,它主要做了三件事情,

    一是调用函数startVM启动虚拟机,

    二是调用函数startReg注册JNI方法,

    三是调用了com.android.internal.os.ZygoteInit类的main函数。


frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

public static void main(String argv[]) {
    try {
        ......
        registerZygoteSocket();//创建一个socket接口,用来和ActivityManagerService通讯
        preload();

        // Do an initial gc to clean up after startup
        gc();

        if (argv[1].equals("start-system-server")) {
            startSystemServer();//启动SystemServer
        }
        //通过Select方式监听端口,即异步读取消息,死循环,没有消息则一直阻塞在那里。
        //在前面创建的socket接口上等待ActivityManagerService请求创建新的应用程序进程。
        runSelectLoop();
        closeServerSocket();
    } catch (MethodAndArgsCaller caller) {
        caller.run();
    } catch (RuntimeException ex) {
        ...
    }
}

startSystemServer() 创建SystemServer进程

/**
 * Prepare the arguments and fork for the system server process.
 */
private static boolean startSystemServer() throws MethodAndArgsCaller, RuntimeException {
    ...
    ZygoteConnection.Arguments parsedArgs = null;
    int pid;
    try {
        parsedArgs = new ZygoteConnection.Arguments(args);
        ...

        pid = Zygote.forkSystemServer(
                parsedArgs.uid, parsedArgs.gid,
                parsedArgs.gids,
                parsedArgs.debugFlags,
                null,
                parsedArgs.permittedCapabilities,
                parsedArgs.effectiveCapabilities);
    } catch (IllegalArgumentException ex) {
        throw new RuntimeException(ex);
    }

    /* For child process */
    if (pid == 0) {
        handleSystemServerProcess(parsedArgs);
    }
    return true;
}
startSystemServer()先配置启动参数ZygoteConnection.Arguments parsedArgs,然后调用Zygote.forkSystemServer()
libcore/dalvik/src/main/java/dalvik/system/Zygote.java
    forkSystemServer()
    nativeForkSystemServer()
dalvik/vm/native/dalvik_system_Zygote.cpp
    Dalvik_dalvik_system_Zygote_forkSystemServer()
    forkAndSpecializeCommon()
最终调用linux系统调用fork() 创建SystemServer进程。
pid = Zygote.forkSystemServer() 这里返回两个进程id,

1、父进程(Zygote)的返回值pid是创建的子进程的id,大于0,直接返回到ZygoteInit.main()函数中,继续执行runSelectLoop();

2、子进程(SystemServer)的返回值pid为0,会调用handleSystemServerProcess(parsedArgs);做一些初始化操作,最后调用到RuntimeInit.invokeStaticMain()函数。

frameworks/base/core/java/com/android/internal/os/RuntimeInit.java

private static void invokeStaticMain(String className, String[] argv)
        throws ZygoteInit.MethodAndArgsCaller {
    ......
    Class<?> cl;
    cl = Class.forName(className);
    Method m;
    m = cl.getMethod("main", new Class[] { String[].class });
    ......
    /*
     * This throw gets caught in ZygoteInit.main(), which responds
     * by invoking the exception's run() method. This arrangement
     * clears up all the stack frames that were required in setting
     * up the process.
     */
    throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}
抛出异常ZygoteInit.MethodAndArgsCaller,会返回到ZygoteInit.main()函数异常处理,执行caller.run();
根据ZygoteInit.startSystemServer()函数中的启动参数

/* 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,1032,3001,3002,3003,3006,3007",
    "--capabilities=" + capabilities + "," + capabilities,
    "--runtime-init",
    "--nice-name=system_server",
    "com.android.server.SystemServer",
};
caller.run()最终会调用到com.android.server.SystemServer的main()函数,即 SystemServer的入口函数。

到此,Zygote进程完成创建SystemServer进程,SystemServer进程由com.android.server.SystemServer.main()开始继续运行,而Zygote进程继续执行runSelectLoop()。


下面来看一下ZygoteInit.runSelectLoop()函数都做了什么。

private static void runSelectLoop() throws MethodAndArgsCaller {
    ...
    while (true) {//死循环,Zygote变为守护进程
        int index;
        ...
        try {
            fdArray = fds.toArray(fdArray);
            /*
             * selectReadable()函数的返回值有三种。
             *     -1: 代表着内部错误
             *      0: 代表着没有可处理的连接,因此会以Socket服务端口
             *         重新建立一个ZygoteConnection对象,并等待客户端的请求
             *     >0: 代表着还有没有处理完的连接请求,
             *         因此需要先处理该请求,而暂时不需要建立新的连接等待
             */
            index = selectReadable(fdArray);
        } catch (IOException ex) {
            throw new RuntimeException("Error in select()", ex);
        }
        if (index < 0) {
            throw new RuntimeException("Error in select()");
        } else if (index == 0) {//<span><span class="comment">构造一个ZygoteConnection对象,并将其加入到peers列表中</span></span>
            ZygoteConnection newPeer = acceptCommandPeer();
            peers.add(newPeer);
            fds.add(newPeer.getFileDesciptor());
        } else {//<span><span class="comment">处理当前socket消息</span></span>,<span><span class="comment">调用ZygoteConnection的runOnce</span></span>()
            boolean done;
            done = peers.get(index).runOnce();
            if (done) {
                peers.remove(index);
                fds.remove(index);
            }
        }
    }
}
Zygote变为一个守护进程,通过selectReadable()监听socket连接请求。(这里具体是谁会请求连接,后续研究

监听到连接请求,selectReadable()返回,就会调用ZygoteConnection的runOnce()函数。

frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java

boolean runOnce() throws ZygoteInit.MethodAndArgsCaller {
    ...
    try {
        parsedArgs = new Arguments(args);//这里的args参数是从socket中读取的,也就是说是客户端传过来的
        ...

        pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
                parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
                parsedArgs.niceName);
    } catch (...) {
        ...
    }

    try {
        if (pid == 0) {
            // in child
            ...
            handleChildProc(parsedArgs, descriptors, childPipeFd, newStderr);
            // should never get here, the child is expected to either
            // throw ZygoteInit.MethodAndArgsCaller or exec().
            return true;
        } else {
            // in parent...pid of < 0 means failure
            ...
            return handleParentProc(pid, descriptors, serverPipeFd, parsedArgs);
        }
    } finally {
        ...
    }
}
runOnce()调用Zygote.forkAndSpecialize()

libcore/dalvik/src/main/java/dalvik/system/Zygote.java  
    forkAndSpecialize()  
    nativeForkAndSpecialize()  
dalvik/vm/native/dalvik_system_Zygote.cpp  
    Dalvik_dalvik_system_Zygote_forkAndSpecialize()  
    forkAndSpecializeCommon()  
类似于上面的Zygote.forkSystemServer(),最后调用linux系统调用fork() 创建新的进程。
这里创建进程的参数是从socket中读取的,也就是说是客户端传过来的。
创建新进程完成后,
父进程(Zygote)调用handleParentProc()处理一些事情后,返回ZygoteInit.runSelectLoop(),进入下一次循环,监听连接请求。
子进程调用handleChildProc(),最后调用ZygoteInit.invokeStaticMain()函数(和RuntimeInit.invokeStaticMain()一样),抛出异常ZygoteInit.MethodAndArgsCaller,返回到ZygoteInit.main()函数异常处理,执行caller.run(); 从而子进程跳出ZygoteInit.runSelectLoop()的死循环,去执行新的入口main()函数,开始新的进程人生。


总结
Zygote进程由init进程启动后,先创建SystemServer进程,然后变成守护进程,监听socket请求,继续创建其他进程。

遗留问题
1、SystemServer进程创建后,SystemServer 由 com.android.server.SystemServer.main() 开始后续流程
2、Zygote变为守护进程后,谁会发起socket连接请求创建新进程


题外知识

Socket编程中有两种方式去触发Socket数据读操作。一种是使用listen()监听某个端口,然后调用read()去从这个端口上读数据,这种方式被称为阻塞式读操作,因为当端口没有数据时,read()函数将一直等待,直到数据准备好后才返回;另一种是使用select()函数将需要监测的文件描述符作为select()函数的参数,然后当该文件描述符上出现新的数据后,自动触发一个中断,然后在中断处理函数中再去读指定文件描述符上的数据,这种方式被称为非阻塞式读操作。LocalServerSocket中使用的正是后者,即非阻塞读操作。


参考:

http://www1.huachu.com.cn/read/readbookinfo.asp?sectionid=1000006113

http://blog.csdn.net/zhgxhuaa/article/details/24584807

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章