Android system startup (3) - SystemServer process

system_serverThe process is mainly used to create system services, AMS, WMS, PMSand are all created by it. Specifically, SystemServerafter the process is created, it mainly does the following work:

  • Start Binderthe thread pool so that it can communicate with other processes;
  • Create SystemServiceManager, used to create, start and manage the life cycle of system services;
  • Start various system services;

1 Zygoteprocessing system_serverprocess

As mentioned in the Zygote process startup processZygoteInit.main , in the method, the process forkSystemServeris started by calling the method system_server, some related timing diagrams:

figure 1

ZygoteInit.forkSystemServerThe code looks like this:

// /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_serverThe process copies Zygotethe address space of the process, so it will also be Zygotecreated by the process Socket, which has no use Socketfor the process, so it needs to be closed at the comment . system_server1SocketNext, 2call handleSystemServerProcessthe method at the comment to start system_serverthe process. handleSystemServerProcessThe code for the method looks like this:

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

1Created at comment ClassLoader. 2The method is called at the comment ZygoteInit.zygoteInit, and the code is as follows:

// /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
}

1Call the method at the comment ZygoteInit.nativeZygoteInit, where Nativethe code of the layer is called to start Binderthe thread pool, so that system_serverthe process can use to Bindercommunicate with other processes. The comment 2is the method used to system_serverenter main.

Described below

1 Start Binderthe thread pool

ZygoteInit.nativeZygoteInit()is a Nativemethod, you must first understand its corresponding JNIfile, as follows:

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

Through the array JNIof methods, it can be seen that nativeZygoteInitthe method corresponds to the function of JNIthe file :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();
}

gCurRuntimeis AndroidRuntimea pointer of type, specifically pointing to AndroidRuntimea subclass of AppRuntimeand app_main.cppdefined in . Next, look at AppRuntime.onZygoteInitthe method, the code is as follows:

// /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
}

The code at comment 1is used to start a Binderthread pool so that system_serverprocesses can use to Bindercommunicate with other processes. Therefore, we can know from here ZygoteInit.nativeZygoteInit()that the function is mainly used to start Binderthe thread pool.

2 access SystemServer.mainmethod

View RuntimeInit.applicationInitthe source code of the method:

// /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.applicationInitThe method is mainly called in the method 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
}

1The at the comment classNameis com.android.server.SystemServer, and the returned by reflection clis SystemServerthe class. 2Find the method in the comments SystemServer.main. Pass the method 3found at the comment into the .mainMethodAndArgsCaller

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

From 1the code in the comment, we can know that the object ZygoteInit.mainwill be obtained in the method MethodAndArgsCaller, and MethodAndArgsCaller.run()the method will be called. MethodAndArgsCalleris Zygotea static inner class of :

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

1The in the comment mMethodrefers to SystemServer.mainthe method. After the method is called mMethod.invoke, SystemServer.mainthe method will also be called dynamically.

2 parsing system_serverprocess

Here is SystemServer.mainthe method:

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

SystemServer.mainOnly the method is called in the method 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");
}

1The dynamic library is loaded in the comment libandroid_servers.so. 2Created in comments SystemServiceManager, she will create, start and lifecycle manage system services. Reuse services such as start , , and so on in the method 3at the comment . In the method at the comment then start , , and . The , , etc. services are started in the commented method .startBootstrapServices()SystemServiceManagerActivityManagerServicePowerManagerServicePackageManagerService4startCoreServices()DropBoxManagerServiceBatteryServiceUsageStateServiceWebViewUpdateService5startOtherServices()CameraServiceAlarmManagerServiceVrManagerService

It can be seen from the comments 3, 4, that the official system services are divided into three types, namely boot services, core services and other services, among which other services are some non-important services that do not need to be started immediately. There are a total of multiple system services , some of which are as follows:5100

figure 2

Guess you like

Origin blog.csdn.net/xingyu19911016/article/details/128619982