Android 8.0系统启动流程_Zygote(二)

本系列主要介绍Android系统启动过程中涉及到的init、Zygote、SystemServerLauncher
文本分析的源码时基于Android8.0源码。

Zygote(孵化器),系统中DVM、ART、应用程序进程和SystemServer进程都是由Zygote创建,其中SystemServer是应用层开发经常碰到的,因为应用层APP的进程是通过SystemServer进程创建出来的。

一、Zygote启动脚本

Android 8.0系统启动流程_init(一)中讲解到了init启动Zygote的过程,init.cpp通过解析init.rc中配置信息,该过程称之为Zygote的启动脚本,其流程包括如下:

  1. 引入init.zygote.xx.rc:在Android 8.0系统启动流程_init(一)中init函数解析部分,讲解了init.rc配置文件的五种语法格式,其中包括为了扩展配置配置文件而引入的import语句,自Android8.0后,init.rc文件被分成了四种格式,通过import语句引入,如下所示
import /init.${ro.zygote}.rc
  1. 自Android5.0后,开始支持64位程序,通过系统的ro.zygote属性来控制使用不同的Zygote启动脚本,启动不同的脚本文件(四种中的一种),解析文件中init.zygote.xx.rc中service语句,如下所示:
\system\core\rootdir\init.zygote32.rc
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
    class main
    priority -20
    user root
    group root readproc
    socket zygote stream 660 root system
    onrestart write /sys/android_power/request_state wake
    ....
    writepid /dev/cpuset/foreground/tasks
\system\core\rootdir\init.zygote32_64.rc
service zygote /system/bin/app_process32 -Xzygote /system/bin --zygote --start-system-server --socket-name=zygote
    class main
    priority -20
    user root
    group root readproc
    .....
    writepid /dev/cpuset/foreground/tasks

service zygote_secondary /system/bin/app_process64 -Xzygote /system/bin --zygote --socket-name=zygote_secondary
    class main
    priority -20
    user root
    group root readproc
    socket zygote_secondary stream 660 root system
    onrestart restart zygote
    writepid /dev/cpuset/foreground/tasks

以上是init.zygote32.rc、init.zygote32_64.rc的部分源码,其他两种init.zygote64.rc和init.zygote64_32.rc基本类似,脚本文件主要解析如下:

  • service:在init.rc通过“service”说明该语句是service,启动一个service进程;
  • zygote:进程名称为zygote;
  • /system/bin:通过应用程序/system/bin/app_process来启动它,这也验证了zygote刚开始时不叫zygote,而是app_procress,Zygote进程启动后,Linux系统将其更改为zygote;
  • –zygote、–start–system–server:启动Zygote的参数,后续app_main.cpp中main函数中判断使用;
  • -socket-name=zygote:建立socket的名称为zygote;
  • class main:将Zygote声明为主要服务,在init启动Zygote中,ForEachServiceInClass函数就是通过查找classname为main的Zygote进程;
  • socket xxx:表示需要为此服务创建一个socket;
  • onrestart xxx:当Zygote服务重启时,需要执行的命令

二、Zygote进程启动过程介绍

Zygote进程启动时序图
下面通过Zygote进程的时序图,按照时序运行涉及到的类,来进行分析。

2.1 app_main.cpp

Android 8.0系统启动流程_init(一)中第四部分讲到init启动Zygote的流程知道最终调用到frameworks\base\cmds\app_process\app_main.cpp下的main方法,如下所示:

frameworks\base\cmds\app_process\app_main.cpp

int main(int argc, char* const argv[])
{
 while (i < argc) {
        const char* arg = argv[i++];
        if (strcmp(arg, "--zygote") == 0) {
            zygote = true;//如果当前运行Zygote进程中,则变量zygote设置为true
            niceName = ZYGOTE_NICE_NAME;
        } else if (strcmp(arg, "--start-system-server") == 0) {
            startSystemServer = true;//如果当前运行SystemServer进程中,则变量startSystemServer 设置为true
        } else if (strcmp(arg, "--application") == 0) {
            application = true;//当前为应用的进程,则变量 application设置为true
        }
 ..
    }
if (zygote) {//如果运行在Zygote中,则启动该进程
        runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
    } 
}

源码分析如下:

  • 判断当前进程:Zyogte及其子进程都是通过fork自身来创建子进程的,这样Zygote及其子进程都可以进入app_main.cpp的main函数中,此时需要通过argd的参数来区分是当前运行的是那个进程?在main函数源码解析中有如下注释,如果是以“–”或不是以“-”开头的arg则进入该函数中,以此作为简单的判断。

Everything up to ‘–’ or first non ‘-’ arg goes to the vm.

// --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.

通过判断arg中是否包含“–zygote”、“–start-system-server”、“–application”或其他参数,来判断当前运行的是那种进程。

  • 启动进程
    如果变量zygote为true,则会调用如下方法,启动Zygote进程。
runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
2.2 AndroidRuntime.cpp
\frameworks\base\core\jni\AndroidRuntime.cpp
int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv, bool zygote)
{
	...
	/* 1 start the virtual machine */
    JniInvocation jni_invocation;
    jni_invocation.Init(NULL);
    JNIEnv* env;
    if (startVm(&mJavaVM, &env, zygote) != 0) {
        return;
    }
    onVmCreated(env);

    /** 2 Register android functions.*/
    if (startReg(env) < 0) {
        ALOGE("Unable to register all android natives\n");
        return;
    }
}
...
//3 获取类名信息
classNameStr = env->NewStringUTF(className);
...
//4 className的“.”转为“/”
char* slashClassName = toSlashClassName(className != NULL ? className : "");
//5 找到ZygoteInit
    jclass startClass = env->FindClass(slashClassName);
    if (startClass == NULL) {
        ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
        /* keep going */
    } else {
    //6.找到ZygoteInit的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 {
        //7. 通过JNI调用ZygoteInit的main方法,由于当前是在Native中,ZygoteInit是java编写。
            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");

源码分析:

  • 启动准备:在注释1和2中,通过startVm创建Java虚拟机和startReg为Java虚拟机注册JNI方法;
  • 找到ZygoteInit类:在注释3、4、5和6将com.android.os.ZygoteInit转为com/android/os/ZygoteInit并赋值给slashClassName,通过slashClassName找到ZygoteInit的main方法;
  • 调用ZygoteInit类:找到该类后,通过注释7的JNI方法调用ZygoteInit的main方法,进入Java层的运行环境中。
2.3 ZygoteInit.java
frameworks\base\core\java\com\android\internal\os\ZygoteInit.java
public static void main(String argv[]) {
	...
	//1.新建一个ZygoteServer对象
	 ZygoteServer zygoteServer = new ZygoteServer();
	...
	//2.创建一个server端的socket,且名称为zygote
	zygoteServer.registerServerSocket(socketName);
 
  //3.预加载类和资源
  preload(bootTimingsTraceLog);
	...
	//4.启动SystemServer进程
	  if (startSystemServer) {
                Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
                // {@code r == null} in the parent (zygote) process, and {@code r != null} in the
                // child (system_server) process.
                if (r != null) {
                    r.run();
                    return;
                }
            }
	 Log.i(TAG, "Accepting command socket connections");

     //5.等待AMS请求
            caller = zygoteServer.runSelectLoop(abiList);
        } catch (Throwable ex) {
            Log.e(TAG, "System zygote died with exception", ex);
            throw ex;
        } finally {
            zygoteServer.closeServerSocket();
        }
	
 }
 ...

ZygoteInit的main方法主要做了如下几件事:
1、创建一个name为“zygote”的Socket服务端,用于等待AMS的请求Zygote来创建新的进程;
2、预加载类和资源,包括drawable、color、OpenGL和文本连接符资源等,保存到Resources一个全局静态变量中,下次读取系统资源的时候优先从静态变量中查找;
3、启动SystemServer进程;
4、通过runSelectLoop()方法,等待AMS的请求创建新的应用程序进程。

1.registerServerSocket

frameworks\base\core\java\com\android\internal\os\ZygoteServer.java
void registerServerSocket(String socketName) {
        if (mServerSocket == null) {
            int fileDesc;
            //1.拼接Socket的名称
            final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
            try {
            //2.得到Soket的环境变量值:ANDROID_SOCKET_zygote
                String env = System.getenv(fullSocketName);
                fileDesc = Integer.parseInt(env);
            } catch (RuntimeException ex) {
                throw new RuntimeException(fullSocketName + " unset or invalid", ex);
            }

            try {
            //3.通过fileDesc创建文件描述符:fd
                FileDescriptor fd = new FileDescriptor();
                fd.setInt$(fileDesc);
                //4.创建服务端的Socket
                mServerSocket = new LocalServerSocket(fd);
            } catch (IOException ex) {
                throw new RuntimeException(
                        "Error binding to local socket '" + fileDesc + "'", ex);
            }
        }
    }

2.预加载类和资源

frameworks\base\core\java\com\android\internal\os\ZygoteInit.java
 static void preload(TimingsTraceLog bootTimingsTraceLog) {
     ...
     //1.预加载位于/system/etc/preloaded-classes文件中的类
        preloadClasses();
     ...
     2.预加载drawble和color的资源信息
        preloadResources();
      ...
      //3.通过JNI调用,预加载底层相关的资源
        nativePreloadAppProcessHALs();
      ...
      //4.预加载OpenGL资源
        preloadOpenGL();
       ...
       //5.预加载共享库:"android","compiler_rt","jnigraphics"
        preloadSharedLibraries();
        //6.预加载文本连接符资源
        preloadTextResources();
      ...
      //7.zygote中,内存共享进程
        warmUpJcaProviders();
      ...
    }

3.启动SystemServer进程

frameworks\base\core\java\com\android\internal\os\ZygoteServer.java
 private static Runnable forkSystemServer(String abiList, String socketName,
            ZygoteServer zygoteServer) {
  ...
  //1.创建数组,保存启动SystemServer的参数
        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 */
            //2.创建SystemServer进程
            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 */
        //3.如果pid为0,表示运行在新的子进程中
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }
            zygoteServer.closeServerSocket();
            //4.处理SystemServer进程
            return handleSystemServerProcess(parsedArgs);
        }
        return null;
    }

4.runSelectLoop()

frameworks\base\core\java\com\android\internal\os\ZygoteServer.java
 /**
     * Runs the zygote process's select loop. Accepts new connections as
     * they happen, and reads commands from connections one spawn-request's
     * worth at a time.
     * 运行在Zygote进程中,等待新的连接,并读取请求数据
     */
    Runnable runSelectLoop(String abiList) {
		ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
        ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
		//1.将ServerSocket添加到集合中
        fds.add(mServerSocket.getFileDescriptor());
        peers.add(null);
        2.开启死循环,不断的等待AMS的请求
          while (true) {
          //3.通过遍历fds存储信息,添加至 pollFds数组中
            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);
            }
            //4. 通过遍历pollFds信息
            for (int i = pollFds.length - 1; i >= 0; --i) {
                if ((pollFds[i].revents & POLLIN) == 0) {
                    continue;
                }
                //5.如果pid为0,表明已经连接socket,
			  if (i == 0) {
                    ZygoteConnection newPeer = acceptCommandPeer(abiList);
                    peers.add(newPeer);
                    fds.add(newPeer.getFileDesciptor());
                }else{
                /6.如果不等于0 ,AMS向Zyogte进程创建一个新的进程的请求
						 ZygoteConnection connection = peers.get(i);
                        final Runnable command = connection.processOneCommand(this);
				}
                ... 
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值