Android 11 SystemServer源码分析

SystemServer#main

上篇说过,system_server进程启动后会调用SystemServer#main方法,SystemServer#main非常的简单

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

我们再看SystemServer#run

private void run() {
    try {
        
        ...

        // The system server should never make non-oneway calls
        Binder.setWarnOnBlocking(true);

        ...

        // Increase the number of binder threads in system_server
        BinderInternal.setMaxThreads(sMaxBinderThreads);

        // Prepare the main looper thread (this thread).
        android.os.Process.setThreadPriority(
                android.os.Process.THREAD_PRIORITY_FOREGROUND);
        android.os.Process.setCanSelfBackground(false);
        Looper.prepareMainLooper();
        Looper.getMainLooper().setSlowLogThresholdMs(
                SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);

        SystemServiceRegistry.sEnableServiceNotFoundWtf = true;

        // Initialize native services.
        System.loadLibrary("android_servers");

        ...

        // Check whether we failed to shut down last time we tried.
        // This call may not return.
        performPendingShutdown();

        // Initialize the system context.
        createSystemContext();

        // Call per-process mainline module initialization.
        ActivityThread.initializeMainlineModules();

        // Create the system service manager.
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setStartInfo(mRuntimeRestart,
                mRuntimeStartElapsedTime, mRuntimeStartUptime);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        // Prepare the thread pool for init tasks that can be parallelized
        SystemServerInitThreadPool.start();

        ...

    } finally {
       ...
    }

    // Setup the default WTF handler
    RuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf);

    // Start services.
    try {
        startBootstrapServices(t);
        startCoreServices(t);
        startOtherServices(t);
    } catch (Throwable ex) {
        ...
    } finally {
        ...
    }

    ...

    // Loop forever.
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

可以看到run方法的工作主要要以下几点:

  1. 对Binder进行了一些设置,这个等到之后分析Binder的时候再看;
  2. performPendingShutdown:判断是否要关机或者重启;
  3. createSystemContext:创建系统上下文,这个留到分析Context的时候再看;
  4. 创建ServiceManager
  5. 开启各种服务,然后进入Looper消息循环

本文主要关注第5点。

performPendingShutdown

private void performPendingShutdown() {
    final String shutdownAction = SystemProperties.get(
            ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
    if (shutdownAction != null && shutdownAction.length() > 0) {
        boolean reboot = (shutdownAction.charAt(0) == '1');

        ...

        if (不需要关机或重启) {
            return;
        }

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                synchronized (this) {
                    ShutdownThread.rebootOrShutdown(null, reboot, reason);
                }
            }
        };

        // ShutdownThread must run on a looper capable of displaying the UI.
        Message msg = Message.obtain(UiThread.getHandler(), runnable);
        msg.setAsynchronous(true);
        UiThread.getHandler().sendMessage(msg);

    }
}

可以看出,主要是根据ShutdownThread.SHUTDOWN_ACTION_PROPERTY属性值来判断是否需要关机或重启

startBootstrapServices

startBootstrapServices主要是启动最重要的相互依赖的关键性的系统服务,比如ActivityManagerService、PackageManagerService、UserManagerService和PowerManagerService等等。
由于SystemServer启动的服务非常众多,我们不可能一下子每个都去了解完,这里我们只关注几个常用的核心服务以及SystemServer的启动阶段即可。后续再去具体分析ActivityManagerService等的具体工作流程。

private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {

    // 启动ActivityManagerService
    ActivityTaskManagerService atm = mSystemServiceManager.startService(
            ActivityTaskManagerService.Lifecycle.class).getService();
    mActivityManagerService = ActivityManagerService.Lifecycle.startService(
            mSystemServiceManager, atm);
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);
    mWindowManagerGlobalLock = atm.getGlobalLock();

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

    // 
    mActivityManagerService.initPowerManagement();

    mSystemServiceManager.startService(LightsService.class);
    
    mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

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

    // 启动PackageManagerService
    mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
}

上面代码精简了非常多的代码,只保留了一下常见的服务启动相关代码。值得注意的是,DisplayManagerService启动后,SystemServer进入PHASE_WAIT_FOR_DEFAULT_DISPLAY阶段。也就是这句

mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

startCoreServices

startCoreServices中启动了没有在startBootstrapServices启动的核心服务

private void startCoreServices(@NonNull TimingsTraceAndSlog t) {

    // Service for system config
    mSystemServiceManager.startService(SystemConfigService.class);

    // Tracks the battery level.  Requires LightService.
    mSystemServiceManager.startService(BatteryService.class);

    // Tracks application usage stats.
    mSystemServiceManager.startService(UsageStatsService.class);
    mActivityManagerService.setUsageStatsManager(
            LocalServices.getService(UsageStatsManagerInternal.class));

    // Tracks whether the updatable WebView is in a ready state and watches for update installs.
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
        mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
    }

    // Tracks and caches the device state.
    mSystemServiceManager.startService(CachedDeviceStateService.class);

    // Tracks cpu time spent in binder calls
    mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);

    // Tracks time spent in handling messages in handlers.
    mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);

    // Manages apk rollbacks.
    mSystemServiceManager.startService(ROLLBACK_MANAGER_SERVICE_CLASS);

    // Service to capture bugreports.
    mSystemServiceManager.startService(BugreportManagerService.class);

    // Serivce for GPU and GPU driver.
    mSystemServiceManager.startService(GpuService.class);
}

startCoreServices启动的服务不多,这里精简了log相关代码。可以看到电池服务、GPU相关服务、BugReport等都在这里启动。

startOtherServices

startOtherServices非常庞大,有1400+行代码,启动了几十上百个服务,其中我们比较常见的应该是ConnectivityService、WindowManagerService

private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
    
    ...

    t.traceBegin("MakeLockSettingsServiceReady");
    if (lockSettings != null) {
        try {
            lockSettings.systemReady();
        } catch (Throwable e) {
            reportWtf("making Lock Settings Service ready", e);
        }
    }
    t.traceEnd();

    
    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_LOCK_SETTINGS_READY);
    // 这两个阶段中间什么也没有做
    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_SYSTEM_SERVICES_READY);

    // Start device specific services
    final String[] classes = mSystemContext.getResources().getStringArray(
            R.array.config_deviceSpecificSystemServices);
    for (final String className : classes) {
        try {
            mSystemServiceManager.startService(className);
        } catch (Throwable e) {
            reportWtf("starting " + className, e);
        }
    }

    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);

    
    mActivityManagerService.systemReady(() -> {
        
        mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);
        
        
        try {
            startSystemUi(context, windowManagerF);
        } catch (Throwable e) {
            reportWtf("starting System UI", e);
        }
        

        // Wait for all packages to be prepared
        mPackageManagerService.waitForAppDataPrepared();

        
        // confirm webview completion before starting 3rd party
        if (webviewPrep != null) {
            ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);
        }
        mSystemServiceManager.startBootPhase(t, SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);

    }, t);

    t.traceEnd(); // startOtherServices
}

可以看到在调用lockSettings.systemReady()之后进入了PHASE_LOCK_SETTINGS_READY和PHASE_SYSTEM_SERVICES_READY,这两个阶段什么都没有做。
“device specific services”看来应该是一组服务,此处暂不深究。这一组服务启动后,进入PHASE_DEVICE_SPECIFIC_SERVICES_READY阶段。
startOtherServices方法的最后调用了ActivityManagerService#systemReady,并在回调中启动了SystemUi。跟进一下

public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
    mSystemServiceManager.preSystemReady();
    synchronized(this) {
        if (mSystemReady) {
            // If we're done calling all the receivers, run the next "boot phase" passed in
            // by the SystemServer
            if (goingCallback != null) {
                goingCallback.run();
            }
            return;
        }

        ...
    }

    ...

    if (bootingSystemUser) {
        t.traceBegin("startHomeOnAllDisplays");
        mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
        t.traceEnd();
    }

    ...
}

可以看到,在调用SystemServiceManager#preSystemReady()就运行了回调,进了PHASE_ACTIVITY_MANAGER_READY阶段。随后启动了SystemUi,这个后续分析SystemUi的时候再深入了解。
另外,在webview就绪之后,进入了PHASE_THIRD_PARTY_APPS_CAN_START阶段,可以启动第三方App了。
值得注意的是,Launcher的启动也是由这里开始:

mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");

SystemServer的启动还有最后一个阶段,发生在ActivityManagerService#finishBooting方法中

final void finishBooting() {
    
    ...

    // Let system services know.
    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_BOOT_COMPLETED);

    ...

    synchronized (this) {
           
        ...

        // 发送系统启动完成通知,包括我们熟悉的开机广播
        mUserController.sendBootCompleted(
                new IIntentReceiver.Stub() {
                    @Override
                    public void performReceive(Intent intent, int resultCode,
                            String data, Bundle extras, boolean ordered,
                            boolean sticky, int sendingUser) {
                        synchronized (ActivityManagerService.this) {
                            mOomAdjuster.mCachedAppOptimizer.compactAllSystem();
                            requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
                        }
                    }
                });
        maybeLogUserspaceRebootEvent();
        mUserController.scheduleStartProfiles();
    }
}

至此,系统服务启动完成。我们熟悉的开机广播也是在这里发出的。

SystemServer启动流程

不同版本的SystemServer启动流程会有一些差别,比如WatchDog的启动时机等等。这里分析的是Android 11中的SystemServer。我们注意到在每个启动阶段都会调用SystemServiceManager#startBootPhase方法,其定义如下:

public void startBootPhase(@NonNull TimingsTraceAndSlog t, int phase) {
    ...

    mCurrentPhase = phase;

    Slog.i(TAG, "Starting phase " + mCurrentPhase);
    try {
        t.traceBegin("OnBootPhase_" + phase);
        final int serviceLen = mServices.size();
        for (int i = 0; i < serviceLen; i++) {
            final SystemService service = mServices.get(i);
            ...
            service.onBootPhase(mCurrentPhase);
            ...
        }
    } finally {
        t.traceEnd();
    }

    ...
}

其主要工作是遍历和调用每个Service的onBootPhase方法,让系统服务知晓当前启动阶段并可以执行相应的操作。

各个阶段的定义位于SystemService.java内:

public abstract class SystemService {

    /*
     * The earliest boot phase the system send to system services on boot.
     */
    public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100;

    /**
     * After receiving this boot phase, services can obtain lock settings data.
     */
    public static final int PHASE_LOCK_SETTINGS_READY = 480;

    /**
     * After receiving this boot phase, services can safely call into core system services
     * such as the PowerManager or PackageManager.
     */
    public static final int PHASE_SYSTEM_SERVICES_READY = 500;

    /**
     * After receiving this boot phase, services can safely call into device specific services.
     */
    public static final int PHASE_DEVICE_SPECIFIC_SERVICES_READY = 520;

    /**
     * After receiving this boot phase, services can broadcast Intents.
     */
    public static final int PHASE_ACTIVITY_MANAGER_READY = 550;

    /**
     * After receiving this boot phase, services can start/bind to third party apps.
     * Apps will be able to make Binder calls into services at this point.
     */
    public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;

    /**
     * After receiving this boot phase, services can allow user interaction with the device.
     * This phase occurs when boot has completed and the home application has started.
     * System services may prefer to listen to this phase rather than registering a
     * broadcast receiver for {@link android.content.Intent#ACTION_LOCKED_BOOT_COMPLETED}
     * to reduce overall latency.
     */
    public static final int PHASE_BOOT_COMPLETED = 1000;
}

PHASE_WAIT_FOR_DEFAULT_DISPLAY: 已启动ActivityManagerService、PowerManagerService、LightsService、DisplayManagerService等核心引导服务

PHASE_LOCK_SETTINGS_READY:已完成核心服务的启动,LockSettingsService已经就绪

PHASE_SYSTEM_SERVICES_READY:系统核心服务已经就绪,可以为其他Service提供服务了

PHASE_DEVICE_SPECIFIC_SERVICES_READY:设备特定服务组已经就绪

PHASE_ACTIVITY_MANAGER_READY:ActivityManagerService就绪,可以发送广播了

PHASE_THIRD_PARTY_APPS_CAN_START:服务可以启动或者bind第三方App,App可以通过Binder调用系统服务了

PHASE_BOOT_COMPLETED:开机完成,可以相应用户交互了。系统服务应该监听PHASE_BOOT_COMPLETED流程而不是等待ACTION_LOCKED_BOOT_COMPLETED广播。

总结

SystemServer是系统非常重要的进程,牵涉非常广泛,但是大部分功能都封装在对应的Service里,所以SystemServer.java本身代码量并不是很多,总体流程也不算很复杂。接下来会深入我们常见的服务,一探究竟。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值