Android系统启动(三) — SystemServer处理过程

system_server 进程主要是用于创建系统服务,AMSWMSPMS 都是由它创建的。 具体来说,SystemServer 进程被创建后,主要做了以下工作:

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

1 Zygote 处理 system_server 进程

Zygote进程启动过程 中讲到 ,在 ZygoteInit.main 方法中,通过调用 forkSystemServer 方法启动 system_server 进程,一些相关时序图:

图1

ZygoteInit.forkSystemServer 代码如下所示:

// /frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
private static Runnable forkSystemServer(String abiList, String socketName, 
                                         ZygoteServer zygoteServer) {
    
    
    ...
    /* For child process 当前运行在 system_server 进程中 */
    if (pid == 0) {
    
    
        if (hasSecondZygote(abiList)) {
    
    
            waitForSecondaryZygote(socketName);
        }
		// 关闭 Zygote 进程创建的 Socket
        zygoteServer.closeServerSocket(); // 1
        return handleSystemServerProcess(parsedArgs); // 2
    }

    return null;
}

system_server 进程复制了 Zygote 进程的地址空间,因此也会得到 Zygote 进程创建的 Socket,这个 Socket 对于 system_server 进程没有任何用处,因此,需要在注释 1 处关闭 Socket 接着,在注释 2 处调用 handleSystemServerProcess 方法来启动 system_server 进程。handleSystemServerProcess 方法的代码如下所示:

// /frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
    
    
    ...
    if (parsedArgs.mInvokeWith != null) {
    
    
        ...
    } else {
    
    
        createSystemServerClassLoader(); // 1
        ClassLoader cl = sCachedSystemServerClassLoader;
        if (cl != null) {
    
    
            Thread.currentThread().setContextClassLoader(cl);
        }

        /*
         * Pass the remaining arguments to SystemServer.
         */
        return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
                                     parsedArgs.mRemainingArgs, cl); // 2
    }
}

private static void createSystemServerClassLoader() {
    
    
    if (sCachedSystemServerClassLoader != null) {
    
    
        return;
    }
    final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
    // TODO: Should we run optimization here?
    if (systemServerClasspath != null) {
    
    
        sCachedSystemServerClassLoader = createPathClassLoader(
            systemServerClasspath, VMRuntime.SDK_VERSION_CUR_DEVELOPMENT);
    }
}

在注释 1 处创建了 ClassLoader。在注释 2 处调用了 ZygoteInit.zygoteInit 方法,代码如下所示:

// /frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv,
                                        ClassLoader classLoader) {
    
    
    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(); // 1
    // 进入 system_server 的 main 方法
    return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader); // 2
}

在注释 1 处调用 ZygoteInit.nativeZygoteInit 方法,此处调用的是 Native 层的代码,用来启动 Binder 线程池,这样 ,system_server 进程就可以使用 Binder 与其他进程进行通信。注释 2 处是用于进入 system_servermain 方法。

以下分别说明

1 启动 Binder 线程池

ZygoteInit.nativeZygoteInit() 是一个 Native 方法,首先要了解它对应的 JNI 文件,如下所示:

// /frameworks/base/core/jni/AndroidRuntime.cpp
int register_com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env)
{
    
    
    const JNINativeMethod methods[] = {
    
    
        {
    
     "nativeZygoteInit", "()V",
         (void*) com_android_internal_os_ZygoteInit_nativeZygoteInit },
    };
    return jniRegisterNativeMethods(env, "com/android/internal/os/ZygoteInit",
                                    methods, NELEM(methods));
}

通过 JNImethods 数组,可以看出 nativeZygoteInit 方法对应的是 JNI 文件 AndroidRuntime.cppcom_android_internal_os_ZygoteInit_nativeZygoteInit 函数:

// /frameworks/base/core/jni/AndroidRuntime.cpp
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
    
    
    gCurRuntime->onZygoteInit();
}

gCurRuntimeAndroidRuntime 类型的指针,具体指向的是 AndroidRuntime 的子类 AppRuntime,在 app_main.cpp 中定义。接着来看 AppRuntime.onZygoteInit 方法,代码如下所示:

// /frameworks/base/cmds/app_process/app_main.cpp
virtual void onZygoteInit()
{
    
    
    sp<ProcessState> proc = ProcessState::self();
    ALOGV("App process: starting thread pool.\n");
    proc->startThreadPool(); // 1
}

注释 1 处的代码用来启动一个 Binder 线程池,这样 system_server 进程就可以使用 Binder 与其他进程通信了。因此,从这里可以知道 ZygoteInit.nativeZygoteInit() 函数主要是用来启动 Binder 线程池的。

2 进入 SystemServer.main 方法

查看 RuntimeInit.applicationInit 方法的源代码:

// /frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
                                          ClassLoader classLoader) {
    
    
    ...
    // Remaining arguments are passed to the start class's static main
    return findStaticMain(args.startClass, args.startArgs, classLoader);
}

RuntimeInit.applicationInit 方法中主要调用了 findStaticMain 方法:

// /frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
protected static Runnable findStaticMain(String className, String[] argv,
                                         ClassLoader classLoader) {
    
    
    Class<?> cl;

    try {
    
    
        // 通过反射得到 SystemServer 类
        cl = Class.forName(className, true, classLoader); // 1
    } 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 }); // 2
    } 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);
    }

    
    return new MethodAndArgsCaller(m, argv); // 3
}

注释 1 处的 classNamecom.android.server.SystemServer,通过反射返回的 clSystemServer 类。在注释 2 处找到 SystemServer.main 方法。在注释 3 处将找到的 main 方法传入到 MethodAndArgsCaller 中。

// /frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public static void main(String argv[]) {
    
    
    ...
    try {
    
    
        ...
        if (startSystemServer) {
    
    
            Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);

            // {@code r == null} in the parent (zygote) process, and {@code r != null} in the child (system_server) process.
            if (r != null) {
    
    
                r.run(); // 1
                return;
            }
        }
        ...
    } catch (Throwable ex) {
    
    
        Log.e(TAG, "System zygote died with exception", ex);
        throw ex;
    } finally {
    
    
        if (zygoteServer != null) {
    
    
            zygoteServer.closeServerSocket();
        }
    }
	...
}

通过注释 1 处的代码可以知道,在 ZygoteInit.main 方法中会获取 MethodAndArgsCaller 对象,并调用 MethodAndArgsCaller.run() 方法。MethodAndArgsCallerZygote 的静态内部类:

// /frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
static class MethodAndArgsCaller 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 }); // 1
        } 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);
        }
    }
}

注释 1 处的 mMethod 指的是 SystemServer.main 方法,调用了 mMethod.invoke 方法后,SystemServer.main 方法也会被动态调用。

2 解析 system_server 进程

以下是 SystemServer.main 方法:

// /frameworks/base/services/java/com/android/server/SystemServer.java 
public static void main(String[] args) {
    
    
    new SystemServer().run();
}

SystemServer.main 方法中只调用了 SystemServer().run() 方法:

// /frameworks/base/services/java/com/android/server/SystemServer.java 
private void run() {
    
    
    try {
    
    
        ...
        // 创建消息 Looper
        Looper.prepareMainLooper();
        Looper.getMainLooper().setSlowLogThresholdMs(
            SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);

        // Initialize native services. 加载了动态库 libandroid_servers.so
        System.loadLibrary("android_servers"); // 1
		...
        // Initialize the system context. 创建系统的 Context
        createSystemContext();

        // Create the system service manager.
        mSystemServiceManager = new SystemServiceManager(mSystemContext); // 2
        mSystemServiceManager.setStartInfo(mRuntimeRestart, mRuntimeStartElapsedTime, 
                                           mRuntimeStartUptime);
        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(); // 3 启动引导服务
        startCoreServices(); // 4 启动核心服务
        startOtherServices(); // 5 启动其他服务
        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");
}

在注释 1 加载了动态库 libandroid_servers.so。在注释 2 处创建 SystemServiceManager,她会对系统服务进行创建、启动和生命周期管理。在注释 3 处的 startBootstrapServices() 方法中回用 SystemServiceManager 启动 ActivityManagerServicePowerManagerServicePackageManagerService 等服务。在注释 4 处的 startCoreServices() 方法中则启动 DropBoxManagerServiceBatteryServiceUsageStateServiceWebViewUpdateService。在注释 5 处的 startOtherServices() 方法中启动了 CameraServiceAlarmManagerServiceVrManagerService 等服务。

从注释 345 处可以 看出, 官方把系统服务分为三种类型,分别是引导服务、核心服务和其他服务,其中,其他服务是一些非要紧的和不需要立即启动的服务。 系统服务总共 100 多个,以下是其中的部分服务:

图2

猜你喜欢

转载自blog.csdn.net/xingyu19911016/article/details/128619982