美文网首页
android Framework—zygote启动过程

android Framework—zygote启动过程

作者: Peakmain | 来源:发表于2021-03-19 14:39 被阅读0次

zygote进程实际是通过init.zygote64.rc文件解析

service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
  //main方法
    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
    writepid /dev/cpuset/foreground/tasks

对应的是 /frameworks/base/cmds/app_process/app_main.cpp的main方法

int main(int argc, char* const argv[])
{
   //过滤第一个参数
    argc--;
    argv++;
    String8 niceName;
    String8 className;

    ++i; 
//解析参数
    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()) {
        args.add(application ? String8("application") : String8("tool"));
        runtime.setClassNameAndArgs(className, argc - i, argv + i);
    } else {
      
        maybeCreateDalvikCache();
        //如果startSystemServer为true的话(默认是true),将start-system-server放到启动的参数args
        if (startSystemServer) {
            args.add(String8("start-system-server"));
        }
      .....
    }

    if (!niceName.isEmpty()) {
        runtime.setArgv0(niceName.string());
        set_process_name(niceName.string());
    }

    if (zygote) { 
         //runtime实际是AndroidRuntime
        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.");
        return 10;
    }
}

实际最终走的是AndroidRuntime的start方法

void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
{
   //className是com.android.internal.os.ZygoteInit
    JNIEnv* env;
 //1、创建jvm虚拟机
    if (startVm(&mJavaVM, &env, zygote) != 0) {
        return;
    }
    onVmCreated(env);

    /*
     * 2、注册Android JNI
     */
    if (startReg(env) < 0) {
        ALOGE("Unable to register all android natives\n");
        return;
    }

    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);
 //className=com.android.internal.os.ZygoteInit
    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);
    }

    char* slashClassName = toSlashClassName(className);
    jclass startClass = env->FindClass(slashClassName);
    if (startClass == NULL) {
    } else {
        //通过JNI调用ZygoteInit的main函数
        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
            "([Ljava/lang/String;)V");
   
    }
    free(slashClassName);
}

AndroidRuntime.start主要做以下几件事情

  • 创建jvm
  • 注册JNI方法
  • 找到ZygoteInit的main方法
  • 通过JNI执行ZygoteInit.main方法,回到Java层
image.png

Zygote的Java世界

    public static void main(String argv[]) {
        try {
              //1、创建一个服务端zygote的socket
            registerZygoteSocket(socketName);
            //2、预加载资源
            preload();
       
            if (startSystemServer) {
            //3、启动SystemServer
                startSystemServer(abiList, socketName);
            }

            Log.i(TAG, "Accepting command socket connections");
           //4、等待客户端请求
            runSelectLoop(abiList);
            closeServerSocket();
        } catch (MethodAndArgsCaller caller) {
            caller.run();
        } catch (RuntimeException ex) {
            Log.e(TAG, "Zygote died with exception", ex);
            closeServerSocket();
            throw ex;
        }
    }

registerZygoteSocket源码分析

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

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

实际就是创建了一个LocalServerSocket,也就是Socket的本地服务端
preload源码分析

    static void preload() {
       //预加载类
        preloadClasses();
       //预加载资源,如drawable和color
        preloadResources();
        //预加载opengl
        preloadOpenGL();
          //预加载 "android", "compiler_rt", "jnigraphics" 这3个共享库
        preloadSharedLibraries();
        //预加载文本资源
        preloadTextResources();
        // 仅用于 zygote 进程,用于内存共享的进程
        WebViewFactory.prepareWebViewInZygote();
    }

启动SystemServer进程

    private static boolean startSystemServer(String abiList, String socketName)
            throws MethodAndArgsCaller, RuntimeException {
       //1、设置启动参数,进程和进程组为1000,进程名为system_server,启动名字为"com.android.server.SystemServer"
        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,
            "--nice-name=system_server",
            "--runtime-args",
            "com.android.server.SystemServer",
        };
        ZygoteConnection.Arguments parsedArgs = null;

        int pid;
        try {
           //2、参数封装成Arguments对象
            parsedArgs = new ZygoteConnection.Arguments(args);
            ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
            ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

            //3、创建一个子进程
            pid = Zygote.forkSystemServer(
                    parsedArgs.uid, parsedArgs.gid,
                    parsedArgs.gids,
                    parsedArgs.debugFlags,
                    null,
                    parsedArgs.permittedCapabilities,
                    parsedArgs.effectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }
             //4、启动SystemServer进程
            handleSystemServerProcess(parsedArgs);
        }
        return true;
    }

runSelectLoop

  private static void runSelectLoop(String abiList) throws MethodAndArgsCaller {
        ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
        ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
        //sServerSocket是刚才registerZygoteSocket 创建的LocalServerSocket
        fds.add(sServerSocket.getFileDescriptor());
        peers.add(null);

        while (true) {
           //死循环获取ActivityManagerService请求Zygote进程创建新的应用程序进程
            StructPollfd[] pollFds = new StructPollfd[fds.size()];
             //fds转移到pollFds
            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) {
                  //0则表示服务端和客户端连接上
                    ZygoteConnection newPeer = acceptCommandPeer(abiList);
                        //将得到的ZygoteConnection 添加到peers中
                    peers.add(newPeer);
                    fds.add(newPeer.getFileDesciptor());
                } else {
                    //创建一个新的应用程序进程
                    boolean done = peers.get(i).runOnce();
                    if (done) {
                        peers.remove(i);
                        fds.remove(i);
                    }
                }
            }
        }
    }

    boolean runOnce() throws ZygoteInit.MethodAndArgsCaller {

        String args[];
        Arguments parsedArgs = null;
        FileDescriptor[] descriptors;

        try {
            //读取socket的参数列表
            args = readArgumentList();
            descriptors = mSocket.getAncillaryFileDescriptors();
        } catch (IOException ex) {
            closeSocket();
            return true;
        }
        try { 
           //将读取到参数封装成Arguments
            parsedArgs = new Arguments(args);

            if (parsedArgs.abiListQuery) {
                return handleAbiListQuery();
            }
       //创建子进程
            pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
                    parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
                    parsedArgs.niceName, fdsToClose, parsedArgs.instructionSet,
                    parsedArgs.appDataDir);
        } catch (ErrnoException ex) {
        }

        try {
            if (pid == 0) {
                // i子进程
                IoUtils.closeQuietly(serverPipeFd);
                serverPipeFd = null;
                handleChildProc(parsedArgs, descriptors, childPipeFd, newStderr);
                return true;
            } else {
                //父进程 
                IoUtils.closeQuietly(childPipeFd);
                childPipeFd = null;
                return handleParentProc(pid, descriptors, serverPipeFd, parsedArgs);
            }
        } finally {
            IoUtils.closeQuietly(childPipeFd);
            IoUtils.closeQuietly(serverPipeFd);
        }
    }

总结

  • 创建AppRuntime并调用start方法,创建zygote进程
  • 注册JNI方法
  • 通过JNI调用ZygoteInit的main函数进入Zygote的Java框架层
  • 通过registerZygoteSocket创建本地socket的服务端,并通过runSelectLoop等待ActivityManagerService的请求来创建新的进程
  • 启动SystemServer进程

相关文章

网友评论

      本文标题:android Framework—zygote启动过程

      本文链接:https://www.haomeiwen.com/subject/pervcltx.html