一、init进程启动

init进程是Linux系统中用户空间的第一个进程,进程号固定为1。

主要职责:

  • 创建共享内存空间,用于属性服务
  • 解析各个rc文件,并启动相应的属性服务进程,包括Zygote服务进程

二、Zygote进程启动

Zygote由init进程通过init.zygote.rc文件fork的。

Zygote进程是Android系统的第一个Java进程(即虚拟机进程),Zygote是所有Java进程的父进程。

1、Zygote的作用

在Android系统中,DVM(Dalvik虚拟机)和ART、应用程序进程以及SystemServer都是由Zygote进程创建的,因此Zygote进程也成为孵化器。

Zygote通过fork(复制进程)的形式来创建应用进程和SystemServer进程,由于Zygote进程在启动时会创建DVM或者ART,因此通过fork而创建的应用程序进程和SystemServer进程可以在内部获取一个DVM或者ART的实例副本。

2、Zygote启动过程

  • app_main.cpp的main函数中的调用AndroidRuntimestart方法启动Zygote进程。(Zygote进程通过fork自身来创建子进程的)
  • 执行AndroidRuntime.cppstart方法。作用:
    1、启动Java虚拟机,
    2、注册JNI方法,
    3、通过将"com.android.internal.os.ZygoteInit"转换为"com/android/internal/os/ZygoteInit"找到ZygoteInit类和通过JNI调用ZygoteInit.main()方法,进入Java层。

3、进入Java层

通过AndroidRuntime.start()方法执行到最后会通过反射调用到ZygoteInit.main()从而进入Java层。

1、ZygoteInit.main

public static void main(String argv[]) {
        ...
        try {
    
            
            String socketName = "zygote";
            String abiList = null;
            boolean enableLazyPreload = false;
            for (int i = 1; i < argv.length; i++) {
                if ("start-system-server".equals(argv[i])) {
                    startSystemServer = true;
                } else if ("--enable-lazy-preload".equals(argv[i])) {
                    enableLazyPreload = 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.");
            }
            //为Zygote注册socket
            zygoteServer.registerServerSocket(socketName);
            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();
            }
            ...
            if (startSystemServer) {
                //启动SystemServer进程
                startSystemServer(abiList, socketName, zygoteServer);
            }

            Log.i(TAG, "Accepting command socket connections");
            //进入循环模式,等待AMS的请求
            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;
        }
    }

可以看到在main方法中主要做了:

  • 创建一个Server端的Socket
  • 预加载类和资源
  • 启动SystemServer进程
  • 进入循环状态,等待AMS请求创建新进程

1、registerServerSocket - 创建socket服务端

ZygoteServerregisterServerSocket

56    void registerServerSocket(String socketName) {
57        if (mServerSocket == null) {
58            int fileDesc;
59            final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;//拼接socket名称
60            try {
61                String env = System.getenv(fullSocketName);
62                fileDesc = Integer.parseInt(env);
63            } catch (RuntimeException ex) {
64                throw new RuntimeException(fullSocketName + " unset or invalid", ex);
65            }
66
67            try {
68                FileDescriptor fd = new FileDescriptor();
69                fd.setInt$(fileDesc);
70                mServerSocket = new LocalServerSocket(fd);//创建socket本地服务端
71            } catch (IOException ex) {
72                throw new RuntimeException(
73                        "Error binding to local socket '" + fileDesc + "'", ex);
74            }
75        }
76    }

在registerServerSocket方法中会创建一个本地socket服务端,等待AMS请求创建新进程

2、preload - 预加载类与资源

static void preload(BootTimingsTraceLog bootTimingsTraceLog) {
   
        //预加载类
        preloadClasses();
        
        //预加载资源文件
        preloadResources();
        
        //预加载OpenGL
        preloadOpenGL();
        
        //通过System.loadLibrary()方法,
        //预加载"android","compiler_rt","jnigraphics"这3个共享库
        preloadSharedLibraries();
        
        预加载 文本连接符资源
        preloadTextResources();

        WebViewFactory.prepareWebViewInZygote();
        endIcuCachePinning();
        warmUpJcaProviders();
    }

Zygote对于类的加载,采用反射机制Class.forName方法来加载。

3、startSystemServer - 启动SystemServer

/**
     * Prepare the arguments and fork for the system server process.
     */
    private static boolean startSystemServer(String abiList, String socketName, ZygoteServer zygoteServer)
            throws Zygote.MethodAndArgsCaller, RuntimeException {
        ...
        /* Hardcoded command line to start the system server */
        //准备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 */
            //fork子进程,即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 */
        //进入SystemServer进程
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }

            zygoteServer.closeServerSocket();
            //完成SystemServer进程剩余工作
            handleSystemServerProcess(parsedArgs);
        }

        return true;
    }

在startSystemServer中会准备参数并fork出一个新的进程-SystemServer进程。从参数信息可以看出system_server的uid和gid都为1000,进程名为system_server

4、runSelectLoop - 循环等待

128    /**
129     * Runs the zygote process's select loop. Accepts new connections as
130     * they happen, and reads commands from connections one spawn-request's
131     * worth at a time.
132     *
133     * @throws Zygote.MethodAndArgsCaller in a child process when a main()
134     * should be executed.
135     */
136    void runSelectLoop(String abiList) throws Zygote.MethodAndArgsCaller {
137        ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
138        ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
139
140        fds.add(mServerSocket.getFileDescriptor());
141        peers.add(null);
142        //无限循环等待AMS请求
143        while (true) {
144            StructPollfd[] pollFds = new StructPollfd[fds.size()];
145            for (int i = 0; i < pollFds.length; ++i) {
146                pollFds[i] = new StructPollfd();
147                pollFds[i].fd = fds.get(i);
148                pollFds[i].events = (short) POLLIN;
149            }
150            try {
151                Os.poll(pollFds, -1); //当pollFds有数据继续执行,否则阻塞
152            } catch (ErrnoException ex) {
153                throw new RuntimeException("poll failed", ex);
154            }
155            for (int i = pollFds.length - 1; i >= 0; --i) {
                   // //采用I/O多路复用机制,当接收到客户端发出连接请求 或者数据处理请求到来,则往下执行;
                   // 否则进入continue,跳出本次循环。
156                if ((pollFds[i].revents & POLLIN) == 0) {
157                    continue;
158                }
                   //即fds[0],代表的是sServerSocket,则意味着有客户端连接请求;
159                if (i == 0) {
                        // 则创建ZygoteConnection对象,并添加到fds。
160                    ZygoteConnection newPeer = acceptCommandPeer(abiList);
161                    peers.add(newPeer);
162                    fds.add(newPeer.getFileDesciptor());
163                } else {
                       //i>0,则代表通过socket接收来自对端的数据
164                    boolean done = peers.get(i).runOnce(this);
165                    if (done) {
166                        peers.remove(i);
167                        fds.remove(i);//处理完则从fds中移除该文件描述符
168                    }
169                }
170            }
171        }
172    }

Zygote采用高效的I/O多路复用机制,保证在没有客户端连接请求或数据处理时休眠,否则响应客户端的请求。
通过调用ZygoteConnection的runOnce方法,创建一个新应用程序进程,并在成功创建后将这个连接从Socket连接列表peers和fd列表fds中移除。

Zygote总结:

Zygote进程启动主要做了:

  • 创建AppRuntime并调用其start方法,启动Zygote进程
  • 创建Java虚拟机并为其注册JNI方法
  • 通过JNI调用ZygoteInit的main函数进入Zygote的Java架构层
  • 通过registerServerSocket方法创建Socket本地服务端,并通过runSelectLoop方法等待AMS的请求来创建新的应用程序进程
  • 启动SystemServer进程

三、SystemServer启动过程

SystemServer用于创建系统服务,我们熟知的AMS、WMS、PMS都是由它创建的,SystemServer是Zygote孵化的第一个进程。

1、startSystemServer – 准备参数、fork进程

在Zygote启动中我们知道在ZygoteInit.java中,会调用startSystemServer方法来启动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 */
            //fork 子进程 system_server
            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 */
        //进入子进程 system_server
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }
            //关闭Zygote进程创建的socket
            zygoteServer.closeServerSocket();
            //完成system_server进程剩余部分
            handleSystemServerProcess(parsedArgs);
        }

        return true;
    }
  • Zygote进程通过fork方法复制Zygote进程的地址空间,从而得到子进程SystemServer进程,因此也会得到Zygote进程创建的socket,这个socket对于SystemServer进程没有用处,所以需要关闭该socket。
  • 调用handleSystemServerProcess方法启动SystemServer进程。

2、handleSystemServerProcess – 启动system_server进程

/**
     * 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);//设置进程名 system_server
        }

        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.
             */
             //将其余参数床底给system_server
            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();
        //启动Binder线程池
        ZygoteInit.nativeZygoteInit();
        //进入SystemServer的main方法
        RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
    }

该方法主要做了两个件事,启动Binder线程池和进入SystemServer的main方法。

1、启动Binder线程池

nativeZygoteInit是一个Native方法,源码如下:

/frameworks/base/include/android_runtime/AndroidRuntime.cpp

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

这里gCurRuntime是AndroidRuntime类型的指针,具体指向的是AndroidRuntime的子类AppRuntime,他在app_main.cpp中定义,AppRuntime的onZygoteInit方法如下:

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

通过调用startThreadPool()方法启动一个Binder线程池,这样SystemServer进程就可以使用Binder与其他进程进行通信了。

2、进入 SystemServer 的 main 方法

回到上面ZygoteInit.zygoteInit()方法中,最后调用RuntimeInit.applicationInit方法,源码如下:

private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
            throws ZygoteInit.MethodAndArgsCaller {
    
        nativeSetExitWithoutCleanup(true);

        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
        invokeStaticMain(args.startClass, args.startArgs, classLoader);
    }

继续调用invokeStaticMain方法:

private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
            throws ZygoteInit.MethodAndArgsCaller {
        Class<?> cl;

        try {
            //通过反射得到SystemServer类
            cl = Class.forName(className, true, classLoader);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Missing class when invoking static main " + className,
                    ex);
        }

        Method m;
        try {
            //得到 SystemServer 的 main 方法
            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.
         */
        throw new ZygoteInit.MethodAndArgsCaller(m, argv);
    }

该方法主要做了下面几件事:

  • className 为 com.android.server.SystemServer,通过反射得到SystemServer的class
  • 通过 class 得到SystemServer的 main 方法
  • 将 main 方法传入 MethodAndArgsCaller 异常中并抛出该异常。该异常会在ZygoteInit的 main方法中捕获。

下面是ZygoteInit的main方法中捕获MethodAndArgsCaller异常的代码:

public static void main(String argv[]) {
        ...
        } catch (Zygote.MethodAndArgsCaller caller) {
            caller.run();
        } catch (Throwable ex) {
            Log.e(TAG, "System zygote died with exception", ex);
            zygoteServer.closeServerSocket();
            throw ex;
        }
    }

当捕获到MethodAndArgsCaller异常就会执行caller.run()方法,MethodAndArgsCallerZygote.java的静态内部类:

/**
     * Helper exception class which holds a method and arguments and
     * can call them. This is used as part of a trampoline to get rid of
     * the initial process setup stack frames.
     */
    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 {
                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);
            }
        }
    }

run方法中会执行mMethod.invoke方法,mMethod就是 SystemServer 的 main 方法, 调用了 mMethod就是 的 invoke 方法后, SystemServer 的 main 方法就会被动态调用, SystemServer 进程就进入了 SystemServer 的 main 方法中。

3、SystemServer 的 main()方法

/**
     * The main entry point from zygote.
     */
    public static void main(String[] args) {
        new SystemServer().run();
    }

调用了SystemServerrun()方法。

private void run() {
        try {
			//如果当前时间小于1970,就是设置为1970年
            if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
                Slog.w(TAG, "System clock is before 1970; setting to 1970.");
                SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
            }

            // Here we go!
            Slog.i(TAG, "Entered the Android system server!");
            int uptimeMillis = (int) SystemClock.elapsedRealtime();
            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
            if (!mRuntimeRestart) {
                MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
            }
			//变更虚拟机的库文件
            SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());

            // Enable the sampling profiler.
            if (SamplingProfilerIntegration.isEnabled()) {
                SamplingProfilerIntegration.start();
                mProfilerSnapshotTimer = new Timer();
                mProfilerSnapshotTimer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            SamplingProfilerIntegration.writeSnapshot("system_server", null);
                        }
                    }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
            }

            // Mmmmmm... more memory!
            //清除vm内存增长上限,因为启动过程中需要较多的虚拟机内存空间
            VMRuntime.getRuntime().clearGrowthLimit();

            // The system server has to run all of the time, so it needs to be
            // as efficient as possible with its memory usage.
            //设置内存有效使用率为0.8
            VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

            // Some devices rely on runtime fingerprint generation, so make sure
            // we've defined it before booting further.
            Build.ensureFingerprintProperty();

            // Within the system server, it is an error to access Environment paths without
            // explicitly specifying a user.
            Environment.setUserRequired(true);

            // Within the system server, any incoming Bundles should be defused
            // to avoid throwing BadParcelableException.
            //访问环境路径前,显示指定用户
            BaseBundle.setShouldDefuse(true);

            // Ensure binder calls into the system always run at foreground priority.
            //确保对系统的Binder调用总是以前台优先级运行。
            BinderInternal.disableBackgroundScheduling(true);

            // Increase the number of binder threads in system_server
            //增加system_server中绑定器线程的数量
            BinderInternal.setMaxThreads(sMaxBinderThreads);

            // Prepare the main looper thread (this thread).
            Process.setThreadPriority(
                Process.THREAD_PRIORITY_FOREGROUND);
            Process.setCanSelfBackground(false);
            //创建当前线程 的Looper
            Looper.prepareMainLooper();

            // Initialize native services.
            //加载android_servers.so库
            System.loadLibrary("android_servers");

            // Check whether we failed to shut down last time we tried.
            // This call may not return.
            performPendingShutdown();

            // Initialize the system context.
            //创建系统Context
            createSystemContext();

            // Create the system service manager.
            //创建系统服务管理器。
            mSystemServiceManager = new SystemServiceManager(mSystemContext);
            mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
            //将 mSystemServiceManager 添加到管理本地服务的sLocalServiceObjects map中
            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
            // Prepare the thread pool for init tasks that can be parallelized
            SystemServerInitThreadPool.get();
        } finally {
            traceEnd();  // InitBeforeStartServices
        }

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

        // Loop forever.
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

在run方法中主要做了:

  • 创建主线程的Looper对象
  • 加载了动态库android_servers.so
  • 创建了全局Context
  • 创建SystemServiceManager对象,用于对系统服务的创建、启动和声明周期管理
  • 启动各种服务

SystemServer总结

SystemServer是Zygote进程fork创建的第一个进程,主要做了:

  • 启动了Binder线程池,这样就可以与其他进程进行通信了
  • 创建SystemServerManager,用于对系统服务进行创建、启动和声明周期管理
  • 启动各种服务

四、Launcher 启动过程

系统启动最后一步是启动一个应用程序来显示系统中已安装的应用程序,这个应用程序叫做Launcher。Launcher 启动过程中会请求PackageManagerServer 返回系统中已安装的应用程序信息,并将这些信息封装成一个快捷图标列表显示在屏幕上,这样用户点击图标就可以启动响应的应用程序。

主要作用:

  • 作为 Android 系统的启动器,用于启动应用程序
  • 作为 Android 系统的桌面,用于显示和管理应用程序的快捷图标和桌面组件

1、Launcher的启动过程

SystemServer 进程在启动过程中会启动 PackageManagerServer,PackageManagerServer启动后会将系统中的应用程序安装完成。
通过AMS将 Launcher 启动起来。

Launcher 启动的入口方法是 AMS 的 systemReady 方法,它在SystemServer启动其它服务startOtherServices()方法中调用。

1、SystemServer & startOtherServices

private void startBootstrapServices() {
		...
        mActivityManagerService.systemReady(() -> {
            Slog.i(TAG, "Making services ready");
            traceBeginAndSlog("StartActivityManagerReadyPhase");
            mSystemServiceManager.startBootPhase(
                    SystemService.PHASE_ACTIVITY_MANAGER_READY);
  			...
        }, BOOT_TIMINGS_TRACE_LOG);
	}

ActivityManagerService 属于引导服务,在startBootstrapServices()方法中创建和启动。

2、AMS & systemReady

public void systemReady(final Runnable goingCallback) {
 			...
            mStackSupervisor.resumeFocusedStackTopActivityLocked();
            mUserController.sendUserSwitchBroadcastsLocked(-1, currentUserId);
        }
    }

最终会调用 ActivityStackSupervisorresumeFocusedStackTopActivityLocked()方法。

3、ActivityStackSupervisor & resumeFocusedStackTopActivityLocked()

boolean resumeFocusedStackTopActivityLocked() {
        return resumeFocusedStackTopActivityLocked(null, null, null);
    }

    boolean resumeFocusedStackTopActivityLocked(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
        if (targetStack != null && isFocusedStack(targetStack)) {
            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }
        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
        if (r == null || r.state != RESUMED) {
            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
        }
        return false;
    }

因为参数都为NULL,所以会执行mFocusedStack.resumeTopActivityUncheckedLocked(null, null),mFocusedStack是ActivityStack类型对象。

4、ActivityStack & resumeTopActivityUncheckedLocked

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        if (mStackSupervisor.inResumeTopActivity) {
            // Don't even start recursing.
            return false;
        }

        boolean result = false;
        try {
            // Protect against recursion.
            mStackSupervisor.inResumeTopActivity = true;
            if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
                mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
                mService.updateSleepIfNeededLocked();
            }
            result = resumeTopActivityInnerLocked(prev, options);
        } finally {
            mStackSupervisor.inResumeTopActivity = false;
        }
        return result;
    }

会继续执行:ActivityStack.resumeTopActivityInnerLocked方法

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
		        if (DEBUG_LOCKSCREEN) mService.logLockScreen("");

        ActivityRecord parent = mActivityContainer.mParentActivity;
        if ((parent != null && parent.state != ActivityState.RESUMED) ||
                !mActivityContainer.isAttachedLocked()) {
            // Do not resume this stack if its parent is not resumed.
            // TODO: If in a loop, make sure that parent stack resumeTopActivity is called 1st.
            return false;
        }

        mStackSupervisor.cancelInitializingActivities();

        // Find the first activity that is not finishing.
        final ActivityRecord next = topRunningActivityLocked();    

        final TaskRecord prevTask = prev != null ? prev.task : null;
        if (next == null) {
            // There are no more activities!
            final String reason = "noMoreActivities";

            return isOnHomeDisplay() &&
                    mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, reason);
        }
        ...
	}

继续执行 ActivityStackSupervisor . resumeHomeStackTask

final ActivityManagerService mService;

    boolean resumeHomeStackTask(int homeStackTaskType, ActivityRecord prev, String reason) {
        if (!mService.mBooting && !mService.mBooted) {
            // Not ready yet!
            return false;
        }

        if (homeStackTaskType == RECENTS_ACTIVITY_TYPE) {
            mWindowManager.showRecentApps(false /* fromHome */);
            return false;
        }

        if (prev != null) {
            prev.task.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
        }

        mHomeStack.moveHomeStackTaskToTop(homeStackTaskType);
        ActivityRecord r = getHomeActivity();
        final String myReason = reason + " resumeHomeStackTask";

        // Only resume home activity if isn't finishing.
        if (r != null && !r.finishing) {
            mService.setFocusedActivityLocked(r, myReason);
            return resumeFocusedStackTopActivityLocked(mHomeStack, prev, null);
        }
        return mService.startHomeActivityLocked(mCurrentUser, myReason);
    }

该方法会调用AMS的startHomeActivityLocked方法。

5、AMS & startHomeActivityLocked

String mTopAction = Intent.ACTION_MAIN;

    boolean startHomeActivityLocked(int userId, String reason) {
        if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
                && mTopAction == null) {
            //如果为低级工厂模式并且mTopAction 为null,则终止
            return false;
        }
        //获得 intent 
        Intent intent = getHomeIntent();
        ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
        if (aInfo != null) {
            intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
            // Don't do this if the home app is currently being
            // instrumented.
            aInfo = new ActivityInfo(aInfo);
            aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
            ProcessRecord app = getProcessRecordLocked(aInfo.processName,
                    aInfo.applicationInfo.uid, true);
            if (app == null || app.instrumentationClass == null) {
                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
                mActivityStarter.startHomeActivityLocked(intent, aInfo, reason);
            }
        } else {
            Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
        }

        return true;
    }
  • 该方法首先会通过getHomeIntent()创建一个启动Activity的Intent。
Intent getHomeIntent() {
    Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
    intent.setComponent(mTopComponent);
    intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
    if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
        intent.addCategory(Intent.CATEGORY_HOME);
    }
    return intent;
}

并且该Intent的Action属性设置为mTopAction,也就是 Intent.ACTION_MAIN,并且Category属性设置为Intent.CATEGORY_HOME

  • 调用 mActivityStarter.startHomeActivityLocked 方法

ActivityStarter & startHomeActivityLocked

void startHomeActivityLocked(Intent intent, ActivityInfo aInfo, String reason) {
        mSupervisor.moveHomeStackTaskToTop(HOME_ACTIVITY_TYPE, reason);
        startActivityLocked(null /*caller*/, intent, null /*ephemeralIntent*/,
                null /*resolvedType*/, aInfo, null /*rInfo*/, null /*voiceSession*/,
                null /*voiceInteractor*/, null /*resultTo*/, null /*resultWho*/,
                0 /*requestCode*/, 0 /*callingPid*/, 0 /*callingUid*/, null /*callingPackage*/,
                0 /*realCallingPid*/, 0 /*realCallingUid*/, 0 /*startFlags*/, null /*options*/,
                false /*ignoreTargetSecurity*/, false /*componentSpecified*/, null /*outActivity*/,
                null /*container*/, null /*inTask*/);
        if (mSupervisor.inResumeTopActivity) {
            // If we are in resume section already, home activity will be initialized, but not
            // resumed (to avoid recursive resume) and will stay that way until something pokes it
            // again. We need to schedule another resume.
            mSupervisor.scheduleResumeTopActivities();
        }
    }

在该方法中,会调用startActivityLocked方法启动Launcher,最终进入Launcher的onCreate方法,完成Launcher启动。

五、Android系统启动流程总结

BootLoader(开机引导) -> Linux Kernel(Linux内核) -> init -> Zygote -> SystemServer(启动各种服务,其中AMS会启动Launcher)