Androidシステム起動(3) - SystemServerプロセス

system_serverこのプロセスは主にシステム サービス、 、AMS、および を作成するために使用されWMSPMSすべてこのプロセスによって作成されます。具体的には、SystemServerプロセスが作成された後、主に次の作業を実行します。

  • Binderスレッド プールを開始して、他のプロセスと通信できるようにします。
  • CreateSystemServiceManagerは、システム サービスのライフ サイクルを作成、開始、管理するために使用されます。
  • さまざまなシステムサービスを開始します。

1Zygote加工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呼び出して処理を開始します。メソッドのコードは次のようになります。handleSystemServerProcesssystem_serverhandleSystemServerProcess

// /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が開始され、プロセスが他のプロセスとの通信に使用できるようになります。コメントは入力方法ですBindersystem_serverBinder2system_servermain

以下で説明します

1Binderスレッドプールを開始します

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

JNIの配列から、メソッドがファイルの関数に対応しているmethodsことがわかりますnativeZygoteInitJNIAndroidRuntime.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開始するために使用されますしたがって、ここから、この関数は主にスレッド プールを開始するために使用されることがわかります。Bindersystem_serverBinderZygoteInit.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リフレクションによって返される はクラスclです。SystemServerコメント内のメソッド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.mainMethodAndArgsCallerMethodAndArgsCaller.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.mainmMethod.invokeSystemServer.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コメントのメソッド内のstart などのサービスをstartBootstrapServices()再利用しますコメントのメソッド内で、 start および を実行します、などのサービスは、コメントされたメソッドで開始されますSystemServiceManagerActivityManagerServicePowerManagerServicePackageManagerService4startCoreServices()DropBoxManagerServiceBatteryServiceUsageStateServiceWebViewUpdateService5startOtherServices()CameraServiceAlarmManagerServiceVrManagerService

コメント3,からわかるように4正式なシステム サービスはブート サービス、コア サービス、その他のサービスの 3 種類に分かれており、このうちその他のサービスは起動する必要のない重要ではないサービスです。すぐに。合計で複数のシステム サービスがあり、その一部は次のとおりです。5100

図2

おすすめ

転載: blog.csdn.net/xingyu19911016/article/details/128619982