Android核心-从开机到AMS启动流程

概览

​Android任意一个App启动都可以拆分为以下几个步骤

  • 1 启动进程
  • 2 启动主Activity
  • 3 显示Activity
  • 4 加载其他逻辑

本篇粗略的讲解第一个步骤

Android进程的启动

在我们开机的时候,显示“Android”这个logo的时候,就是Android启动系统了,第一个进程叫做init,编号为1,是Android系统启动的第一个进程,他干了以下几件事:

  • 1 解析两个配置文件,一个叫做init.rc,另一个是跟硬件有关
  • 2 执行了一些操作,其中一个就是创建zygote进程(重点)
  • 3 初始化属性相关的资源,并启动属性服务
  • 4 然后进入一个无限循环,等待干一些事情

除了第二步创建了zygote进程外,别的我们都不关心,那我们zygote进程怎么起来的呢,这个就要看native的代码了,就是在一个叫做AndroidRuntime.cpp的文件的start()函数,他是这么干的:

  • 1 创建虚拟机:startVM(),这里会做一些检查工作,比如引用有没有超过2000个啊啥的,然后设置虚拟机的heapsize,默认是16MB,一般都会被修改为32MB
  • 2 注册JNI函数:startReg(),这里会设置Thread的创建函数,还会注册一些函数,比如JNITest等
  • 3 通过JNI函数调用java层函数:CallStaticVoidMethod(),调用的类是:com.android.internal.os.ZygoteInit,传递的参数是true
  • 4 然后就会进入到java层的ZygoteInit.java的main函数中了,来看一下代码:
public static void main(String argv[]) {
    // 创建server端,因为我们的zygote和init是通过socket通信的
    ZygoteServer zygoteServer = new ZygoteServer();
    // Mark zygote start. This ensures that thread creation will throw an error.
    ZygoteHooks.startZygoteNoThreadCreation();
    // Zygote goes into its own process group.
    try {
        Os.setpgid(0, 0);
    } catch (ErrnoException ex) {
        throw new RuntimeException("Failed to setpgid(0,0)", ex);
    }

    try {
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "ZygoteInit");
        RuntimeInit.enableDdms();
        boolean startSystemServer = false;
        String socketName = "zygote";
        String abiList = null;

        // 参数处理,支持的abi,套接字名字等
        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]);
            }
        }

        // abi检测 
        if (abiList == null) {
            throw new RuntimeException("No ABI list supplied.");
        }

        //1 注册zygote的socket(重点啊,要考的)
        zygoteServer.registerServerSocket(socketName);
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "ZygotePreload");
        EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
                SystemClock.uptimeMillis());
        //2 预加载一些类、资源等
        preload();

        //强制进行一次gc()
        gcAndFinalize();
        
        // Zygote process unmounts root storage spaces.
        Zygote.nativeUnmountStorageOnInit();
        // Set seccomp policy
        Seccomp.setPolicy();
        ZygoteHooks.stopZygoteNoThreadCreation();
        if (startSystemServer) {
            //3 (重点)启动SystemServer进程,这里很风骚的抛出Zygote.MethodAndArgsCaller异常
            startSystemServer(abiList, socketName, zygoteServer);
        }

        Log.i(TAG, "Accepting command socket connections");
        //预留点,zygote在这里阻塞等待,处理来自SS的请求,比如ActivityServiceManager.startProcessLocked()
        //这里也很风骚的抛出Zygote.MethodAndArgsCaller异常
        zygoteServer.runSelectLoop(abiList);
        //关闭socket
        zygoteServer.closeServerSocket();
    } catch (Zygote.MethodAndArgsCaller caller) {
        //预留点,fuck,这个异常是在后面找到SystemServer的main函数的时候抛出的
        //这个run方法执行了传递进来的main函数
        caller.run();
    } catch (Throwable ex) {
        Log.e(TAG, "System zygote died with exception", ex);
        zygoteServer.closeServerSocket();
        throw ex;
    }
复制代码

这里来分析一下代码:

  • 1 建立了IPC通信服务的服务端的socket
  • 2 调用preload()预加载一些类和资源,光类就有1000多个,所以加载慢,这也是Android启动慢的原因
  • 3 启动system_server进程

第一步:注册Socket通信的server端

void registerServerSocket(String socketName) {
    if (mServerSocket == 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);
            //建立IPC通信服务端的socket
            //1 谁是客户端?
            //2 怎么和客户端连接?什么时候连接?怎么处理消息?
            mServerSocket = new LocalServerSocket(fd);
        } catch (IOException ex) {
            throw new RuntimeException(
                    "Error binding to local socket '" + fileDesc + "'", ex);
        }
    }
}
复制代码

这里很简单,就是new了一个serversocket而已

第二步:预加载类和资源

static void preload() {
    Log.d(TAG, "begin preload");

    beginIcuCachePinning();
    // 加载class
    preloadClasses();
    // 加载资源
    preloadResources();
    // openGL
    preloadOpenGL();
    
    // 共享库等
    preloadSharedLibraries();
    preloadTextResources();
    // Ask the WebViewFactory to do any initialization that must run in the zygote process,
    // for memory sharing purposes.
    WebViewFactory.prepareWebViewInZygote();
    endIcuCachePinning();
    warmUpJcaProviders();
    Log.d(TAG, "end preload");
}
复制代码

这个也很简单,也不是重点,就是分别调用Class.forName(xxx),来加载而已

第三步:启动system_server进程,这个是重点

private static boolean startSystemServer(String abiList, String socketName, ZygoteServer zygoteServer) throws Zygote.MethodAndArgsCaller, RuntimeException {
    //...

    // 这里的参数要注意
    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,3009,3010",
            "--capabilities=" + capabilities + "," + capabilities,
            "--nice-name=system_server", //进程名字,就是system_server
            "--runtime-args",
            "com.android.server.SystemServer", // 重点啊。就是这个java类
    };
    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 */
        // 通过zygote 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 */
    if (pid == 0) { //pid==0表示进入到fork出来的子进程中了
        if (hasSecondZygote(abiList)) {
            waitForSecondaryZygote(socketName);
        }

        //关闭Zygote的socket
        zygoteServer.closeServerSocket();
        //system_server开始工作了
        handleSystemServerProcess(parsedArgs);
    }

    return true;
}
复制代码

很简单,传参数给Zygote来fork出来system_server进程,然后看这个函数

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

    final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
    if (systemServerClasspath != null) {
        performSystemServerDexOpt(systemServerClasspath);
    }

    if (parsedArgs.invokeWith != null) {
        String[] args = parsedArgs.remainingArgs;
        // 将类路径复制到参数
        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) {
            //这里获取ClassLoader,用于后面反射加载main函数的
            cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);
            Thread.currentThread().setContextClassLoader(cl);
        }

        /*
         * Pass the remaining arguments to SystemServer.
         */
        //重点在这里啊:传递参数并初始化
        ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
    }
}
复制代码

接着点进去

public static final void zygoteInit(int targetSdkVersion, String[] argv,ClassLoader classLoader) throws Zygote.MethodAndArgsCaller {
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
    RuntimeInit.redirectLogStreams();
    //常规初始化
    RuntimeInit.commonInit();
    //zygote初始化
    ZygoteInit.nativeZygoteInit();
    //这里面调用main函数,argv就是main函数的参数
    RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}
复制代码

接着看

protected static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) throws Zygote.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);

    // 开始调用SystemServer的main函数了,startClass就是前面传入的com.android.server.SystemServer
    invokeStaticMain(args.startClass, args.startArgs, classLoader);
}
复制代码

接着点

private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader) throws Zygote.MethodAndArgsCaller {
    Class<?> cl;
    try {
        cl = Class.forName(className, true, classLoader);
    } catch (ClassNotFoundException ex) {
        throw new RuntimeException("Missing class when invoking static main " + className,ex);
    }

    //这里通过反射调用main函数
    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);
    }

    // 不直接调用main函数,而是抛出了这个异常
    throw new Zygote.MethodAndArgsCaller(m, argv);
}
复制代码

上面直接抛出一个异常,我看来看看这个异常的构造

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);
        }
    }
}
复制代码

666,原来接受了函数名和参数,run方法就直接调用,那么什么时候调用呢,返回第一个图,记得那个fuck吗,那里捕获了这个异常,然后回调了这个方法:

catch (Zygote.MethodAndArgsCaller caller) {
    //预留点,fuck,这个异常是在后面找到SystemServer的main函数的时候抛出的
    //这个run方法执行了传递进来的main函数
    caller.run();
} 
复制代码

可以滑上去看看第一张图的代码,也就是说现在调到了com.android.server.SystemServer.main()这里来了,通过反射取得函数信息,然后赋值给异常,通过捕获异常来回调,很风骚的代码。然后我们来看看SystemServer的main函数干了啥:

public static void main(String[] args) {
    new SystemServer().run();
}
复制代码

看它的run()方法

private void run() {
    try {
        //..省略一大堆代码

        // 开启Looper
        Looper.prepareMainLooper();
        // Initialize native services.
        // 加载libandroid_servers.so库
        System.loadLibrary("android_servers");
        //...

        // 这里是重点!
        createSystemContext();
        // Create the system service manager.
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }

    // Start services.
    try {
        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
        // 注册一大堆Service
        startBootstrapServices();
        startCoreServices();
        startOtherServices();
    } catch (Throwable ex) {
        throw ex;
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }

    // 轮询
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}
复制代码

这里只粘一个吧,其他的都差不多

private void startBootstrapServices() {
    Installer installer = mSystemServiceManager.startService(Installer.class);
    // 重点啊,启动ActivityManagerService
    mActivityManagerService = mSystemServiceManager.startService(ActivityManagerService.Lifecycle.class).getService();
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);
    
    // 启动PowerManagerService
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
    
    mActivityManagerService.initPowerManagement();

    mSystemServiceManager.startService(LightsService.class);
    
    mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

    mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
    //...

    // 启动PackageManagerService
    mPackageManagerService = PackageManagerService.main(mSystemContext, installer,mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    mFirstBoot = mPackageManagerService.isFirstBoot();
    mPackageManager = mSystemContext.getPackageManager();

    //...

    mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
    // Initialize attribute cache used to cache resources from packages.
    AttributeCache.init(mSystemContext);
    // Set up the Application instance for the system process and get started.
    // 2 注册Service,这里面才会在native端创建BpBinder,这个后面启动Activity要用的
    mActivityManagerService.setSystemProcess();
    // 传感器服务
    startSensorService();
}
复制代码

好,现在我们的ActivityManagerService有了,到这就差不多了,来归纳一下流程

  • 1 Android系统启动的时候init进程启动了
  • 2 init进程启动了zygote进程
  • 3 zygote进程启动了system_server进程,然后通过反射和捕获异常风骚的调用到了SystemServer的main函数中
  • 4 SystemServer的main函数初始化了AMS,PMS等一些列的service

到此,AMS已经启动,接着就是AMS和APP之间通过Bindler进行沟通的逻辑了。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享