Android源码解析--SystemServer启动流程

1.前言

在整个android系统中,进程的启动流程如下:

  • init进程 –> Zygote进程 –> SystemServer进程 –>各种应用进程

先启动init进程,它是整个linux系统的根进程,接着启动了Zygote进程,它是Android系统的根进程,接着启动的就是本文要讲到的SystemServer进程,它管理着Android系统的各种系统服务,然后才是启动各种上层应用进程。

SystemServer也是Android Java的两大支柱,另一大支柱是专门负责孵化Java进程的Zygote进程(SystemServer也是由其孵化),这两大支柱任何一个倒了都会导致Android Java崩溃,然后Linux系统的init进程 会重新启动两大支柱 以重建 Android Java。

2. Zygote进程启动SyetemServer进程

刚刚提到,System_server是在Zygote进程中被启动的,源码在frameworks/base/core/java/com/android/internal/os/ZygoteInit.java 中:

public static void main(String argv[]) {
 ...
  if (startSystemServer) {
     startSystemServer(abiList, socketName);
  }
 ...
}


/**
 * 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 */
    String args[] = { // 注释1 启动System_server的相关固定参数
        "--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 {
        parsedArgs = new ZygoteConnection.Arguments(args);
        ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
        ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

        /* Request to fork the system server process */
        pid = Zygote.forkSystemServer(//注释2 从Zygote fork System_server进程
                parsedArgs.uid, parsedArgs.gid,
                parsedArgs.gids,
                parsedArgs.debugFlags,
                null,
                parsedArgs.permittedCapabilities,
                parsedArgs.effectiveCapabilities);
    } 
	...
    /* For child process */
    if (pid == 0) {
        if (hasSecondZygote(abiList)) {
            waitForSecondaryZygote(socketName);
        }
		//注释3 完成刚启动的System_server进程的剩余部分工作
        handleSystemServerProcess(parsedArgs);
    }

    return true;
}

相关的代码解释已经写在注释中了,上面注释3 调用的方法是用来做启动System_server进程后一些剩余的工作,看代码:

 /**
 * Finish remaining work for the newly forked system server process.
 */
private static void handleSystemServerProcess(
        ZygoteConnection.Arguments parsedArgs)
        throws ZygoteInit.MethodAndArgsCaller {main

    closeServerSocket();//注释1 关掉socket, Android中除了Zygote进程,其他进程之间的通信都是通过Binder完成
 ...
        /*
         * Pass the remaining arguments to SystemServer.
         */
		//注释2 调用此方法会启动Binder线程池 以及 启动SystemServer
        RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
  ...
}

上述代码中,注释1 SyetemServer进程是复制了Zygote进程的地址空间,因此也会得到Zygote进程创建的Socket,这个Socket对于SyetemServer进程没有用处,所以关闭。 注释2中,调用RuntimeInit的zygoteInit函数会启动System_server的Binder线程池,跟进代码RuntimeInit.zygoteInit:

public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
        throws ZygoteInit.MethodAndArgsCaller {
   	...
    nativeZygoteInit();//注释1
    applicationInit(targetSdkVersion, argv, classLoader);//注释2
}

此处 注释1 去启动了Binder线程池, 注释2进入了 System_server的 main方法,注释1最终会进入native层,感兴趣的可以跟进去,我们接着看注释2:

  private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
   ...
    invokeStaticMain(args.startClass, args.startArgs, classLoader);
}

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

    try {
        cl = Class.forName(className, true, classLoader);
    } catch (ClassNotFoundException ex) {
        throw new RuntimeException(
                "Missing class when invoking static main " + className,
                ex);
    }

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

 
    throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}

此处通过反射调用了SystemServer的main方法,并以抛出MethodAndArgsCaller这个 异常方式让其被 ZygoteInit.java的main函数捕获:

public static void main(String argv[]) {
   ...
        closeServerSocket();
    } catch (MethodAndArgsCaller caller) {
        caller.run();//注释1
    } catch (RuntimeException ex) {
        Log.e(TAG, "Zygote died with exception", ex);
        closeServerSocket();
        throw ex;
    }
}

在注释1 调用了 run方法,进入这个run方法:

public static class MethodAndArgsCaller extends Exception
        implements Runnable {
	...
    public MethodAndArgsCaller(Method method, String[] args) {
        mMethod = method;
        mArgs = args;
    }

    public void run() {
        try { //此处反射区调用 SystemServer的 main方法
            mMethod.invoke(null, new Object[] { mArgs });
        } 
	...
    }
}

3. 进入SystemServer进程

首先进入SystemServer进程的main函数:

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

,进入了run :

private void run() {
    try {
        //初始化时间,最早只能是1970年
        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
        }
 		...
        // Mmmmmm... more memory!
        VMRuntime.getRuntime().clearGrowthLimit();

        //由于SystemServer进程一直在运行,所以内存使用率要尽可能高一些
        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

        // 有些设备依赖于运行时指纹生成,因此请确保在进一步启动之前已经定义了指纹。
        Build.ensureFingerprintProperty();

        // 调用当前进程的mainLooper的 prepare
        android.os.Process.setThreadPriority(
            android.os.Process.THREAD_PRIORITY_FOREGROUND);
        android.os.Process.setCanSelfBackground(false);
        Looper.prepareMainLooper();

        // SystemServer的 JNI代码
        System.loadLibrary("android_servers");
		...
        // 【注释1】初始化当前进程的 Context
        createSystemContext();

        // Create the system service manager.
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }

    try {
        startBootstrapServices();//【注释2】 启动引导服务
        startCoreServices();//【注释3】  启动核心服务
        startOtherServices();//【注释4】  启动其他服务
    }
	...
    // 开启消息死循环 
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

run方法内容很多,我们把关键的找出来,上面注释1 初始了当前进程的上下文Context:

private void createSystemContext() {
    ActivityThread activityThread = ActivityThread.systemMain();
    mSystemContext = activityThread.getSystemContext();
    mSystemContext.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
}

在SystemServer中,其他应用的Activity等Context都是以 ActivityThread的形式存在。

注释2、3、4就是启动SystemServer管理的各种Android系统服务:

系统服务有很多,这里只展示一部分,以后再筛选用的比较多的来进行分析。我们接着刚刚的启动服务代码看:

private void startBootstrapServices() {
    //需要在安装应用前启动此服务,才能创建关键目录,如具有适当权限的/data/user。我们需要在初始化其他服务之前完成此操作。
    Installer installer = mSystemServiceManager.startService(Installer.class);

    //启动 Activity manager 
    mActivityManagerService = mSystemServiceManager.startService(
            ActivityManagerService.Lifecycle.class).getService();
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);

	mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
...
}

在代码中看到,在上述注释【3】【4】【5】启动的各种服务,通常都是通过 mSystemServiceManager.startService()来启动的,然后会调用add(service) :

/**
 * Starts a service by class name.
 * @return The service instance.
 */
public SystemService startService(String className) {
    final Class serviceClass;//此处泛型为SystemService,说明所有的服务类都必须实现SystemService
    try {
        serviceClass = (Class)Class.forName(className);
    } catch (ClassNotFoundException ex) {
        Slog.i(TAG, "Starting " + className);
        throw new RuntimeException("Failed to create service " + className
                + ": service class not found, usually indicates that the caller should "
                + "have called PackageManager.hasSystemFeature() to check whether the "
                + "feature is available on this device before trying to start the "
                + "services that implement it", ex);
    }
    return startService(serviceClass); // 注释1
}

此处注释1 继续往下跟:

/**
 * 创建一个系统服务,该服务必须实现SystemService接口
 *
 * @return 返回实例或者 null
 * @throws RuntimeException if the service fails to start.
 */
public  T startService(Class serviceClass) {
    try {
        final String name = serviceClass.getName();

        // Create the service.
        if (!SystemService.class.isAssignableFrom(serviceClass)) {
            throw new RuntimeException("Failed to create " + name
                    + ": service must extend " + SystemService.class.getName());
        }
        final T service;
        try {
            Constructor constructor = serviceClass.getConstructor(Context.class);
            service = constructor.newInstance(mContext);
        } catch (InstantiationException ex) {
            throw new RuntimeException("Failed to create service " + name
                    + ": service could not be instantiated", ex);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException("Failed to create service " + name
                    + ": service must have a public constructor with a Context argument", ex);
        } catch (NoSuchMethodException ex) {
            throw new RuntimeException("Failed to create service " + name
                    + ": service must have a public constructor with a Context argument", ex);
        } catch (InvocationTargetException ex) {
            throw new RuntimeException("Failed to create service " + name
                    + ": service constructor threw an exception", ex);
        }

        // Register it.
        mServices.add(service);//【注释1】 添加服务,注册到SystemServer

        // Start it.
        try {
            service.onStart();//【注释2】 启动服务
        } catch (RuntimeException ex) {
            throw new RuntimeException("Failed to start service " + name
                    + ": onStart threw an exception", ex);
        }
        return service;
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
}

创建服务成功后,在注释1 处 将服务注册到SystemServer, 注释2 启动服务

4、 总结

SyetemServer启动流程梳理:

  • 1.Zygote进程fork出SystemServer进程,并关闭没用的socket;

    1. 启动Binder线程池,这样就可以与其他进程进行通信;
  • 3.创建SystemServiceManager用于对系统的服务进行创建、启动和生命周期管理;

  • 4.SystemServer进程主要用于启动系统中的服务并进行管理。

  • 5.服务对象都有自己的异步消息对象,并运行在单独的线程中;

你可能感兴趣的:(android源码分析)