14

Android SystemServer启动(二)

 3 years ago
source link: https://mp.weixin.qq.com/s?__biz=MzIzNTc5NDY4Nw%3D%3D&%3Bmid=2247484991&%3Bidx=1&%3Bsn=7a4701c30ade3569c75591a12644c4f3
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

小憩第53篇原创文章

2020年最后一天,这糟糕的2020年终于过去了。

都说灾难之后都将迎来大幸运,在这里预祝大家元旦快乐,让我们拥有美好的2021。

Android init 启动

Android Linux Zygote启动

Android Java Zygote启动

Android SystemServer启动(一)

继续上篇文章的 SystemServer 启动分析。

此次分析过程基于Android 10.0

run

在之前已经分析到,通过 SystemServerrun 方法进入到 SystemServer 内部逻辑。

所以我们直接来看 run 方法

private void run() {
    try {
        traceBeginAndSlog("InitBeforeStartServices");
        ...
        ...
        
        // 创建Looper
        Looper.prepareMainLooper();
        Looper.getMainLooper().setSlowLogThresholdMs(
                SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);

        // 初始化native service
        System.loadLibrary("android_servers");

        performPendingShutdown();

        // 创建system context
        createSystemContext();

        // 创建SystemServiceManager
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setStartInfo(mRuntimeRestart,
                mRuntimeStartElapsedTime, mRuntimeStartUptime);
        
        // 添加到本地LocalServices中,以便后续获取对应的服务对象
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        SystemServerInitThreadPool.get();
    } finally {
        traceEnd();  // InitBeforeStartServices
    }

    // 启动各项services
    try {
        traceBeginAndSlog("StartServices");
        startBootstrapServices();
        startCoreServices();
        startOtherServices();
        SystemServerInitThreadPool.shutdown();
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    } finally {
        traceEnd();
    }

    StrictMode.initVmDefaults(null);

    if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
        int uptimeMillis = (int) SystemClock.elapsedRealtime();
        MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
        final int MAX_UPTIME_MILLIS = 60 * 1000;
        if (uptimeMillis > MAX_UPTIME_MILLIS) {
            Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
                    "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
        }
    }

    // 开启loop循环,等待消息的来临
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

SystemServerrun 方法中主要做的事情是:

  1. 创建当前线程的 Looper
  2. 加载 native services 原生库 android_servers
  3. SystemContext
    ActivityThread
    SystemContext
    
  4. 创建 SystemServiceManager ,用来启动后续的各项服务
  5. 开启各项服务

  6. 开启 Looper 循环,等待消息的来临并执行

SystemContext

其中 SystemContext 的创建是通过 ActivityThread 来获取的

private void createSystemContext() {
    ActivityThread activityThread = ActivityThread.systemMain();
    mSystemContext = activityThread.getSystemContext();
    mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

    final Context systemUiContext = activityThread.getSystemUiContext();
    systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}

最终获取到的 SystemContext 是由 ContextImpl 创建的

public ContextImpl getSystemContext() {
    synchronized (this) {
        if (mSystemContext == null) {
            mSystemContext = ContextImpl.createSystemContext(this);
        }
        return mSystemContext;
    }
}

SystemServiceManager

它是 SystemServer 的服务大管家,提供启动服务的相关方法。

主要涉及的方法有

  1. startService : 通过反射创建相关服务,并且调用对应服务的 onStart() 方法来开启服务
  2. startBootPhase : 开启特殊的启动阶段节点,各项服务会根据不同的阶段节点执行不同的逻辑。

启动的阶段节点分别为:

// 启动阶段,初始化一些默认展示
public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100;

// 该启动阶段将会锁定setting数据
public static final int PHASE_LOCK_SETTINGS_READY = 480;

// 该启动阶段将会调用核心的system services,例如PowerManager与PackageManager
public static final int PHASE_SYSTEM_SERVICES_READY = 500;

// 该启动阶段将会调用设备特殊服务
public static final int PHASE_DEVICE_SPECIFIC_SERVICES_READY = 520;

// 该启动阶段将会将会发送服务广播
public static final int PHASE_ACTIVITY_MANAGER_READY = 550;

// 该启动阶段将会启动不绑定三方app
public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;

// 该启动阶段标志着启动完成,用户可以进行设备交互,应用桌面已经启动
public static final int PHASE_BOOT_COMPLETED = 1000;

这些启动阶段会穿插在各项的服务启动序列中,每一个启动阶段节点的插入,都会伴随着该启动阶段节点之前的服务执行相关逻辑。

所以这里启动阶段节点相对于标识或者说依赖关系,即后续的启动阶段需要依赖于前面某些服务的特色处理逻辑之后才能进行。

而这些启动阶段的节点体现都分布在这些方法中

traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();

具体的节点插入时机为

private void startBootstrapServices() {
        mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
}

private void startCoreServices() {
        ...
}

private void startOtherServices() {
        mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);

        mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);

        mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);

        mActivityManagerService.systemReady(() -> {
            mSystemServiceManager.startBootPhase(
                    SystemService.PHASE_ACTIVITY_MANAGER_READY);        
            
            mSystemServiceManager.startBootPhase(
                    SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
        }
}

对应的响应各个阶段的处理逻辑是在对应 serviceonBootPhase() 方法中

public void onBootPhase(int phase) {
 ...
}

下面我们来看下各个阶段都启动了哪些服务。

startBootstrapServices

private void startBootstrapServices() {
    final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
    traceBeginAndSlog(TAG_SYSTEM_CONFIG);
    SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
    traceEnd();

    // 启动Installer
    Installer installer = mSystemServiceManager.startService(Installer.class);

    // 启动DeviceIdentifiersPolicyService
    mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);

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

    // 启动PowerManagerService
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

    // 初始化PowerManager
    mActivityManagerService.initPowerManagement();

    // 启动RecoverySystemService
    mSystemServiceManager.startService(RecoverySystemService.class);

    RescueParty.noteBoot(mSystemContext);

    // 启动LightsService
    mSystemServiceManager.startService(LightsService.class);

    // 启动SidekickService
    if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
        mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
    }

    // 启动DisplayManagerService
    mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

    // 插入启动阶段节点,执行对应的节点逻辑
    mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
    
    ...
    ...
}

在开始插入启动阶段节点之前,也可以称之为 BootPhase 0 ,启动的服务有:

Installer
DeviceIdentifiersPolicyService
UriGrantsManagerService
ActivityManagerService
PowerManagerService
RecoverySystemService
LightsService
DisplayManagerService

由于 PackageManager 启动需要 DisplayManagerService 的相关信息,所以设置 BootPhase 100 ,执行 DisplayManagerService 中的 onBootPhase 方法来处理 BootPhase 100 的逻辑

public void onBootPhase(int phase) {
    if (phase == PHASE_WAIT_FOR_DEFAULT_DISPLAY) {
        synchronized (mSyncRoot) {
            long timeout = SystemClock.uptimeMillis()
                    + mInjector.getDefaultDisplayDelayTimeout();
            while (mLogicalDisplays.get(Display.DEFAULT_DISPLAY) == null ||
                    mVirtualDisplayAdapter == null) {
                long delay = timeout - SystemClock.uptimeMillis();
                if (delay <= 0) {
                    throw new RuntimeException("Timeout waiting for default display "
                            + "to be initialized. DefaultDisplay="
                            + mLogicalDisplays.get(Display.DEFAULT_DISPLAY)
                            + ", mVirtualDisplayAdapter=" + mVirtualDisplayAdapter);
                }
                if (DEBUG) {
                    Slog.d(TAG, "waitForDefaultDisplay: waiting, timeout=" + delay);
                }
                try {
                    mSyncRoot.wait(delay);
                } catch (InterruptedException ex) {
                }
            }
        }
    }
}

处理完之后继续启动 PackageManagerService 与其他的服务。

BootPhase 100BootPhase 480 会启动大量的服务。

包括初始化的服务、核心服务与其他服务。分别从 startBootstrapServicesstartCoreServicesstartOtherServices

private void startBootstrapServices() {
    ...
    ...

    // BootPhase 100

    // 启动PackageManagerService
    try {
        Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    } finally {
        Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
    }
    mFirstBoot = mPackageManagerService.isFirstBoot();
    mPackageManager = mSystemContext.getPackageManager();

    // 启动UserManagerService,创建/data/user/ 目录
    mSystemServiceManager.startService(UserManagerService.LifeCycle.class);

    // 设置AMS
    mActivityManagerService.setSystemProcess();

    // 启动OverlayManagerService
    mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));

    // 启动SensorPrivacyService,传感器
    mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext));

    ...
}

BootPhase 100 阶段, startBootstrapServices 启动以下服务

PackageManagerService
UserManagerService
OverlayManagerService
SensorPrivacyService

随后进入 startCoreServices

startCoreServices

private void startCoreServices() {
    // 启动BatterService, 管理电量,需要LightService
    mSystemServiceManager.startService(BatteryService.class);

    // 启动UsageStatsService,统计应用使用情况
    mSystemServiceManager.startService(UsageStatsService.class);
    mActivityManagerService.setUsageStatsManager(
            LocalServices.getService(UsageStatsManagerInternal.class));

    // 启动WebViewUpdateService, 管理WebView更新
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
        mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
    }

    // 启动CachedDeviceStateService, 缓存设备状态
    mSystemServiceManager.startService(CachedDeviceStateService.class);

    // 启动BinderCallsStatsService, 记录cpu在binder回调中花费的时间
    mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);

    // 启动LooperStatsService, 记录使用handler message花费的时间
    mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);

    // 启动RollbackManagerService,管理apk回卷
    mSystemServiceManager.startService(RollbackManagerService.class);

    // 启动BugreportManagerService, 捕获bug的报告
    mSystemServiceManager.startService(BugreportManagerService.class);

    // 启动GpuService, 管理GPU
    mSystemServiceManager.startService(GpuService.class);

}

// BootPhase 100 启动的服务
UsageStatsService
WebViewUpdateService
CachedDeviceStateService
BinderCallsStatsService
LooperStatsService
RollbackManagerService
BugreportManagerService
GpuService

以上是启动的核心服务;继续进入 startOtherServices

startOtherServices

    private void startOtherServices() {
        final Context context = mSystemContext; // 获取Context

        try {

            ServiceManager.addService("sec_key_att_app_id_provider",
                    new KeyAttestationApplicationIdProviderService(context));

            mSystemServiceManager.startService(KeyChainSystemService.class);

            ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());

            mSystemServiceManager.startService(TelecomLoaderService.class);

            telephonyRegistry = new TelephonyRegistry(context);
            ServiceManager.addService("telephony.registry", telephonyRegistry);

            mEntropyMixer = new EntropyMixer(context);

            mContentResolver = context.getContentResolver(); // 获取ContentResolver

            mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);

            mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);

            mActivityManagerService.installSystemProviders(); // 安装系统Provider

            ...

            mSystemServiceManager.startService(new AlarmManagerService(context)); // 闹钟服务

            ...

            mActivityManagerService.setWindowManager(wm); // 设置WindowManager

            ...

        }

        ...

        // 进入安全模式
        if (safeMode) {
            mActivityManagerService.enterSafeMode();
        }

        ...
        ...

        // BootPhase  480
        mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);

        // BootPhase 500
        mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);


        // BootPhase 520
        mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);

        try {
            wm.systemReady();
        } catch (Throwable e) {
            reportWtf("making Window Manager Service ready", e);
        }

        if (safeMode) {
            mActivityManagerService.showSafeModeOverlay();
        }

        // 更新Configuration
        final Configuration config = wm.computeNewConfiguration(DEFAULT_DISPLAY);
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        w.getDefaultDisplay().getMetrics(metrics);
        context.getResources().updateConfiguration(config, metrics);

        final Theme systemTheme = context.getTheme();
        if (systemTheme.getChangingConfigurations() != 0) {
            systemTheme.rebase();
        }

        try {
            mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
        } catch (Throwable e) {
            reportWtf("making Power Manager Service ready", e);
        }

        mSystemServiceManager.startService(PermissionPolicyService.class);

        mPackageManagerService.systemReady();

        ...

        mActivityManagerService.systemReady(() -> {
            
            // BootPhase 550
            mSystemServiceManager.startBootPhase(
                    SystemService.PHASE_ACTIVITY_MANAGER_READY);

            try {
                mActivityManagerService.startObservingNativeCrashes();
            } catch (Throwable e) {
                reportWtf("observing native crashes", e);
            }

            traceBeginAndSlog("MakeConnectivityServiceReady");
            try {
                if (connectivityF != null) {
                    connectivityF.systemReady();
                }
            } catch (Throwable e) {
                reportWtf("making Connectivity Service ready", e);
            }

            ...
            
            // BootPhase 600
            mSystemServiceManager.startBootPhase(
                    SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);

            try {
                if (locationF != null) {
                    locationF.systemRunning();
                }
            } catch (Throwable e) {
                reportWtf("Notifying Location Service running", e);
            }

            try {
                if (countryDetectorF != null) {
                    countryDetectorF.systemRunning();
                }
            } catch (Throwable e) {
                reportWtf("Notifying CountryDetectorService running", e);
            }

            ...

        }, BOOT_TIMINGS_TRACE_LOG);

    }

startOtherServices 中启动了大量服务,总共差不多有 80 多种,这里就不一一列举出来。

我这里将其与 BootPhase 做了个归总,来看一下各个启动阶段节点都启动了哪些服务与对应服务的操作。

// BootPhase 100
KeyAttestationApplicationIdProviderService (startOtherServices)
KeyChainSystemService 
SchedulingPolicyService
TelecomLoaderService
TelephonyRegistry
EntropyMixer
AccountManagerService
ContentService

...(大量服务)

AppBindingService

BootPhase 480

BootPhase 500

PermissionPolicyService
DeviceSpecificServices(包含大量Service)

// 准备好 Power、Package与Diaplay服务
PowerManagerService.systemReady
PackageManagerService.systemReady
DisplayManagerService.systemReady

BootPhase 520

BootPhase 550

CarServiceHelperService
startSystemUi

// 准备好 Network、Ip、Connectivity服务
NetworkManagementService.systemReady
NetworkPolicyManagerService.systemReady
IpSecService.systemReady
NetworkStatsService.systemReady
ConnectivityService.systemReady
NetworkPolicyService.systemReady


BootPhase 600
 
NetworkStack

// 运行Location、CountryDetection、Network、Input、Telephoney、Media、Mms、Incident服务
LocationService.systemRunning
CountryDetectionService.systemRunning
NetworkTimeUpdateService.systemRunning
InputManagerService.systemRunning
TelephonyRegistry.systemRunning
MediaRouterService.systemRunning
MmsServiceBroker.systemRunning
IncidentDaemon.systemRunning

最后经过以上一系列的服务调用,会调用 ActivityManagerServicefinishBooting 方法来执行最后一个 BootPhase 1000

final void finishBooting() {
    ...

    // BootPhase 1000
    mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED);

    ...
}

至此,系统服务启动阶段完成就绪, system_server 进程启动完成则进入 Looper.loop() 状态,等待消息队列 MessageQueue 中的消息到来,然后执行对应的 Message

以上是 SystemService 的启动过程,主要通过 BootPhase 0 ~ BootPhase 1000 来分别启动不同的 Service ,根据不同的 BootPhase ,相应的 Service 执行不同的逻辑。后续 Service 启动逻辑与执行逻辑可能依赖于之前的 Service ,而它们之间的依赖管理是通过 BootPhase 来建立的。

推荐阅读

Kotlin协程实现原理:挂起与恢复

Jetpack:DataStore必知的几个优点

算法之旅:复杂度分析

QrQfuuq.png!mobile


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK