zygote进程启动

1.init.cpp —> main()

main()方法主要完成一下 6 件事:

  • klog_init() 将log写入到/dev/kmsg中
  • process_kernel_cmdline()解析内核启动参数
  • signal_handler_init()函数设置了信号处理函数
  • property_load_boot_defaults()函数导入了默认环境变量
  • property_init()和start_property_service()初始化和启动属性服务
  • init_parse_cinfig_file(“init.rc”)解析配置文件同时进入循环调用execute_one_command()函数启动子进程

通过对init.rc文件的解析最终会调用linux系统的fork()函数创建处一个子进程,同时通过execve()函数启动进程,最终进入到进程定义的main()方法中。

注意回头看一下是怎么调用到main()方法的

2.zygote进程的启动

在zygote进程对应的文件是app_main.cpp文件,在app_main.cpp文件的main()方法中先解析了init.rc中配置的参数并根据配置的参数设置zygote的状态。
在状态设置阶段主要做了:

  • 设置进程名称为zygote
  • 通过startSystemServer = true标示启动的是systemServer
  • 调用runtime.start()方法

然后调用runtime.start()方法。runtime的类型是由AndroidRuntime派生类AppRunTime,start()方法定义在AndroidRunTime类中。在启动zygote进程是start()方法接受的第一参数是com.android.internal.os.ZygoteInit,这个参数很重要。下面看一下AndroidRuntime——>start()方法的实现:

void AndroidRuntime::start(const char* className, const Vector& options, bool zygote)
{
    -----------------------------
    
    /* 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.
     * 注册JNI函数
     */
    if (startReg(env) < 0) {
        ALOGE("Unable to register all android natives\n");
        return;
    }

    /*
     * We want to call main() with a String array with arguments in it.
     * At present we have two arguments, the class name and an option string.
     * Create an array to hold them.
     */
    jclass stringClass;
    jobjectArray strArray;
    jstring classNameStr;

    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 {
        //调用该类的main()方法
        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);
            
            ----------------------
}

AndroidRuntime主要做了三件事儿:

  • 调用startVM()函数启动虚拟机
  • 调用startReg()函数注册jni方法
  • 通过调用的方法调用com.android.internal.os.ZygoteInit类main()方法。

startVM()方法多了大量的命令参数拼接最后通过JNI_CreateJavaVM()方法创建虚拟机。

startReg()方法注册JNI方法,Android中java和Native层的交互需要通过JNI机制来完成,并且Android中大量使用JNI函数。

int AndroidRuntime::startReg(JNIEnv* env)
{
        ------------------------
    //注册jni方法, gRegJNI是个数组,其中定义了要使用的JNI的方法
    if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
        env->PopLocalFrame(NULL);
        return -1;
    }
    env->PopLocalFrame(NULL);
    return 0;
}

static int register_jni_procs(const RegJNIRec array[], size_t count, JNIEnv* env)
{
    for (size_t i = 0; i < count; i++) {
        //循环便利调用数组中的元素的mProc()方法完成方法的注册
        if (array[i].mProc(env) < 0) {
#ifndef NDEBUG
            ALOGD("----------!!! %s failed to load\n", array[i].mName);
#endif
            return -1;
        }
    }
    return 0;
}

AndroidRuntime.start()的第一个参数是ZygoteInit类的文件路径,所有最终会调用到ZygoteInit类的main()方法。终于到java中了

    public static void main(String argv[]) {
        try {
            RuntimeInit.enableDdms();
            // Start profiling the zygote initialization.
            SamplingProfilerIntegration.start();

            boolean startSystemServer = false;
            String socketName = "zygote";
            String abiList = null;
            for (int i = 1; i < argv.length; i++) {
                if ("start-system-server".equals(argv[i])) {
                    startSystemServer = true;
                } else if (argv[i].startsWith(ABI_LIST_ARG)) {
                    abiList = argv[i].substring(ABI_LIST_ARG.length());
                } else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
                    socketName = argv[i].substring(SOCKET_NAME_ARG.length());
                } else {
                    throw new RuntimeException("Unknown command line argument: " + argv[i]);
                }
            }

            if (abiList == null) {
                throw new RuntimeException("No ABI list supplied.");
            }
            //1.创建Zygote进程的socket接口
            registerZygoteSocket(socketName);
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
                SystemClock.uptimeMillis());
            //2.预加载类和资源
            preload();
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
                SystemClock.uptimeMillis());

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

            // Do an initial gc to clean up after startup
            //做一个初始化后的GC操作
            gcAndFinalize();

            // Disable tracing so that forked processes do not inherit stale tracing tags from
            // Zygote.
            Trace.setTracingEnabled(false);
            //3.启动系统服务(SystemServer)
            if (startSystemServer) {
                startSystemServer(abiList, socketName);
            }

            Log.i(TAG, "Accepting command socket connections");
            //4.无限循环接受Socket接口的数据,等待AMS请求创建应用程序进程
            runSelectLoop(abiList);

            closeServerSocket();
        } catch (MethodAndArgsCaller caller) {
            //5.当启动一个新进程的时候会抛出异常,然后执行caller.run()方法
            caller.run();
        } catch (RuntimeException ex) {
            Log.e(TAG, "Zygote died with exception", ex);
            closeServerSocket();
            throw ex;
        }
    }

ZygoteInit的main()方法主要做了5件事儿:

  • 通过registerZygoteSocket()函数创建了一个Zygote的socket接口用来和AMS进行通信。
  • 调用preload()预加载类和资源
  • 调用startSystemServer()方法启动systemServer
  • 调用runSelectLoop()方法监听socket接口
  • 通过捕获一个MethodAndArgsCaller异常并调用捕获的异常的run()方法。
        private static void registerZygoteSocket(String socketName) {
        if (sServerSocket == 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);
            }
            //通过文件描述符创建socket,这里的文件描述符值得文件是 dev/socket/zygote。 这个地址是在init.rc文件中配置的
            try {
                FileDescriptor fd = new FileDescriptor();
                fd.setInt$(fileDesc);
                sServerSocket = new LocalServerSocket(fd);
            } catch (IOException ex) {
                throw new RuntimeException(
                        "Error binding to local socket '" + fileDesc + "'", ex);
            }
        }
    }

zygote的socket接口主要是通过/dev/socket/zygote文件的文件操作符进行通信。

preload()方法主要预先加载了framework中通用的类和资源(core/res/res/values/arrays.xml)、openGL、本地共享库、webView的一些资源。
预先加载主要是为了在启动新应用程序时不用重复加载这些资源从而加快启动速度。

private static void runSelectLoop(String abiList) throws MethodAndArgsCaller {
        ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
        ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();

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

        while (true) {
                if (i == 0) {
                    ZygoteConnection newPeer = acceptCommandPeer(abiList);
                    peers.add(newPeer);
                    fds.add(newPeer.getFileDesciptor());
                } else {
                    //调用zygoteConnection类的RunOnce()方法
                    boolean done = peers.get(i).runOnce();
                    if (done) {
                        peers.remove(i);
                        fds.remove(i);
                    }
                }
            }
        }
    }

在runSelectLoop()方法中通过调用ZygoteConnection.runOnce()方法来创建子进程。

我们知道Zygote进程启动后启动的第一个系统进程是SystemServer,SysetmServer用来管理Android系统中像AMS、WMS、PMS等重要的系统服务。

    private static boolean startSystemServer(String abiList, String socketName)
       
       -----------------参数处理--------------------

        try {
            parsedArgs = new ZygoteConnection.Arguments(args);
            ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
            ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

            /* Request to fork the system server process */
            //fork处一个SystemServer的进程,在Zygote.forkSystemServer()中调用了JNI方法nativeForkSystemServer()方法fork处一个进程。
            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);
            }
            //SystemServer进程创建成功之后做些处理
            handleSystemServerProcess(parsedArgs);
        }

        return true;
    }

在ZygoteInit–>startSystemServer()中通过ZygoteConnection对参数进行处理,然后通过Zygote.forkSystemServer()方法创建出一个SysetmServer进程。当返回的进程ID(Pid)等于 0时通过HandlerSystemServerprocess()来继续处理。

private static void handleSystemServerProcess(
            ZygoteConnection.Arguments parsedArgs)
            throws ZygoteInit.MethodAndArgsCaller {
        //关闭socket通信
        closeServerSocket();

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


        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(parsedArgs.remainingArgs, 0, amendedArgs, 2, parsedArgs.remainingArgs.length);
            }

            WrapperInit.execApplication(parsedArgs.invokeWith,
                    parsedArgs.niceName, parsedArgs.targetSdkVersion,
                    VMRuntime.getCurrentInstructionSet(), null, args);
        } else {
            ClassLoader cl = null;
            if (systemServerClasspath != null) {
                cl = new PathClassLoader(systemServerClasspath, ClassLoader.getSystemClassLoader());
                Thread.currentThread().setContextClassLoader(cl);
            }

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

        /* should never reach here */
    }

在handdleSystemServerProcess()方法中首先关闭Zygote进程的socket接口,由于SystemServer有zygote进程fork而来且SystemServer不需要使用socket通信所以调用closeServerSocket()方法关闭socket接口。然后调用RuntimeInit.zygoteInit()方法:

/Volumes/android_source/source/aosp/frameworks/base/core/java/com/android/internal/os/RuntimeInit.java

    public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
            throws ZygoteInit.MethodAndArgsCaller {
        /**
         * 一些通用的应用程序初始化;如:默认异常处理、时区配置、LogManager、Http UserAgent等设置
         */
        commonInit();
        //native Binder驱动程序初始化
        nativeZygoteInit();
        //重要
        applicationInit(targetSdkVersion, argv, classLoader);
    }

在RuntimeInit–>zygoteInit()方法中通过CommonInit()方法主要做了一些应用的初始化操作(如:java的默认异常处理,时区HttpUerAgent的设置)。在nativeZygoteInit()方法中在nativie中启动了Binder的驱动程序。最后调用applicationInit() 方法调用到SystemServer的main()方法中。

/Volumes/android_source/source/aosp/frameworks/base/core/jni/AndroidRuntime.cpp

static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
    gCurRuntime->onZygoteInit();
}

---------------------------------------------
/Volumes/android_source/source/aosp/frameworks/base/cmds/app_process/app_main.cpp的内嵌类AppRuntime的onZygoteInit()方法

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

在RuntimeInit的natvieZygoteInit()方法中调用了AppRuntime的onZygoteInit()方法其中创建了一个sp对象并启动了一个线程池。这部分涉及到Binder的启动和通信机制在此不深究。

在RuntimeInit的zygoteInit()方法中在调用natvieZygoteInit()方法启动Binder机制的驱动程序后还调用了applicationInit()方法;

/Volumes/android_source/source/aosp/frameworks/base/core/java/com/android/internal/os/RuntimeInit.java

    private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
            throws ZygoteInit.MethodAndArgsCaller {
            
                --------------------
                
        // Remaining arguments are passed to the start class's static main
        invokeStaticMain(args.startClass, args.startArgs, classLoader);
    }
    
    ---------------------------------------
    private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
            throws ZygoteInit.MethodAndArgsCaller {
        Class<?> cl;

        try {
        //这里的className指的是SystemServer类的文件目录
            cl = Class.forName(className, true, classLoader);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Missing class when invoking static main " + className,
                    ex);
        }

        Method m;
        try {
            m = cl.getMethod("main", new Class[] { String[].class });
        } catch (NoSuchMethodException ex) {
            throw new RuntimeException(
                    "Missing static main on " + className, ex);
        } catch (SecurityException ex) {
            throw new RuntimeException(
                    "Problem getting static main on " + className, ex);
        }

        int modifiers = m.getModifiers();
        if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
            throw new RuntimeException(
                    "Main method is not public and static on " + className);
        }

        /*
         * 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.
         *在这里抛出一个MethodAndArgsCaller异常,这个异常将在ZygoteInit的main()方法中捕获。抛出异常的目的是清除当前栈中的栈帧
         */
        throw new ZygoteInit.MethodAndArgsCaller(m, argv);
    }

在RuntimeInit的applicationInit()方法中直接调用了他的invokeStaticMain()方法。在invokeStaticMain()方法中通过放射的技术查找了SystemServer的main()方法并抛出了一个MethodAndArgsCaller的异常,此异常将在ZygoteInit的main()方法中被捕获,并在捕获后调用他的run方法。


/Volumes/android_source/source/aosp/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java的内部类

        public static class MethodAndArgsCaller extends Exception
            implements Runnable {
        /** method to call */
        private final Method mMethod;

        /** argument array */
        private final String[] mArgs;

        public MethodAndArgsCaller(Method method, String[] args) {
            mMethod = method;
            mArgs = args;
        }

        public void run() {
            try {
            //反射调用SystemServer的main()方法
                mMethod.invoke(null, new Object[] { mArgs });
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(ex);
            } catch (InvocationTargetException ex) {
                Throwable cause = ex.getCause();
                if (cause instanceof RuntimeException) {
                    throw (RuntimeException) cause;
                } else if (cause instanceof Error) {
                    throw (Error) cause;
                }
                throw new RuntimeException(ex);
            }
        }
    }
}

MethodAndArgsCaller的异常将在ZygoteInit的main()方法中捕获并在捕获后调用Caller的run()方法。通过上边的run()方法我们可以发现其中通过反射调用了SystemServer的main方法。

这基本就是Zygote进程和SystemServer进程启动的全过程

你可能感兴趣的:(移动开发)