源码分析 — SystemServer

一、概述

在Android启动的时候,会涉及到很多系统级的服务启动,如ActivityManagerService(AMS)、PackageManagerService(PMS) 等等,那他们是在什么时候被启动的呢?

需要知道的概念:

SystemServer的启动流程:ZygoteInit --> SystemServer

二、SystemServer启动时序图

这里写图片描述

三、SystemServer启动的源码分析

3.1 类 ZygoteInit

public static void main(String argv[]) {
    // Mark zygote start. This ensures that thread creation will throw
    // an error.
    ZygoteHooks.startZygoteNoThreadCreation();

    try {
		// ...省略大段代码...
        // Zygote process unmounts root storage spaces.
        Zygote.nativeUnmountStorageOnInit();
		
		// 此处开启SystemServer
        if (startSystemServer) {
            startSystemServer(abiList, socketName);
        }
		// ...省略大段代码...
    } catch (MethodAndArgsCaller caller) {
        caller.run();// 这里先留意一下
    } catch (Throwable ex) {
        throw ex;
    }
}

/**
* Prepare the arguments and fork for the system server process.
 */
private static boolean startSystemServer(String abiList, String socketName)
        throws MethodAndArgsCaller, RuntimeException {
    // ...省略代码...
    
    /* Hardcoded command line to start the system server */
    // 启动SystemService所需要的参数
    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",
        "--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 */
        // Zygote通过forkSystemServer来启动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 */
    if (pid == 0) {
        if (hasSecondZygote(abiList)) {
            waitForSecondaryZygote(socketName);
        }
		// 执行SystemServer进程的方法
        handleSystemServerProcess(parsedArgs);
    }

    return true;
}

/**
 * Finish remaining work for the newly forked system server process.
 */
private static void handleSystemServerProcess(
        ZygoteConnection.Arguments parsedArgs)
        throws ZygoteInit.MethodAndArgsCaller {
	
	// ...省略代码...
	
	if (parsedArgs.niceName != null) {
		// niceName = system_server
	    Process.setArgV0(parsedArgs.niceName);
	}
	// 获得SystemServer类的路径
    final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
    if (systemServerClasspath != null) {
        performSystemServerDexOpt(systemServerClasspath);
    }

    if (parsedArgs.invokeWith != null) {
        // ...省略代码...
    } else {
		// ...省略代码...

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

3.2 类 RuntimeInit

public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
        throws ZygoteInit.MethodAndArgsCaller {
    // 将Java的System.out和System.err的输出转移到Android日志系统中
    redirectLogStreams();
    
    commonInit(); //常规的初始化
    nativeZygoteInit(); //native层的初始化
    // 
    applicationInit(targetSdkVersion, argv, classLoader);
}

/**
 * Redirect System.out and System.err to the Android log.
 */
public static void redirectLogStreams() {
    System.out.close();
    System.setOut(new AndroidPrintStream(Log.INFO, "System.out"));
    System.err.close();
    System.setErr(new AndroidPrintStream(Log.WARN, "System.err"));
}

private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
            throws ZygoteInit.MethodAndArgsCaller {
    // ...省略大段代码...

    // 启动指定类的main方法(startClass是要启动的类的类名)
    invokeStaticMain(args.startClass, args.startArgs, classLoader);
}

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

    try {
	    // 1.根据类名获取class对象
        cl = Class.forName(className, true, classLoader);
    } catch (ClassNotFoundException ex) {
        throw new RuntimeException(
                "Missing class when invoking static main " + className,
                ex);
    }

    Method m;
    try {
	    // 2.声明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);
    }
	// 3.校验main方法的修饰符是否是public static的;
    int modifiers = m.getModifiers();
    if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
        throw new RuntimeException(
                "Main method is not public and static on " + className);
    }

    /* 
     * 上面全部满足后,抛出了异常,这个异常在ZygoteInit.main()中被捕获,
     * 就是上面提示要注意的地方,在异常捕获的地方执行caller.run()方法;
     */
	throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}

3.3 类MethodAndArgsCaller

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

四、SystemServer源码分析

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

private void run() {
	//设置当前虚拟机的运行库路径
    SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
    
    // 此处给主线程创建一个Looper对象;
    Looper.prepareMainLooper();

    /* 
     * Initialize native services.
     * 这个经常在添加.so库中用到;
     */ 
    System.loadLibrary("android_servers");
    
    /*
     * Initialize the system context.
     * 1.这里会创建系统的Context(ContextImpl实例)
     * 2.调用ActivityThread.systemMain(),生成一个系统进程中的ActivityThread实例,并将activityThread与Context进行关联;
     */
    createSystemContext();

    /*
     * Create the system service manager.
     * 创建一个系统服务的Manager,里面包含有List<SystemService> mServices用于存储开启的SystemService;
     */
    mSystemServiceManager = new SystemServiceManager(mSystemContext);
    
    /*
     * 将上面创建的SystemServiceManager添加到LocalServices中,
     * LocalServices中持有一个ArrayMap<Class<?>, Object> sLocalServiceObjects;
     * 
     * 即一个LocalServices可以对应一个SystemServiceManager,
     * 而一个SystemServiceManager中存储了多个SystemService;
     */
    LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    
    // 启动系统所需的服务
    try {
	    // 分析这个方法,下面类似;
        startBootstrapServices();
        startCoreServices();
        startOtherServices();
    } catch (Throwable ex) {
        throw ex;
    }

    //开启Looper循环,获取消息队列中的消息;
    Looper.loop();
}

private void startBootstrapServices() {
    Installer installer = mSystemServiceManager.startService(Installer.class);

    // 创建ActivityManagerService(AMS)实例
    mActivityManagerService = mSystemServiceManager.startService(
            ActivityManagerService.Lifecycle.class).getService();
   
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
    // Display manager is needed to provide display metrics before package manager starts up.
    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);

    // 给应用进程设置实例,并启动
    mActivityManagerService.setSystemProcess();

    // 创建Sensor(传感器)服务,它依赖于PMS、ops service、permissions service,因此要在他们初始化之后才能创建;
    startSensorService();
}

private void startOtherServices() {
	// ...省略代码...
	// 启动 WMS,并将WMS 服务注册到服务管理器 ServiceManager 中,其他地方可以通过 ServiceManager.getService(String name) 方法获取。
	WindowManagerService wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
                    new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
	ServiceManager.addService(Context.WINDOW_SERVICE, wm, false, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
	// 启动 InputManagerService
    ServiceManager.addService(Context.INPUT_SERVICE, inputManager, false, DUMP_FLAG_PRIORITY_CRITICAL);
    // ...省略代码...
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值