Android Framework 之 SystemServer进程

SystemServer进程在android系统中占了举足轻重的地位,系统的所有服务和SystemUI都是由它启动。

一、SystemServer进程主函数流程

1、主函数三部曲

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

SystemServer的入口函数同样是main,调用顺序先是构造函数,再是run,构造函数没有什么重点地方后文dump详细介绍,主要流程主要还是run方法。run里面哦流程其实还是遵循普遍的三部曲:初始化上下文->启动服务->进入loop循环

1)初始化上下文

//frameworks/base/services/java/com/android/server/SystemServer.java    
    private void run() {
        TimingsTraceAndSlog t = new TimingsTraceAndSlog();
        try {
            t.traceBegin("InitBeforeStartServices");
        //.....一些属性的初始化....
            // The system server should never make non-oneway calls
            Binder.setWarnOnBlocking(true);
            // The system server should always load safe labels
            PackageItemInfo.forceSafeLabels();
            // Default to FULL within the system server.
            SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;
            // Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
            SQLiteCompatibilityWalFlags.init(null);
            // Here we go! 
            Slog.i(TAG, "Entered the Android system server!");
            final long uptimeMillis = SystemClock.elapsedRealtime(); //记录开始启动的时间错,调试系统启动时间的时候需要关注
            // Mmmmmm... more memory!
            VMRuntime.getRuntime().clearGrowthLimit();
            // Some devices rely on runtime fingerprint generation, so make sure we've defined it before booting further.
            Build.ensureFingerprintProperty();
            // Within the system server, it is an error to access Environment paths without explicitly specifying a user.
            Environment.setUserRequired(true);
            // Within the system server, any incoming Bundles should be defused to avoid throwing BadParcelableException.
            BaseBundle.setShouldDefuse(true);
            // Within the system server, when parceling exceptions, include the stack trace
            Parcel.setStackTraceParceling(true);
            // Ensure binder calls into the system always run at foreground priority.
            BinderInternal.disableBackgroundScheduling(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");
            // Allow heap / perf profiling.
            initZygoteChildHeapProfiling();
            // 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();
       } finally {
            t.traceEnd();  // InitBeforeStartServices
        }

2)启动系统所有服务

//frameworks/base/services/java/com/android/server/SystemServer.java    
        // Start services.
        try {
            t.traceBegin("StartServices");
            startBootstrapServices(t);   //启动BOOT服务(即没有这些服务系统无法运行)
            startCoreServices(t);        //启动核心服务
            startOtherServices(t);       //启动其他服务
            startApexServices(t);        //启动APEX服务,此服务必现要在前面的所有服务启动之后才能启动,为了防止OTA相关问题
            // Only update the timeout after starting all the services so that we use
            // the default timeout to start system server.
            updateWatchdogTimeout(t);
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {
            t.traceEnd(); // StartServices
        }
    /**
     * Starts system services defined in apexes.
     * <p>Apex services must be the last category of services to start. No other service must be
     * starting after this point. This is to prevent unnecessary stability issues when these apexes
     * are updated outside of OTA; and to avoid breaking dependencies from system into apexes.
     */
    private void startApexServices(@NonNull TimingsTraceAndSlog t) {
        t.traceBegin("startApexServices");
        // TODO(b/192880996): get the list from "android" package, once the manifest entries are migrated to system manifest.
        List<ApexSystemServiceInfo> services = ApexManager.getInstance().getApexSystemServices();
        for (ApexSystemServiceInfo info : services) {
            String name = info.getName();
            String jarPath = info.getJarPath();
            t.traceBegin("starting " + name);
            if (TextUtils.isEmpty(jarPath)) {
                mSystemServiceManager.startService(name);
            } else {
                mSystemServiceManager.startServiceFromJar(name, jarPath);
            }
            t.traceEnd();
        }
        // make sure no other services are started after this point
        mSystemServiceManager.sealStartedServices();
        t.traceEnd(); // startApexServices
    }

如上代码大体启动了四类服务:

  • startBootstrapServices:启动一些关键引导服务,这些服务耦合到一起
  • startCoreServices:启动一些关键引导服务,这些服务没有耦合到一起
  • startOtherServices:启动其他一些杂七杂八的服务
  • startApexServices:启动apex类的服务,其实就是mainline那些东西,详情参考请点击我

另外,我找到了一篇文章专门记录了所有的服务:Android10.0 Framework层服务一览表_android contexthub-CSDN博客

3)进入loop循环

//frameworks/base/services/java/com/android/server/SystemServer.java
        StrictMode.initVmDefaults(null);
        if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
            final long uptimeMillis = SystemClock.elapsedRealtime();
            final long maxUptimeMillis = 60 * 1000;
            if (uptimeMillis > maxUptimeMillis) {
                Slog.wtf(SYSTEM_SERVER_TIMING_TAG, "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
            }
        }
        // Loop forever.
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");

和之前讲的binder一样,基本上所有的进程最后都会进入loop进行循环,轮询主线程相关的handle消息和binder消息,如下日志堆栈,表示handle消息处理过程中发生异常:

2、顺序启动服务

1)startBootstrapServices阶段

启动看门狗->启动AMS:

//开始启动Bootstrap服务
//t.traceBegin("ArtModuleServiceInitializer");
//注册artd服务:这是Android系统中用于支持Android Runtime的后台守护进程
ArtModuleServiceInitializer.setArtModuleServiceManager(new ArtModuleServiceManager());
//启动watchdog:这是Android系统framework层使用的看门狗
final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();
//读取SYSTEM配置:详见后续章节
SystemServerInitThreadPool.submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
//启动platform_compat和platform_compat_native服务:底层兼容性相关服务,当前只有AMS和PMS用到了它
PlatformCompat platformCompat = new PlatformCompat(mSystemContext);
ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE, platformCompat);
ServiceManager.addService(Context.PLATFORM_COMPAT_NATIVE_SERVICE, new PlatformCompatNative(platformCompat));
//启动file_integrity服务:跟文件加密校验等相关,该服务需要依赖keystore
mSystemServiceManager.startService(FileIntegrityService.class);
//启动installd服务:该服务直接影响应用程序的安装和管理,在后续AMS和PKMS启动的时候会使用到
Installer installer = mSystemServiceManager.startService(Installer.class);
//启动device_identifiers服务:该服务管理设备标识符(例如设备序列号/IMEI)的生成存储访问策略
mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
//启动uri_grants服务:用于管理URI授权相关任务,控制应用程序之间共享数据时的URI访问权限确保系统安全
mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);
//启动powerstats服务:该服务监控和管理设备的能耗统计信息,涉及收集、分析和报告应用程序和系统组件的能耗数据
mSystemServiceManager.startService(PowerStatsService.class);
//调用native方法:android_server_SystemServer_startIStatsService
startIStatsService();
startMemtrackProxyService();
//实际上启动了AppOpService和PermissionService服务,他们用于管理应用程序操作权限
mSystemServiceManager.startService(AccessCheckingService.class);
//启动ams服务
ActivityTaskManagerService atm = mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();

启动AMS->启动PMS:

//启动dataloader_manager服务:用于管理data目录加载相关的服务,在PMS启动之前要先启动它
mDataLoaderManagerService = mSystemServiceManager.startService(DataLoaderManagerService.class);
// Incremental service needs to be started before package manager
mIncrementalServiceHandle = startIncrementalService();
//启动pms服务:电源管理相关的服务,包括息屏和亮屏,开机和关机等操作
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
//启动thermalservice服务:温控相关的服务
mSystemServiceManager.startService(ThermalManagerService.class);
//启动performance_hint服务:
mSystemServiceManager.startService(HintManagerService.class);
//让AMS和PMS建立联系
mActivityManagerService.initPowerManagement();

启动PMS->启动DMS:

//启动recovery服务:用户系统恢复相关的服务,init进程可以通过/system/bin/uncrypt触发OTA包解密
mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class);
//启动PackageWatchdog.noteBoot
RescueParty.registerHealthObserver(mSystemContext);
PackageWatchdog.getInstance(mSystemContext).noteBoot();
//启动lights服务:管理控制LED指示灯事件,例如接收新消息、电话来电、设备充电等LED的闪烁频率亮度颜色
mSystemServiceManager.startService(LightsService.class);
//启动手表上面的两个跟显示相关的服务
if (SystemProperties.getBoolean("config.enable_display_offload", false)) mSystemServiceManager.startService(WEAR_DISPLAYOFFLOAD_SERVICE_CLASS);
if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false))  mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
//启动display服务:即DMS服务,管理设备显示相关逻辑
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
//设置SystemService当前阶段:PHASE_WAIT_FOR_DEFAULT_DISPLAY,此状态是系统启动阶段最早的,字面理解等待DMS服务器启动
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

启动DMS->启动PKMS:

//启动domain_verification服务:这个服务的功能通常涉及验证特定的域名或域,在后续PKMS启动的时候会使用到
DomainVerificationService domainVerificationService = new DomainVerificationService( mSystemContext, SystemConfig.getInstance(), platformCompat);
mSystemServiceManager.startService(domainVerificationService);
//启动PKMS:调用PKMS的主函数
try {
    Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
    mPackageManagerService = PackageManagerService.main(mSystemContext, installer, domainVerificationService, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF);
    } finally {
        Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
}
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
//注册DexUseManagerLocal:PKMS需要使用它,负责负责管理应用程序中的Dex文件,包括加载、卸载、优化等操作
LocalManagerRegistry.addManager(  DexUseManagerLocal.class,  DexUseManagerLocal.createInstance(mSystemContext));
//启动otadexopt服务:PKMS需要使用它,在OTA升级的时候需要通过它对包进行优化
boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt", false);
if (!disableOtaDexopt) {
    Watchdog.getInstance().pauseWatchingCurrentThread("moveab");
    OtaDexoptService.main(mSystemContext, mPackageManagerService);
    Watchdog.getInstance().resumeWatchingCurrentThread("moveab");
}
//启动user服务:管理多用户的服务,例如用户切换,包括用户涉及到的信息和权限
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);

初始化相关操作:

// Initialize attribute cache used to cache resources from packages.
AttributeCache.init(mSystemContext);
//通过 setSystemProcess方法为系统进程设置一个Application实例确保系统进程中的应用程序环境得到正确初始化
mActivityManagerService.setSystemProcess();
//为前文的domain_verification服务进行注册接受者
platformCompat.registerPackageReceiver(mSystemContext);
//初始化看门狗:此操作只能在ams所有工作准备完毕之后
watchdog.init(mSystemContext, mActivityManagerService);
//设置DMS服务的调度策略
mDisplayManagerService.setupSchedulerPolicies();
//启动overlay服务:管理应用程序的覆盖层,例如不同用户的主题、图标、颜色等
mSystemServiceManager.startService(new OverlayManagerService(mSystemContext));
//启动resources服务:管理应用程序的资源,如布局文件、字符串、图形等
ResourcesManagerService resourcesService = new ResourcesManagerService(mSystemContext);
resourcesService.setActivityManagerService(mActivityManagerService);
mSystemServiceManager.startService(resourcesService);
//启动sensor_privacy服务:负责管理和控制设备上的传感器相关服务
mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext));
mSystemServiceManager.startService(SensorService.class);

2)startCoreServices阶段

//启动system_config服务:负责管理系统的各种配置信息,如权限配置、功能开关、默认设置等
mSystemServiceManager.startService(SystemConfigService.class);
//启动battery和batteryproperties服务:能够实时监控电池的状态、电量变化等信息,可能需要 LightService(灯光服务)等其他服务的支持
mSystemServiceManager.startService(BatteryService.class);
//启动usagestats服务:通过监控应用程序的使用情况和统计数据,为系统和应用程序提供有关应用程序活动的详细信息
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(LocalServices.getService(UsageStatsManagerInternal.class));
//启动webviewupdate服务:负责追踪可更新的WebView是否准备就绪,并监控WebView的更新安装情况
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
//本地服务,跟踪设备的各种状态,如网络连接状态、电量情况、传感器数据等, 该服务会将设备状态信息进行缓存,以便系统和应用程序可以更快速地访问设备状态数据,而无需每次都重新获取
mSystemServiceManager.startService(CachedDeviceStateService.class);
//启动binder_calls_stats服务:该服务用于跟踪在Binder调用中消耗的CPU时间,有助于系统开发人员分析和优化系统中的Binder通信性能
mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);
//启动looper_stats服务:该服务可以收集关于Handler处理消息时间的统计数据,有助于开发人员分析和优化系统中处理消息的效率和性能
mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);
//启动rollback服务:负责管理应用程序包的回滚操作,即在应用程序升级失败时将其还原到先前的版本
mSystemServiceManager.startService(ROLLBACK_MANAGER_SERVICE_CLASS);
//本地服务:可以监视并处理由应用程序或进程崩溃导致的原生Tombstones,帮助识别问题并进行故障排除
mSystemServiceManager.startService(NativeTombstoneManagerService.class);
//启动bugreport服务:负责捕获和处理系统中发生的bug报告,以帮助开发人员诊断和解决应用程序或系统的问题
mSystemServiceManager.startService(BugreportManagerService.class);
//启动gpu服务:负责管理GPU驱动和图形处理相关的服务
mSystemServiceManager.startService(GpuService.class);
//启动remote_provisioning服务:该服务负责处理系统进程对远程配置密钥和数据的请求,以支持设备在远程配置方面的操作
mSystemServiceManager.startService(RemoteProvisioningService.class);
//启动cpu_monitor服务:用于监控CPU的运行情况,以便跟踪和优化系统在不同CPU负载下的性能表现
if (Build.IS_DEBUGGABLE || Build.IS_ENG) mSystemServiceManager.startService(CpuMonitorService.class);

3)startOtherServices阶段

启动安全相关服务->启动系统调度策略服务:

//启动sec_key_att_app_id_provider服务:为应用程序提供密钥验证服务,以确保应用程序的安全性和完整性
ServiceManager.addService("sec_key_att_app_id_provider",  new KeyAttestationApplicationIdProviderService(context));
//此服务可以有效地管理设备上的密钥链KeyChain,包括存储和访问各种加密密钥、证书等敏感信息。这对于安全通信、数字签名、数据加密等方面都是至关重要的
mSystemServiceManager.startService(KeyChainSystemService.class);
//此服务可以实现对软件包或二进制文件的透明性验证,确保它们未被篡改且来源可信
mSystemServiceManager.startService(BinaryTransparencyService.class);
//启动scheduling_policy服务:负责处理系统调度策略的服务,以优化系统资源的分配和任务执行
ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
//启动telephony相关服务
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE) || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELECOM) || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY))   mSystemServiceManager.startService(TelecomLoaderService.class);
telephonyRegistry = new TelephonyRegistry(context, new TelephonyRegistry.ConfigurationProvider());
ServiceManager.addService("telephony.registry", telephonyRegistry);
//启动EntropyMixer组件:用于生成随机数和加密所需的随机性数据
mEntropyMixer = new EntropyMixer(context);
//启动account服务:负责处理设备上的账户管理相关操作,包括添加、删除、验证账户等功能
mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
//启动content服务:内容提供者服务,此服务提供应用程序对设备上存储的内容进行访问和管理的功能。这包括文件系统操作、数据库访问、共享数据等内容服务,有助于应用程序之间共享数据、处理多媒体内容和实现数据持久化等功能
mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);
//启动device_config_updatable服务:此服务可以处理与设备配置相关的操作,确保设备的配置信息得到正确地管理和更新
mActivityManagerService.getContentProviderHelper().installSystemProviders();
mSystemServiceManager.startService(UPDATABLE_DEVICE_CONFIG_SERVICE_CLASS);
SQLiteCompatibilityWalFlags.reset();
//启动dropbox服务:负责记录系统中发生的错误、异常和其他日志信息,以便开发人员进行故障排查和问题分析
mSystemServiceManager.startService(DropBoxManagerService.class);
//启动role服务:负责管理和分配系统中的角色,以及授予默认权限和定义各种角色
LocalManagerRegistry.addManager(RoleServicePlatformHelper.class, new RoleServicePlatformHelperImpl(mSystemContext));
mSystemServiceManager.startService(ROLE_SERVICE_CLASS);
//启动vibrator_manager服务:对设备的振动功能进行管理,包括控制振动强度、模式以及在特定事件触发时触发振动等功能
mSystemServiceManager.startService(VibratorManagerService.Lifecycle.class);
//启动dynamic_system服务:动态分区服务
dynamicSystem = new DynamicSystemService(context);
ServiceManager.addService("dynamic_system", dynamicSystem);
//启动consumer_ir服务:管理红外线功能,通过红外等控制周围的设备(例如电视等),与硬件强相关            
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CONSUMER_IR)) {
consumerIr = new ConsumerIrService(context);
ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr); }
//启动tare服务:主要在InternalResourceService中负责处理应用程序的ARC计数(应用程序引用计数),通常用于管理内存、文件句柄、网络连接等资源,确保资源被正确释放以避免浪费或系统不稳定
mSystemServiceManager.startService(RESOURCE_ECONOMY_SERVICE_CLASS);

启动系统调度策略服务->开始DMS相关的所有服务

//启动alarm服务:责管理和触发各种定时任务、闹钟以及重复性任务。提供闹铃和定时器等功能
if(!sMtkSystemServerIns.startMtkAlarmManagerService()) mSystemServiceManager.startService(ALARM_MANAGER_SERVICE_CLASS);
//启动input服务:处理事件分发,以前在WindowManagerService中,现在独立了出来,并且初始化的时候传递了 DisplayThread.get().getLooper()进去作为消息处理器,还启动了了Watchdog.getInstance().addMonitor(this)进行监视
inputManager = new InputManagerService(context);
//启动device_state服务:管理带有用户可配置硬件的设备状态的系统服务,根据设备的物理状态,dms wms和systemUI可能会有不同的行为。这对于可变状态设备(如可折叠或可滚动设备)非常有用
mSystemServiceManager.startService(DeviceStateManagerService.class);
//启动media.camera.proxy服务:camera相关的服务,同时会与media.camera服务进行交互
if (!disableCameraService)  mSystemServiceManager.startService(CameraServiceProxy.class);
//设置PHASE_WAIT_FOR_SENSOR_SERVICE状态,WMS开始执行main函数,注册window服务,注册input服务
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_SENSOR_SERVICE);
wm = WindowManagerService.main(context, inputManager, !mFirstBoot, new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager, /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
mActivityManagerService.setWindowManager(wm);
wm.onInitReady();
//启动相关sensor服务,这些服务必现在PHASE_WAIT_FOR_SENSOR_SERVICE之后
SystemServerInitThreadPool.submit(() -> { startISensorManagerService(); }, START_SENSOR_MANAGER_SERVICE);
SystemServerInitThreadPool.submit(() -> { startHidlServices(); }, START_HIDL_SERVICES);
//启动vrmanager服务:如果是手表启动VR服务,VR也跟DMS/WMS相关
if (!isWatch && enableVrService) mSystemServiceManager.startService(VrManagerService.class);
//开始input服务:主要调用mNative.start(),然后添加到了看门狗进行监听
inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback());
inputManager.start();
//通知DMS窗口管理服务,系统事件输入服务已经准备好
mDisplayManagerService.windowManagerAndInputReady();

开始DMS相关的所有服务->启动相对独立的服务

//启动bluetooth_manager服务:通过jar来实例化BluetoothService
mSystemServiceManager.startServiceFromJar(BLUETOOTH_SERVICE_CLASS, BLUETOOTH_APEX_SERVICE_JAR_PATH);
//启动connmetrics和netd_listener服务:分别对应网络连接相关的服务IpConnectivityMetrics;接收netd进程的底层事件的服务NetdEventListenerService
mSystemServiceManager.startService(IP_CONNECTIVITY_METRICS_CLASS);
//启动network_watchlist服务:管理系统的网络监控列表
mSystemServiceManager.startService(NetworkWatchlistService.Lifecycle.class);
//启动pinner服务:主要功能是将关键进程的重要文件固定在内存中,避免因为数据被移动到磁盘上而导致性能下降或延迟。这种服务对于优化系统性能和确保关键数据持续在内存中非常重要
mSystemServiceManager.startService(PinnerService.class);
//debug模式才能启用:System-server-local proxy into the native service.
if (Build.IS_DEBUGGABLE && ProfcollectForwardingService.enabled()) mSystemServiceManager.startService(ProfcollectForwardingService.class);
//他不是一个服务,而只是拥有一个用于接收包安装和更新通知的广播接收器,来负责处理应用程序的签名配置或相关的安全性功能
SignedConfigService.registerUpdateReceiver(mSystemContext);
//启动app_integrity服务:主要目的是确保应用程序的完整性,并执行相关的验证规则以增强系统的安全性和稳定性
mSystemServiceManager.startService(AppIntegrityManagerService.class);
//启动logcat服务: Service responsible for managing the access to Logcat.
mSystemServiceManager.startService(LogcatManagerService.class);

启动输入法服务->启动存储相关服务

//安全模式开启飞行模式
final boolean safeMode = wm.detectSafeMode();
if (safeMode) Settings.Global.putInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 1);
else if (context.getResources().getBoolean(R.bool.config_autoResetAirplaneMode)) Settings.Global.putInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0);
//启动input_method服务:键盘输入法服务,打开和关闭输入法。注意和前面的事件输入服务区别
String immsClassName = context.getResources().getString(R.string.config_deviceSpecificInputMethodManagerService);
if (immsClassName.isEmpty()) mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);
else  mSystemServiceManager.startService(immsClassName);
//启动accessibility服务:截获所有的用户输入,集中处理和分发设备上产生的无障碍事件,保证无障碍服务相关功能的稳定
mSystemServiceManager.startService(ACCESSIBILITY_MANAGER_SERVICE_CLASS);
//making display ready
wm.displayReady();
//启动mount服务:StorageManagerService服务,负责管理存储设备(如内部存储、外部存储、USB 存储等)的服务。它处理挂载(mounting)、卸载(unmounting)、格式化、检测存储设备状态等操作。 NotificationManagerService在某些情况下需要依赖他,例如插入USB的时候需要弹框
//启动storagestats服务:访问详细的存储统计信息。这提供了应用程序、用户和外部/共享存储如何利用磁盘空间的摘要
if (!"0".equals(SystemProperties.get("system_init.startmountservice"))) {
    mSystemServiceManager.startService(STORAGE_MANAGER_SERVICE_CLASS);
    storageManager = IStorageManager.Stub.asInterface(ServiceManager.getService("mount"));
    mSystemServiceManager.startService(STORAGE_STATS_SERVICE_CLASS);
}
//启动uimode服务:UiModeManagerService服务,负责管理深色主题/夜间模式,包括车载模式,同时虽然不直接管理省电模式,但是和省电模式UI相关功能有一些耦合
mSystemServiceManager.startService(UiModeManagerService.class);
//启动locale服务:为应用程序提供一种机制来存储和管理与本地化设置相关的信息,允许应用程序将其特定的UI本地化信息存储在系统中,以便在需要时访问并应用到应用程序的用户界面中
mSystemServiceManager.startService(LocaleManagerService.class);
//启动grammatical_inflection服务:该服务可能被用于文本处理工具、语言学应用程序或其他需要处理语言变形的应用中
mSystemServiceManager.startService(GrammaticalInflectionService.class);
//启动app_hibernation服务:AppHibernationService 服务,主要用于处理应用程序的休眠状态管理,以支持系统在需要时对不活跃应用程序进行优化处理,从而提高存储利用率并改善系统效率
mSystemServiceManager.startService(APP_HIBERNATION_SERVICE_CLASS);

启动锁屏服务->启动状态栏管理服务

//初始化ArtManagerLocal相关设置,updatePackagesIfNeeded检查并更新应用程序包,performFstrimIfNeeded执行TRIM操作,确保系统中的应用程序处于最新状态
DexOptHelper.initializeArtManagerLocal(context, mPackageManagerService);
Watchdog.getInstance().pauseWatchingCurrentThread("dexopt");
mPackageManagerService.updatePackagesIfNeeded();
Watchdog.getInstance().resumeWatchingCurrentThread("dexopt");
mPackageManagerService.performFstrimIfNeeded();
//启动lock_settings服务:LockSettingsService服务,管理设备的锁屏设置,包括密码、图案、PIN 码等锁定方式的配置和验证
mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);
lockSettings = ILockSettings.Stub.asInterface(ServiceManager.getService("lock_settings"));
//启动persistent_data_block服务:系统可以管理设备上存储的重要持久化数据块,并确保这些数据块得到正确地处理和维护,以支持设备的正常运行和数据的安全性
final boolean hasPdb = !SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("");
if(hasPdb) mSystemServiceManager.startService(PersistentDataBlockService.class);
//启动testharness服务:用于管理测试工具模式(Test Harness Mode)服务,管理自动化测试服务,用于在设备上设置自动测试框架
mSystemServiceManager.startService(TestHarnessModeService.class);
//启动oem_lock服务:负责控制和管理设备的 OEM 锁定设置
if (hasPdb || OemLockService.isHalPresent()) mSystemServiceManager.startService(OemLockService.class);
//启动deviceidle服务:监控设备的使用情况,以确定设备是否处于空闲状态,控制设备的休眠模式和管理应用程序的激活和限制
mSystemServiceManager.startService(DEVICE_IDLE_CONTROLLER_CLASS);
//启动device_policy服务:用于管理设备安全策略和控制权限的重要服务。它允许管理员远程管理设备并强制执行各种策略以确保设备的安全性和合规性
dpms = mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class);
//启动statusbar服务:负责状态栏的显示、隐藏、通知管理以及其他与状态栏相关的功能。而SystemUI则负责更新、渲染和显示状态栏内容,并处理用户与状态栏的交互
statusBar = new StatusBarManagerService(context);
if (!isWatch) statusBar.publishGlobalActionsProvider();
ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar, false, DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);

启动一些比较使用功能的服务

//启动music_recognition服务:根据设备配置判断是否应启动音乐识别管理器服务
if (deviceHasConfigString(context, R.string.config_defaultMusicRecognitionService)) mSystemServiceManager.startService(MUSIC_RECOGNITION_MANAGER_SERVICE_CLASS);
//启动content_capture服务:ContentCaptureManagerService服务,负责处理和管理与内容捕获相关的功能,内容捕获服务通常用于提供自动填充、建议、或者其他智能功能,以改善用户体验并增强应用程序的功能性
startContentCaptureService(context, t);
//启动attention服务:AttentionManagerService服务,注意力管理器服务通常与用户界面、通知系统或其他应用程序交互,以根据用户的注意力状态做出相应的反应或调整
startAttentionService(context, t);
//启动resolver服务:RotationResolverManagerService服务,务负责处理设备屏幕旋转相关的逻辑,包括监测设备方向变化、调整屏幕显示方向、以及触发相应的屏幕旋转事件等
startRotationResolverService(context, t);
//SystemCaptionsManagerService:根据设备配置情况判断是否应启动系统字幕管理器服务
startSystemCaptionsManagerService(context, t);
//启动texttospeech服务:TextToSpeechManagerService服务,负责提供文本转语音的功能,允许应用程序将文本数据转换为语音输出。通过该服务,用户可以享受到文字内容的语音朗读功能,增强了用户体验和可访问性
startTextToSpeechManagerService(context, t);
//启动ambient_context服务:AmbientContextManagerService服务,负责收集和分析设备周围环境的数据,以提供更智能和个性化的用户体验。通过监测环境信息,该服务可以自动调整设备设置、应用程序行为或提供定制化的功能,从而增强用户体验并提供更多智能化的服务
startAmbientContextService(t);
//启动wearable_sensing服务:WearableSensingManagerService服务,负责管理和处理与可穿戴设备相关的传感器数据,如运动传感器、心率传感器等。通过该服务,系统可以监测和分析用户在可穿戴设备上的活动、健康状况等数据,以提供个性化的健康、运动或其他方面的服务和建议
startWearableSensingService(t);
//启动speech_recognition服务:SpeechRecognitionManagerService服务,系统语音识别管理器服务,负责处理设备上的语音输入,并将其转换为文本或对应的命令
mSystemServiceManager.startService(SPEECH_RECOGNITION_MANAGER_SERVICE_CLASS);
//启动app_prediction服务:AppPredictionManagerService服务,负责分析用户的操作习惯、使用模式和其他相关数据,以预测用户可能要使用的应用程序,提供更智能、个性化的应用程序推荐
if (deviceHasConfigString(context, R.string.config_defaultAppPredictionService)) mSystemServiceManager.startService(APP_PREDICTION_MANAGER_SERVICE_CLASS);
//启动content_suggestions服务:ContentSuggestionsManagerService服务,负责根据用户的偏好、历史数据和其他相关信息,提供个性化的内容推荐,包括应用程序、新闻、视频、音乐等。通过该服务,系统可以为用户提供更加符合其兴趣和需求的内容,并改善用户体验
if (deviceHasConfigString(context, R.string.config_defaultContentSuggestionsService))  mSystemServiceManager.startService(CONTENT_SUGGESTIONS_SERVICE_CLASS);
//启动search_ui服务:SearchUiManagerService服务,负责管理设备上的搜索界面,包括搜索功能的展示、用户界面交互等,此服务可以为lanucher应用提供搜索相关的功能支持,例如在搜索界面中展示搜索结果、协助搜索操作等
mSystemServiceManager.startService(SEARCH_UI_MANAGER_SERVICE_CLASS);
//启动smartspace服务:SmartspaceManagerService服务,智能空间管理器服务通常负责提供设备主屏幕上的智能助手功能,例如展示天气信息、日历事件、提醒事项等内容。通过智能空间管理器服务,用户可以快速查看重要信息,并获取有用的实时数据
mSystemServiceManager.startService(SMARTSPACE_MANAGER_SERVICE_CLASS);

启动网络相关服务

//网络堆栈器初始化,所有网络相关服务之前都需要初始化它
ConnectivityModuleConnector.getInstance().init(context); //会打印日志"Network stack init"
NetworkStackClient.getInstance().init();                 //会打印日志"Network stack init"
//启动network_management服务:主要是用于创建、配置和启动网络管理服务,并确保该服务可以有效地运行以满足系统对网络管理的需求
networkManagement = NetworkManagementService.create(context);
ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
//启动font服务:负责管理设备上的字体资源,包括加载、缓存、渲染字体以及提供字体相关功能,以确保应用程序和系统能够正确显示文本内容并提供字体选择和调整的功能
mSystemServiceManager.startService(new FontManagerService.Lifecycle(context, safeMode));
//启动textservices服务:负责管理设备上的文本输入服务、文本处理服务、拼写检查等相关功能,为用户提供良好的文本输入和编辑体验
mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);
//启动textclassification服务:用于启动文本分类管理器服务,以提供文本内容的智能分类和分析功能,例如识别文本中的实体、情感分析、语言识别等,帮助用户更好地理解和处理文本信息
if (!disableSystemTextClassifier) mSystemServiceManager.startService(TextClassificationManagerService.Lifecycle.class);
//启动network_score服务:服务通常负责根据网络质量、连接稳定性等因素为网络提供评分,并帮助系统做出优化网络连接的决策
mSystemServiceManager.startService(NetworkScoreService.Lifecycle.class);
//启动netstats服务:启动网络统计服务,并确保在启动NetworkPolicyManager之前先启动 NetworkStatsService,同时进行相应的跟踪操作来监控执行过程
mSystemServiceManager.startServiceFromJar(NETWORK_STATS_SERVICE_INITIALIZER_CLASS,CONNECTIVITY_SERVICE_APEX_PATH);
//启动netpolicy服务:可以监控和限制应用程序的数据使用,有助于优化数据使用,节省用户的流量消耗,并在需要时提供通知提示,还可以配置网络策略,以确定是否允许应用程序在漫游状态下访问数据网络,以避免高额的漫游费用
networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService,networkManagement);
ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
//启动wifi和wifiscanner服务:管理WIFI和WIFI扫描服务
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI)) {
    mSystemServiceManager.startServiceFromJar(WIFI_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
    mSystemServiceManager.startServiceFromJar(WIFI_SCANNING_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
}
//启动wifirtt服务:
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_RTT)) mSystemServiceManager.startServiceFromJar(WIFI_RTT_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
//启动wifiaware服务:
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_AWARE)) mSystemServiceManager.startServiceFromJar(WIFI_AWARE_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
//启动wifip2p服务:
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT)) mSystemServiceManager.startServiceFromJar(WIFI_P2P_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
//根据设备是否支持 LoWPAN 功能来决定是否启动 LoWPAN 服务。 LoWPAN 是一种低功耗无线个人区域网络技术,用于连接低功耗设备,例如传感器、智能家居设备等,以实现设备间的通信互连。
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOWPAN)) mSystemServiceManager.startService(LOWPAN_SERVICE_CLASS);
//启动pac_proxy服务:PAC代理服务通常用于管理和配置网络代理设置,以便应用程序能够正确地路由网络流量
pacProxyService = new PacProxyService(context);
ServiceManager.addService(Context.PAC_PROXY_SERVICE, pacProxyService);
//Connectivity service initializer for core networking
//启动ethernet服务/connectivity服务/ipsec服务/connectivity_native服务/servicediscovery服务/nearby服务
mSystemServiceManager.startServiceFromJar(CONNECTIVITY_SERVICE_INITIALIZER_CLASS, CONNECTIVITY_SERVICE_APEX_PATH);
networkPolicy.bindConnectivityManager();
//启动vpn_management服务:管理VPN相关功能
vpnManager = VpnManagerService.create(context);
ServiceManager.addService(Context.VPN_MANAGEMENT_SERVICE, vpnManager);
//启动vcn_management服务: VCN 管理服务,可以实现对虚拟运营商网络的配置、管理和控制,从而提供更灵活的网络连接选项和功能
vcnManagement = VcnManagementService.create(context);
ServiceManager.addService(Context.VCN_MANAGEMENT_SERVICE, vcnManagement);

启动通知和时间定位相关的服务

//启动system_update服务:允许查询发送系统更新的信息,通过维护system-update-info.xml文件来实现
ServiceManager.addService(Context.SYSTEM_UPDATE_SERVICE, new SystemUpdateManagerService(context));
//启动updatelock服务:OTA/update purposes can so advise the OS. 服务启动后发送android.os.UpdateLock.UPDATE_LOCK_CHANGED广播
ServiceManager.addService(Context.UPDATE_LOCK_SERVICE, new UpdateLockService(context));
//启动notification服务:通知服务,管理通知的发布和是否显示
mSystemServiceManager.startService(NotificationManagerService.class);
SystemNotificationChannels.removeDeprecated(context);
SystemNotificationChannels.createAll(context);
notification = INotificationManager.Stub.asInterface( ServiceManager.getService(Context.NOTIFICATION_SERVICE));
//启动devicestoragemonitor服务:存储空间的监控,当存储空间低于阈值时发送广播
mSystemServiceManager.startService(DeviceStorageMonitorService.class);
//启动time_detector服务:TimeDetectorService服务, 处理时间检测周围的逻辑。
mSystemServiceManager.startService(TIME_DETECTOR_SERVICE_CLASS);
//启动location服务:位置服务,实现了通过GNSS、GPS、定位等功能	
mSystemServiceManager.startService(LocationManagerService.Lifecycle.class);
//启动country_detector服务:通过检查设备的时区、语言设置、SIM 卡信息等来确定用户所在的国家或地区。开发人员可以利用这个服务来适应不同国家或地区的用户需求,以提供更个性化和本地化的体验
countryDetector = new CountryDetectorService(context);
ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
//启动time_zone_detector服务:TimeZoneDetectorService服务,主要用于检测用户所在的时区信息
mSystemServiceManager.startService(TIME_ZONE_DETECTOR_SERVICE_CLASS);
//启动AltitudeService服务:处理海拔高度相关功能的服务,可能涉及到获取设备所在位置的海拔高度信息或其他与海拔有关的操作
mSystemServiceManager.startService(AltitudeService.Lifecycle.class);
//启动location_time_zone_manager服务:LocationTimeZoneManagerService服务,负责处理位置和时区信息的管理服务
mSystemServiceManager.startService(LOCATION_TIME_ZONE_MANAGER_SERVICE_CLASS);
//启动gnss_time_update_service服务:GnssTimeUpdateService服务,通过GNSS卫星来更新时间
if (context.getResources().getBoolean(R.bool.config_enableGnssTimeUpdateService)) mSystemServiceManager.startService(GNSS_TIME_UPDATE_SERVICE_CLASS);

启动壁纸和audio相关的服务

//启动search服务:SearchManagerService服务,是搜索管理服务,负责处理搜索用户界面,并维护可搜索活动的注册表。与桌面应用的搜索栏有关系
if (!isWatch) mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS);
//启动wallpaper服务:WallpaperManagerService服务,壁纸管理服务
if (context.getResources().getBoolean(R.bool.config_enableWallpaperService)) mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
//启动wallpaper_effects_generation服务:A service used to return wallpaper effect given a request. 从注释来看跟壁纸效果有关系,例如动态壁纸,交互式壁纸
mSystemServiceManager.startService(WALLPAPER_EFFECTS_GENERATION_MANAGER_SERVICE_CLASS);
//启动audio服务:AudioService服务,AudioFlinger的上层管理封装,主要是音量、音效、声道及铃声等的管理
boolean isArc = context.getPackageManager().hasSystemFeature("org.chromium.arc");
if (!isArc) { mSystemServiceManager.startService(AudioService.Lifecycle.class);
} else { // 
    String className = context.getResources().getString(R.string.config_deviceSpecificAudioService);
    mSystemServiceManager.startService(className + "$Lifecycle");
}
//启动soundtrigger_middleware服务:SoundTriggerMiddlewareService则可能处于底层系统层次,提供声音触发功能的中间件支持,并与硬件驱动等交互,为更高级别的声音触发功能提供基础支持(注意和SoundTriggerService区分)
mSystemServiceManager.startService(SoundTriggerMiddlewareService.Lifecycle.class);
//启动broadcastradio服务:可以实现设备上广播电台的调谐、收听、搜索等功能。这个服务负责管理与广播电台相关的逻辑,并提供给应用程序或其他组件访问广播收音机的能力
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BROADCAST_RADIO)) mSystemServiceManager.startService(BroadcastRadioService.class);
//启动DockObserver服务:?
if (!isTv) mSystemServiceManager.startService(DockObserver.class);
//启动com.android.clockwork.ThermalObserver服务:?
if (isWatch) mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS);
//WiredAccessoryManager 用于监视主板或对接站上连接的有线耳机,并通过 InputManagerService 的 notifyWiredAccessoryChanged 接口和 UEventObserver 子系统来进行监测
if (!isWatch) inputManager.setWiredAccessoryCallbacks(new WiredAccessoryManager(context, inputManager));
//启动midi服务:MidiService服务,涉及MIDI音乐相关功能,如MIDI文件播放、音乐合成等操作。MIDI是音乐乐器数字接口的缩写,定义了如何通过数字信号传输音乐数据,包括音符、音量、音色、节奏等信息,而不涉及声音本身
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) mSystemServiceManager.startService(MIDI_SERVICE_CLASS);

启动adb/usb/serial和其他服务

//启动adb服务:AdbService服务,用于adb调试
mSystemServiceManager.startService(ADB_SERVICE_CLASS);
//启动usb服务:UsbService服务,管理所有USB状态,主机模式委托给UsbHostManager管理,从机模式委托给UsbDeviceManager管理
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST) || mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_ACCESSORY) || isEmulator){
    mSystemServiceManager.startService(USB_SERVICE_CLASS);
}
//启动serial服务:串口服务,对串口的设备进行操作
if (!isWatch) ServiceManager.addService(Context.SERIAL_SERVICE, new SerialService(context));
//启动hardware_properties服务:可以给其他组件提供硬件信息,可以通过dumpsys hardware_properties获取这些信息
hardwarePropertiesService = new HardwarePropertiesManagerService(context);
ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE, hardwarePropertiesService);
//启动TwilightManager服务:此服务可以根据经度和纬度来计算黄昏状态,计算黄昏状态对于确定日出和日落时间以及天文事件的安排非常重要,也有助于制定户外活动、摄影计划等。
if (!isWatch) mSystemServiceManager.startService(TwilightService.class);
//启动color_display服务:负责管理设备屏幕的色彩显示设置,包括调整亮度、对比度、色温等选项,以提供用户个性化和舒适的屏幕显示体验
mSystemServiceManager.startService(ColorDisplayService.class);
//启动jobscheduler服务:JobSchedulerService服务,负责管理作业队列、调度作业的执行时间和条件,以及通知应用程序关于作业执行状态的信息。这个服务有助于提高应用程序的稳定性和用户体验,同时有效地管理后台任务的执行
mSystemServiceManager.startService(JOB_SCHEDULER_SERVICE_CLASS);
//启动soundtrigger服务:SoundTriggerService可能更专注于用户界面上的声音触发功能,如语音助手、语音控制等。注意和SoundTriggerMiddlewareService区分
mSystemServiceManager.startService(SoundTriggerService.class);
//启动trust服务:该服务是设备中的信任管理相关的服务,通常用于处理和管理设备上的安全认证和信任相关功能。管理和验证设备用户的身份认证信息,如密码、指纹、面部识别等
mSystemServiceManager.startService(TrustManagerService.class);
//启动backup服务:BackupManagerService服务,处理和管理应用程序数据的备份和恢复操作,以确保用户数据的安全性和可靠性
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS);
//启动appwidget服务:AppWidgetService负责管理和显示应用程序小部件的服务,提供了处理小部件更新和事件的功能,在Launcher中被调用和管理,Launcher 负责在设备主屏幕上管理小部件的布局和显示
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS) || context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {
mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS);}
//启动voiceinteraction服务:VoiceInteractionManagerService语音交互管理服务,语音识别和交互功能,使用户可以通过语音与设备进行交互和控制
mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS);
//启动GestureLauncherService服务:The service that listens for gestures detected in sensor firmware and starts the intent accordingly. For now, only camera launch gesture is supported, and in the future, more gestures can be  added
if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) mSystemServiceManager.startService(GestureLauncherService.class);
//启动SensorNotificationService服务:传感器通知服务可能是与设备中的传感器相关的服务,代码中监听了传音的状态变化
mSystemServiceManager.startService(SensorNotificationService.class);
//启动contexthub服务:上下文中心运行时环境 (CHRE) 为在低功耗处理器上运行应用程序提供了一个通用平台,具有简单、标准化、嵌入式友好的 API,参考https://source.android.google.cn/devices/contexthub?hl=vi
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_CONTEXT_HUB)) mSystemServiceManager.startService(ContextHubSystemService.class);
//启动diskstats服务:主要用来各个应用程序的磁盘使用统计信息,使用adb shell dumpsys diskstats可以输出用程序的UID(用户ID)、读取字节数、写入字节数、读取操作数和写入操作数等信息
ServiceManager.addService("diskstats", new DiskStatsService(context));
//启动runtime服务:主要用来统计当前时间相关的数据信息,使用adb shell dumpsys runtime可以输出这些信息。注意跟运行时好像没有太大关系
ServiceManager.addService("runtime", new RuntimeService(context));
//启动network_time_update_service服务:通过[ntp://time.android.com, ntp://pool.ntp.org]查询网络时间,如果查询失败会有重连机制
if (!isWatch && !disableNetworkTime) {
    networkTimeUpdater = new NetworkTimeUpdateService(context);
    ServiceManager.addService("network_time_update_service", networkTimeUpdater); }
//CertBlacklister提供了一种简单的机制来更新SSL证书公钥和序列号的平台黑名单,android维护在/data/misc/keychain目录
CertBlacklister blacklister = new CertBlacklister(context); 
//启动emergency_affordance服务:A service that listens to connectivity and SIM card changes and determines if the emergency affordance should be enabled.
if (EmergencyAffordanceManager.ENABLED) mSystemServiceManager.startService(EmergencyAffordanceService.class);

启动TV和多媒体相关的服务

//启动blob_store服务:BlobStoreManagerService服务,Service responsible for maintaining and facilitating access to data blobs published by apps
mSystemServiceManager.startService(BLOB_STORE_MANAGER_SERVICE_CLASS);
//启动dreams服务:DreamManagerService主要是提供屏保服务,应用可以通过继承DreamService实现自己想要的屏保效果,可以参考https://www.jianshu.com/p/75d8581ec4fe/
mSystemServiceManager.startService(DreamManagerService.class);
//启动graphicsstats服务:图形统计服务通常用于收集和记录与图形渲染相关的性能数据和统计信息,收集有关GPU、渲染器等图形相关组件的性能指标,记录应用程序的帧率(FPS)、绘制时间、内存使用情况等性能数据
ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE, new GraphicsStatsService(context));
//启动coverage服务:CoverageService可能与代码覆盖率检测相关,实现用于监视代码执行的机制,收集有关代码路径和执行次数的信息,用于衡量源代码中被测试用例覆盖到的代码比例
if (CoverageService.ENABLED) ServiceManager.addService(CoverageService.COVERAGE_SERVICE, new CoverageService());
//启动print服务:PrintManagerService服务主要用于处理打印相关的功能。让应用程序可以与打印服务进行通信,从而实现打印文档、图片等内容
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS);
//启动attestation_verification服务:处理关于认证和验证相关的功能,负责管理设备或组件的认证过程,确保设备的合法性和可信度
mSystemServiceManager.startService(AttestationVerificationManagerService.class);
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_COMPANION_DEVICE_SETUP)) {
    //启动companiondevice服务:CompanionDeviceManagerService服务用于处理配件设备的管理和设置,包括配对、连接和配置外部设备,如智能手表、健康追踪器等
    mSystemServiceManager.startService(COMPANION_DEVICE_MANAGER_SERVICE_CLASS);
    //启动virtualdevice服务:VirtualDeviceManagerService用于管理虚拟设备或模拟器,可能包括创建、启动和管理虚拟设备实例
    mSystemServiceManager.startService(VIRTUAL_DEVICE_MANAGER_SERVICE_CLASS);
}
//启动restrictions服务:系统可以实现对设备和应用程序使用的某些功能、资源或数据进行限制和控制,从而确保系统在合规性和安全性方面的要求得到满足
mSystemServiceManager.startService(RestrictionsManagerService.class);
//启动media_session服务:MediaSessionService负责注册、跟踪和处理应用程序之间的多媒体控制命,
mSystemServiceManager.startService(MEDIA_SESSION_SERVICE_CLASS);
//启动hdmi_control服务:提供HDMI控制消息、HDMI- cec和MHL控制命令的发送和处理服务,另外还负责建立和管理eARC连接
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) mSystemServiceManager.startService(HdmiControlService.class);
//启动tv_interactive_app服务:提供了一种专门处理电视上交互式应用程序的服务,负责管理安装、卸载和运行在电视上的交互式应用程序
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV) mSystemServiceManager.startService(TvInteractiveAppManagerService.class);
//启动tv_input服务:关注管理电视输入设备和频道,与输入源和多媒体内容相关
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV) mSystemServiceManager.startService(TvInputManagerService.class);
//启动tv_tuner_resource_mgr服务:TunerResourceManagerService服务通常用于管理电视信号调谐器tuner资源,协助进行节目频道的切换和调谐器设置,以便用户可以浏览不同的电视频道
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_TUNER)) mSystemServiceManager.startService(TunerResourceManagerService.class);
//启动media_resource_monitor服务:MediaResourceMonitorService服务用于监控系统中各种媒体资源的使用情况,包括音频、视频、图像等
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) mSystemServiceManager.startService(MEDIA_RESOURCE_MONITOR_SERVICE_CLASS);
//TvInputManagerService关注电视信号和输入设备的管理,TvInteractiveAppManagerService关注电视应用程序和用户界面的管理,TunerResourceManagerService主要关注电视信号调谐器资源的管理,MediaResourceMonitorService则主要关注系统中各种媒体资源的实时监控和优化
//TvRemoteService服务负责接收来自电视遥控器的配对和各种点击滑动事件,且还加入了 Watchdog.getInstance().addMonitor(this)监视
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) mSystemServiceManager.startService(TvRemoteService.class);
//启动media_router服务:负责检测、注册和管理设备上可用的多媒体输出和输入路由,实现多屏互动、外部设备连接和优化用户体验的目的
mediaRouter = new MediaRouterService(context);
ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);

启动人脸、虹膜、指纹检查匹配特征码提取服务

//启动face服务:通常用于处理人脸识别相关的功能,包括人脸检测,人脸匹配,人脸特征提取,从而实现对用户身份的验证,进而解锁设备或授权访问
final boolean hasFeatureFace = mPackageManager.hasSystemFeature(PackageManager.FEATURE_FACE);
if (hasFeatureFace) final FaceService faceService = mSystemServiceManager.startService(FaceService.class);
//启动iris服务:通常用于处理虹膜识别相关的功能,包括虹膜检测,虹膜匹配,虹膜特征提取,从而实现对用户身份的验证,进而解锁设备或授权访问
final boolean hasFeatureIris = mPackageManager.hasSystemFeature(PackageManager.FEATURE_IRIS);
if (hasFeatureIris)  mSystemServiceManager.startService(IrisService.class);
//启动fingerprint服务:通常用于处理指纹识别相关的功能,包括指纹检查,指纹匹配,指纹特征提取,指纹支付,从而实现对用户身份的验证,进而解锁设备或授权访问
final boolean hasFeatureFingerprint = mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);
if (hasFeatureFingerprint) final FingerprintService fingerprintService = mSystemServiceManager.startService(FingerprintService.class);
//启动biometric服务:通常用于管理和提供生物识别相关功能,负责统一管理不同类型的生物识别技术,如人脸识别、虹膜识别、指纹识别等,从而实现多模态生物识别和更全面的身份验证功能
mSystemServiceManager.startService(BiometricService.class);
//启动auth服务:AuthService主要关注用户的身份认证和授权管理,与用户身份验证和访问控制有关。BiometricService主要涉及生物识别技术的管理和应用。BiometricService可能作为AuthService的一部分,为身份认证提供更多选择,例如通过生物特征进行快速身份验证或强化认证措施
mSystemServiceManager.startService(AuthService.class);
//启动jobscheduler服务:是一个执行与动态代码加载相关的后台任务的服务,负责在特定条件下进行日志记录和监视动态代码加载的情况
if (!isWatch) DynamicCodeLoggingService.schedule(context);
if (!isWatch) PruneInstantAppsJobService.schedule(context);
//启动shortcut服务:用于管理应用程序快捷方式的服务。快捷方式允许用户快速访问应用程序的特定功能或操作,而不必打开整个应用程序
mSystemServiceManager.startService(ShortcutService.Lifecycle.class);
//启动launcherapps服务:LauncherAppsService主要负责与设备启动器应用程序进行交互,管理应用程序快捷方式的显示和操作;ShortcutService则专注于应用程序内部的快捷方式管理,提供创建和管理应用程序快捷方式的功能。LauncherAppsService可能会利用ShortcutService提供的快捷方式管理功能来对启动器界面上的应用程序快捷方式进行管理
mSystemServiceManager.startService(LauncherAppsService.class);
//启动crossprofileapps服务:在android上多个用户可以拥有各自的配置文件或用户账户,CrossProfileAppsService 服务主要针对设备上不同用户配置文件之间的应用程序交互,提供跨用户配置文件应用程序的管理和访问功能
mSystemServiceManager.startService(CrossProfileAppsService.class);
//启动people服务:?
mSystemServiceManager.startService(PeopleService.class);
//启动media_metrics服务:用于收集和管理与媒体应用程序相关的统计数据、指标和信息
mSystemServiceManager.startService(MediaMetricsManagerService.class);
//启动background_install_control服务:应该是从data/bic/states记录的信息进行后台安装?
mSystemServiceManager.startService(BackgroundInstallControlService.class);
//启动media_projection服务:用于屏幕捕获和录制功能的管理。用户可以选择允许或拒绝应用程序对屏幕内容的访问,从而保护用户隐私和安全。这个服务在需要使用屏幕录制或捕获功能的应用程序中发挥着重要作用,如屏幕分享应用、教育应用、游戏录制应用等
mSystemServiceManager.startService(MediaProjectionManagerService.class);

启动状态监控统计相关的服务

//手表特有的一些服务
if (isWatch) {
    mSystemServiceManager.startService(WEAR_POWER_SERVICE_CLASS);
    mSystemServiceManager.startService(HEALTH_SERVICE_CLASS);
    mSystemServiceManager.startService(WEAR_CONNECTIVITY_SERVICE_CLASS);
    mSystemServiceManager.startService(WEAR_DISPLAY_SERVICE_CLASS);
    mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS);
    mSystemServiceManager.startService(WEAR_GLOBAL_ACTIONS_SERVICE_CLASS);
}
//启动slice服务:SliceManagerService服务通常用于管理和提供Slice切片功能,它是Android中的一种交互式内容片段,可以显示在系统桌面、通知栏或其他应用程序中,参考https://developer.android.google.cn/guide/slices?hl=zh-cn
if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_SLICES_DISABLED)) mSystemServiceManager.startService(SLICE_MANAGER_SERVICE_CLASS);
//启动IoTSystemService
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_EMBEDDED)) mSystemServiceManager.startService(IOT_SERVICE_CLASS);
//启动statscompanion和statsmanager服务:StatsCompanion类注册了两个服务,StatsCompanionService和StatsManagerService,他们一起负责管理和协调统计数据的采集、存储和处理工作
mSystemServiceManager.startServiceFromJar(STATS_COMPANION_LIFECYCLE_CLASS, STATS_COMPANION_APEX_PATH);
//启动reboot_readiness服务:RebootReadinessManagerService服务,用于检测设备是否处于空闲状态并且可以重新启动而不会造成用户中断,参考https://source.android.google.cn/docs/core/architecture/modular-system/scheduling?hl=zh-cn
mSystemServiceManager.startServiceFromJar(REBOOT_READINESS_LIFECYCLE_CLASS, SCHEDULING_APEX_PATH);
//StatsPullAtomService服务:SystemService containing PullAtomCallbacks that are registered with statsd ?
mSystemServiceManager.startService(STATS_PULL_ATOM_SERVICE_CLASS);
//启动statsbootstrap服务:StatsBootstrapAtomService服务,用于系统启动时进行初始统计数据拉取和初始化的服务
mSystemServiceManager.startService(STATS_BOOTSTRAP_ATOM_SERVICE_LIFECYCLE_CLASS);
//启动incidentcompanion服务:用于处理系统事件或故障信息的服务。IncidentCompanionService更专注于故障事件的管理和处理,而StatsBootstrapAtomService和StatsPullAtomService则更偏向于数据准备、系统初始化和性能数据拉取方面的工作
mSystemServiceManager.startService(IncidentCompanionService.class);
//启动sdk_sandbox服务:通过SdkSandboxManagerService,开发者可以更好地管理和控制SDK的运行环境,特别是在集成第三方SDK或插件时,以确保外部代码不会对系统造成潜在威胁或风险。
mSystemServiceManager.startService(SDK_SANDBOX_MANAGER_SERVICE_CLASS);
//启动adservices_manager服务:AdServicesManagerService服务,怀疑是广告相关的服务,该服务像/data/system/adservices存储了一些配置
SystemService adServices = mSystemServiceManager.startService(AD_SERVICES_MANAGER_SERVICE_CLASS);
//启动ondevicepersonalization_system_service服务:提供的构建块示例包括政策引擎,用于保护用户数据的入站流量、出站流量和列入许可名单的操作。参考https://source.android.google.cn/docs/core/architecture/modular-system/ondevicepersonalization?hl=pt-br
mSystemServiceManager.startService(ON_DEVICE_PERSONALIZATION_SYSTEM_SERVICE_CLASS);

启动telephone相关服务

//如果使能了安全模式,调用AMS接口进入安全模式
if (safeMode) mActivityManagerService.enterSafeMode();
//启动imms服务:用于处理多媒体短信(Multimedia Messaging Service即彩信)相关的功能和通讯
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) mmsService = mSystemServiceManager.startService(MmsServiceBroker.class);
//启动autofill服务:AutofillManagerService是自动填充服务。这种功能可以自动识别并填写出现过的数据,例如用户名、密码、地址等,减少用户的重复输入和提高操作效率
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOFILL)) mSystemServiceManager.startService(AUTO_FILL_MANAGER_SERVICE_CLASS);
//启动credential服务:CredentialManagerService是用于实现凭据管理服务。通常指用户的身份验证信息,如用户名、密码、API 密钥等,用于确认用户身份或授权用户访问特定资源
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_CREDENTIALS)) {
    boolean credentialManagerEnabled = DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_CREDENTIAL, CredentialManager.DEVICE_CONFIG_ENABLE_CREDENTIAL_MANAGER, true);
    if (credentialManagerEnabled)  mSystemServiceManager.startService(CREDENTIAL_MANAGER_SERVICE_CLASS);
}
//启动translation服务:TranslationManagerService是用于实现翻译管理的服务。这种服务通常用于处理文本内容的翻译,将文本从一种语言翻译成另一种语言,以满足用户在多语言环境下的需求
if (deviceHasConfigString(context, R.string.config_defaultTranslationService)) mSystemServiceManager.startService(TRANSLATION_MANAGER_SERVICE_CLASS);
//启动selection_toolbar服务:SelectionToolbarManagerService用于实现选择工具栏管理功能。这种服务通常与用户界面中的文本或内容选择交互相关,并提供一系列操作和选项以增强用户在选择文本或内容时的体验和效率
mSystemServiceManager.startService(SELECTION_TOOLBAR_MANAGER_SERVICE_CLASS);
//启动clipboard服务:ClipboardService用于实现剪贴板管理功能。剪贴板是计算机操作系统中的一种缓冲区,用于在不同应用程序之间传递数据、复制和粘贴文本、图像或其他类型的内容
mSystemServiceManager.startService(ClipboardService.class);
//启动app_binding服务:从注释和dump来看,此服务跟SMS有关系。As of android Q, we only use it for the default SMS app.
mSystemServiceManager.startService(AppBindingService.Lifecycle.class);
//启动tracing.proxy服务:此服务是Perfetto工具与systemserver的中介,帮助来抓取trace报告
mSystemServiceManager.startService(TracingServiceProxy.class);

进入PHASE_LOCK_SETTINGS_READY阶段

// It is now time to start up the app processes...
if (lockSettings != null) lockSettings.systemReady();
//system server进程进入PHASE_LOCK_SETTINGS_READY阶段,可以启动应用程序了?
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_LOCK_SETTINGS_READY);

二、SystemServer启动过程日志

1、SystemServerTiming日志封装

如上可以看出一些需要有时序的日志被封装在TimingsTraceAndSlog里面,SystemServer进程直接固定为"SystemServerTiming"。此类的traceBegin对时间搓进行了判断,即在耗时太久的时候会打印"not tracing duration of ",逻辑如下:

    public void traceBegin(String name) {
        assertSameThread();
        Trace.traceBegin(mTraceTag, name);
        if (!DEBUG_BOOT_TIME) return;
        if (mCurrentLevel + 1 >= mMaxNestedCalls) {
            Slog.w(mTag, "not tracing duration of '" + name + "' because already reached "   + mMaxNestedCalls + " levels");
            return;
        }
        mCurrentLevel++;
        mStartNames[mCurrentLevel] = name;
        mStartTimes[mCurrentLevel] = SystemClock.elapsedRealtime();
    }

2、ReadingSystemConfig多线程读取系统配置

SystemServer进程在启动看门狗之后,就开始进行系统配置文件的解析,具体代码如下:

//frameworks/base/services/java/com/android/server/SystemServer.java
// 初始化线程池
SystemServerInitThreadPool tp = SystemServerInitThreadPool.start();
mDumper.addDumpable(tp);  
Slog.i(TAG, "Reading configuration...");
final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
t.traceBegin(TAG_SYSTEM_CONFIG);
// 给线程池提交任务:SystemConfig::getInstance
SystemServerInitThreadPool.submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
t.traceEnd()
//frameworks/base/services/core/java/com/android/server/SystemServerInitThreadPool.java
public static @NonNull Future<?> submit(@NonNull Runnable runnable, @NonNull String description) {
        Objects.requireNonNull(description, "description cannot be null");
        SystemServerInitThreadPool instance;
        synchronized (LOCK) {
            Preconditions.checkState(sInstance != null, "Cannot get " + TAG  + " - it has been shut down");
            instance = sInstance;
        }//核心逻辑submitTask,最后还是调用了runnable.run(),这里相当于通过线程启动了SystemConfig::getInstance任务
        return instance.submitTask(runnable, description); 
}

如上代码相当于在线程池中启了SystemConfig.java,从他的代码逻辑可以看出读取etc目录下相关的配置文件

//frameworks/base/services/core/java/com/android/server/SystemConfig.java
//Loads global system configuration info.
//Note: Initializing this class hits the disk and is slow.  This class should generally only be accessed by the system_server process.
public class SystemConfig {
    static final String TAG = "SystemConfig";
    static SystemConfig sInstance;
    SystemConfig() {
        TimingsTraceLog log = new TimingsTraceLog(TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
        log.traceBegin("readAllPermissions");
        try {
            readAllPermissions();
            readPublicNativeLibrariesList();
        } finally {
            log.traceEnd();
        }
    }
    private void readAllPermissions() {
        final XmlPullParser parser = Xml.newPullParser();
        // Read configuration from system
        readPermissions(parser, Environment.buildPath(Environment.getRootDirectory(), "etc", "sysconfig"), ALLOW_ALL);
        // Read configuration from the old permissions dir
        readPermissions(parser, Environment.buildPath(Environment.getRootDirectory(), "etc", "permissions"), ALLOW_ALL);
        // .....省略读取其他分区的etc配置文件
    }
    private void readPublicNativeLibrariesList() {
        readPublicLibrariesListFile(new File("/vendor/etc/public.libraries.txt"));
        String[] dirs = {"/system/etc", "/system_ext/etc", "/product/etc"};
        for (String dir : dirs) {
            File[] files = new File(dir).listFiles();
            if (files == null) {
                Slog.w(TAG, "Public libraries file folder missing: " + dir);
                continue;
            }
            for (File f : files) {
                String name = f.getName();
                if (name.startsWith("public.libraries-") && name.endsWith(".txt")) {
                    readPublicLibrariesListFile(f);
                }
            }
        }
    }}

3、SystemServer启动阶段OnBootPhase

SystemServiceManager维护了改进程的各个状态,具体在 startBootPhase方法中实现:

    //Starts the specified boot phase for all system services that have been started up to this point.
    public void startBootPhase(@NonNull TimingsTraceAndSlog t, int phase) {
        if (phase <= mCurrentPhase) {
            throw new IllegalArgumentException("Next phase must be larger than previous");
        }
        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);
                long time = SystemClock.elapsedRealtime();
                t.traceBegin("OnBootPhase_" + phase + "_" + service.getClass().getName());
                try {
                    //遍历回调所有服务的onBootPhase方法,各个服务可以在此回调方法中判断当前所处阶段并执行对应需要的逻辑
                    service.onBootPhase(mCurrentPhase); 
                } catch (Exception ex) {
                    throw new RuntimeException("Failed to boot service " + service.getClass().getName() + ": onBootPhase threw an exception during phase " + mCurrentPhase, ex);
                }
                warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onBootPhase");
                t.traceEnd();
            }
        } finally {
            t.traceEnd();
        }

        if (phase == SystemService.PHASE_BOOT_COMPLETED) {
            final long totalBootTime = SystemClock.uptimeMillis() - mRuntimeStartUptime;
            t.logDuration("TotalBootTime", totalBootTime);
            SystemServerInitThreadPool.shutdown();
        }
    }

所以在每个阶段进入的时候,都会有关键日志:

Starting phase XXX

OnBootPhase_XXX

OnBootPhase_XXX_服务名

1)PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100

The earliest boot phase the system send to system services on boot. 即systemserver进程启动过程中第一个状态,系统启动后等待DMS服务的初始化,调用时间点在SystemService->startBootstrapServices:

搜索了此阶段状态,只有DisplayManagerService里面有去处理回调中此状态, 从代码逻辑来看只是简单的阻塞等待DMS初始化完成:

2)PHASE_WAIT_FOR_SENSOR_SERVICE = 200

第二个阶段,阻塞等待Sensor服务的启动,因为此阶段需要调用WMS的main方法,此方法依赖sensor服务(包括加速度计、陀螺仪、磁力传感器):

搜索了该阶段状态,只有SensorService有去处理回调中此状态, 从代码逻辑来看只是简单的等待sensor服务的启动完成,sensor服务的启动在子线程中调用jni的方式来到SensorService.cpp

3)PHASE_LOCK_SETTINGS_READY = 480

4、SystemServer无法找到服务

ArtModuleServiceInitializer.setArtModuleServiceManager(new ArtModuleServiceManager());
ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE, platformCompat);
mSystemServiceManager.startService(FileIntegrityService.class);

mSystemServiceManager.startService(Installer.class);

5、Slow operation

三、SystemServer如何启动绑定服务?

参考:Binder死磕到底(三):浅析AIDL-CSDN博客

1、 SystemServiceManager启动服务

从第一章可以看到SystemServer启动大部分的服务都是通过mSystemServiceManager的startService方法来进行启动。其参数通常只是一个继承于 SystemService的类或者类名,而不是一个实例对象。这里举个例子:

1)SystemServer启动服务

这里用WallpaperEffectsGenerationManagerService来举例子:

//AOSP/frameworks/base/services/java/com/android/server/SystemServer.java 
public final class SystemServer implements Dumpable {
    private static final String TAG = "SystemServer";
    private SystemServiceManager mSystemServiceManager;
    //.......
    private static final String WALLPAPER_EFFECTS_GENERATION_MANAGER_SERVICE_CLASS ="com.android.server.wallpapereffectsgeneration.WallpaperEffectsGenerationManagerService";    
    //.......
    private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
            // WallpaperEffectsGeneration manager service
            // TODO (b/135218095): Use deviceHasConfigString(context,
            //  R.string.config_defaultWallpaperEffectsGenerationService)
            t.traceBegin("StartWallpaperEffectsGenerationService");
            mSystemServiceManager.startService(
                    WALLPAPER_EFFECTS_GENERATION_MANAGER_SERVICE_CLASS);
            t.traceEnd();
    }

如上案例通过mSystemServiceManager.startService方法启动,SystemServiceManager管理了当前所有的系统级服务,内部维护了列表,通过反射等方式去启动服务:

//AOSP/frameworks/base/services/core/java/com/android/server/SystemServiceManager.java 
public final class SystemServiceManager implements Dumpable {
    private static final String TAG = SystemServiceManager.class.getSimpleName();
    private static final boolean DEBUG = false;
    // Services that should receive lifecycle events.
    private List<SystemService> mServices;    //维护被启动的服务实例对象
    private Set<String> mServiceClassnames;    //维护被启动的服务类名
    private int mCurrentPhase = -1;        //SystemServer进程启动的阶段
    //构造方法初始化了两个列表mServices 和mServiceClassnames ,分别来维护被启动的服务实例对象和类名
    SystemServiceManager(Context context) {
        mContext = context;
        mServices = new ArrayList<>();
        mServiceClassnames = new ArraySet<>();
        mNumUserPoolThreads = Math.min(Runtime.getRuntime().availableProcessors(),
                DEFAULT_MAX_USER_POOL_THREADS);
    }
    //通过类名去启动服务,在进行类加载
    public SystemService startService(String className) {
        final Class<SystemService> serviceClass = loadClassFromLoader(className,
                this.getClass().getClassLoader());
        return startService(serviceClass);
    }
    //通过jar去启动服务,提供jar路径去进行类加载
    public SystemService startServiceFromJar(String className, String path) {
        PathClassLoader pathClassLoader =
                SystemServerClassLoaderFactory.getOrCreateClassLoader(
                        path, this.getClass().getClassLoader(), isJarInTestApex(path));
        final Class<SystemService> serviceClass = loadClassFromLoader(className, pathClassLoader);
        return startService(serviceClass);
    }
    //进行反射实例化对应的类,并进行异常处理
    public <T extends SystemService> T startService(Class<T> serviceClass) {
        try {
            final String name = serviceClass.getName();
            Slog.i(TAG, "Starting " + name);
            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);

            // Create the service.
            if (!SystemService.class.isAssignableFrom(serviceClass)) {
                throw new RuntimeException("Failed to create " + name
                        + ": service must extend " + SystemService.class.getName());
            }
            final T service;
            try {
                Constructor<T> constructor = serviceClass.getConstructor(Context.class);
                service = constructor.newInstance(mContext);
            } catch (InstantiationException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service could not be instantiated", ex);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service must have a public constructor with a Context argument", ex);
            } catch (NoSuchMethodException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service must have a public constructor with a Context argument", ex);
            } catch (InvocationTargetException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service constructor threw an exception", ex);
            }

            startService(service);
            return service;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }
    //前面的过程都准备好后已经拿到了一个具体的实例对象,这个实例对象必现继承SystemService 
    public void startService(@NonNull final SystemService service) {
        // Check if already started
        String className = service.getClass().getName();
        //如果mServiceClassnames已经包含此类表示已经启动,不能加载第二次
        if (mServiceClassnames.contains(className)) {
            Slog.i(TAG, "Not starting an already started service " + className);
            return;
        }
        mServiceClassnames.add(className);
        //服务实例对象添加到mServices,方便后续统一维护,统一发放当前状态
        mServices.add(service);
        // Start it.
        long time = SystemClock.elapsedRealtime();
        try {//调用服务的onStart方法,正式启动服务
            service.onStart();
        } catch (RuntimeException ex) {
            throw new RuntimeException("Failed to start service " + service.getClass().getName()
                    + ": onStart threw an exception", ex);
        }
        warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
    }
    //统一对所有启动的服务更新他们的启动阶段状态
    public void startBootPhase(@NonNull TimingsTraceAndSlog t, int phase) {
        if (phase <= mCurrentPhase) {
            throw new IllegalArgumentException("Next phase must be larger than previous");
        }
        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);
                long time = SystemClock.elapsedRealtime();
                t.traceBegin("OnBootPhase_" + phase + "_" + service.getClass().getName());
                try {
                    service.onBootPhase(mCurrentPhase);
                } catch (Exception ex) {
                    throw new RuntimeException("Failed to boot service "
                            + service.getClass().getName()
                            + ": onBootPhase threw an exception during phase "
                            + mCurrentPhase, ex);
                }
                warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onBootPhase");
                t.traceEnd();
            }
        } finally {
            t.traceEnd();
        }

        if (phase == SystemService.PHASE_BOOT_COMPLETED) {
            final long totalBootTime = SystemClock.uptimeMillis() - mRuntimeStartUptime;
            t.logDuration("TotalBootTime", totalBootTime);
            SystemServerInitThreadPool.shutdown();
        }
    }
    /**
     * @return true if system has completed the boot; false otherwise.
     */
    public boolean isBootCompleted() {
        return mCurrentPhase >= SystemService.PHASE_BOOT_COMPLETED;
    }
}

2)服务主动注册ServiceManager

接着上面的WallpaperEffectsGenerationManagerService.java 例子:

//AOSP/frameworks/base/services/wallpapereffectsgeneration/java/com/android/server/wallpapereffectsgeneration/WallpaperEffectsGenerationManagerService.java
public class WallpaperEffectsGenerationManagerService extends
        AbstractMasterSystemService<WallpaperEffectsGenerationManagerService,
                WallpaperEffectsGenerationPerUserService> {
    private final ActivityTaskManagerInternal mActivityTaskManagerInternal;
    public WallpaperEffectsGenerationManagerService(Context context) {
        super(context,
                new FrameworkResourcesServiceNameResolver(context,     com.android.internal.R.string.config_defaultWallpaperEffectsGenerationService),
                null,
                PACKAGE_UPDATE_POLICY_NO_REFRESH | PACKAGE_RESTART_POLICY_NO_REFRESH);
        mActivityTaskManagerInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
    }
    public void onStart() {
        //像ServiceManager进行服务注册
        publishBinderService(WALLPAPER_EFFECTS_GENERATION_SERVICE,
                new WallpaperEffectsGenerationManagerStub());
    }
}

这里需要讨论如下两个问题:

问题一:publishBinderService是如何向ServiceManager进行服务注册?

publishBinderService本来是SystemService.java类的方法,所以前面为什么要让服务继承于SystemService:

//AOSP/frameworks/base/services/core/java/com/android/server/SystemService.java 

    protected final void publishBinderService(@NonNull String name, @NonNull IBinder service) {
        publishBinderService(name, service, false);
    }
    protected final void publishBinderService(@NonNull String name, @NonNull IBinder service,
            boolean allowIsolated) {
        publishBinderService(name, service, allowIsolated, DUMP_FLAG_PRIORITY_DEFAULT);
    }
    /**
     * Publish the service so it is accessible to other services and apps.
     *
     * @param name the name of the new service
     * @param service the service object
     * @param allowIsolated set to true to allow isolated sandboxed processes
     * to access this service
     * @param dumpPriority supported dump priority levels as a bitmask
     *
     * @hide
     */
    protected final void publishBinderService(String name, IBinder service,
            boolean allowIsolated, int dumpPriority) {
        ServiceManager.addService(name, service, allowIsolated, dumpPriority);
    }

如上核心代码,还是通过ServiceManager.addService去进行服务注册

问题二:WallpaperEffectsGenerationManagerStub是个什么东西?

如上代码在addService进行服务注册的时候的对象是一个IBinder,这个IBinder是不是比较熟悉,是ADIL里面的服务端对象?

2、SystemServiceRegistry绑定服务

上面的过程只是启动了服务,并且像ServiceManager系统中注册了服务,那么客户端进程如何使用服务呢?

方式一:ServiceManager.getService()

这种方式有弊端,系统Selinux权限禁止普通应用进程直接通过ServiceManager去获取服务

方式二:(XXXManager)getSystemService(Context.XXX_SERVICE)

这种方式,在应用开发里非常流行,例如在应用获取三方PMS或者AMS等都是这种方式:

因此如果我们需要蒋注册的服务暴露给三方应用,那么就需要对此进行实现XXXManager,系统已经提供了相关的框架,其主要源码在SystemServiceRegistry

1)SystemServiceRegistry的逻辑

如上代码在静态类实现,即类加载之后对服务进行注册,注意这里的注册服务,createService里面有两类返回值,第一类是直接实例化XXXManager回去,第二类是通过IXXX进行asInterface转换为XXXManager。这里是不是很熟悉,没错这里看起来是返回了AIDL的客户端实例对象。下面我们深入研究一下registerService方法:

registerService方法又三个参数:

  • serviceName:服务名, Context.WALLPAPER_EFFECTS_GENERATION_SERVICE,三方应用可以通过此名来获取改服务
  • serviceClass:类名,这里WallpaperEffectsGenerationManager.class
  • serviceFetcher:实现类,从注册方法里面看此实例类与签名的服务名进行匹配

问题一:serviceFetcher是什么玩意?

参考链接:系统服务 SystemServiceRegistry-CSDN博客

如上文档介绍了,此类提供了三类serviceFetcher,分别是:CachedServiceFetcher、StaticServiceFetcher、StaticApplicationContextServiceFetcher。

这里重点介绍一下CachedServiceFetcher:

2)应用层如何获取系统级服务?

通常应用代码通过Context.getSystemService(Context.XXX)来获取系统注册的服务,普通的三方应用只能通过这种方式,而无法通过ServiceManager.getService,因为她没有权限直接获取

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

如上代码逻辑,通过Context.getSystemService最后还是调用了fetcher.getService。最后回到CachedServiceFetcher里面的实现。

3、系统级服务注册和应用获取 流程总结

服务端:

  • SystemServer启动对应系统级服务,系统级服务通常在onStart的时候通过publishBinderService向系统进行注册
  • publishBinderService其实是通过ServiceManager.addService来实现

客户端:

  • 系统级客户端进程可以直接通过ServiceManager.getService获取服务,需要配置selinux权限
  • 普通应用进程只有通过Context.getSystemService来获取服务,注意普通进程使用ServiceManager.getService方式会违反neverallow原则
  • SystemServiceRegistry为Context.getSystemService提供了一套方案
  • SystemServiceRegistry维护了几个Map列表,以服务名作为键,提供 registerService方法添加到Map列表,通过 getSystemService方法从Map列表获取
  • getSystemService如果第一次获取服务,会通过ServiceFetcher的createService来创建XxxManager实例代理对象,如果不是第一次直接从Map列表中获取
  • createService第一种方式直接new XXXManager并返回 

 

  • createService第二种方式通过AIDL方式 IXXXManager.Stub.asInterface(iBinder)进行转换

下面针对IUsageStatsManager案例来进行介绍

1)接口定义IUsageStatsManager

IXXX接口定义在aosp/frameworks/base/core/java下面

因此会被编译进/system/framework/framework.jar

2)服务端实现UsageStatsService

3)SystemServiceRegistry关联客户端

如上第一行代码从ServiceManager拿到该服务的binder句柄,然后在第二行通过AIDL通用方式强转为binder通信客户端代理。最后此代理封装到UsageStatsManager里面。

此时应用进程可以直接通过通用方式来获取服务:

4)客户端实现UsageStatsManager

4、SystemServer新增服务selinux配置

当systemserver新增服务的时候,在user版本,会暴露如下selinux权限日志:

[  281.740040] .(4)[457:servicemanager]SELinux: avc:  denied  { add } for pid=10936 uid=1000 name=tinno_can scontext=u:r:system_server:s0 tcontext=u:object_r:default_android_service:s0 tclass=service_manager permissive=0

#主题进程:name/这里应该其实是systemserver进程服务
#主体上下文:scontext=u:r:system_server:s0
#客体上下文:tcontext=u:object_r:default_android_service:s0
#客体类别:tclass=service_manager
#白话文翻译:systemserver的XXX服务名称执行客体资源service_manager关联的资源的时候没有add权限
#注意:tclass=service_manager表示这里的客体资源非文件,而是service_manager维护的系统服务注册表,形成一个抽象的客体资源

并出现systemserver进程crash报错:

如上堆栈可以了解到crash原因为主动抛出异常:

最后根据此avc通过工具生成te语句,在system/sepolicy/private/system_server.te中添加如下,编译出现neverallow报错

allow system_server default_android_service:service_manager add;

总结:阻止所有域(*通配符)向Service Manager注册或操作使用,要求开发者必须为服务定义‌专属类型‌(如system_app_service),而非复用默认的通用类型。

这里我们结合源码来解读一下UsageStatsService服务的权限是如何配置。

1)服务名称的定义

UsageStatsService服务名称的定义是在Context.java,这里定义的服务名称为"usagestats"。

因此上面的selinux权限日志,本来完整的打印应该如下:

[  281.740040] .(4)[457:servicemanager]SELinux: avc:  denied  { add } for pid=10936 uid=1000 name=usagestats scontext=u:r:system_server:s0 tcontext=u:object_r:default_android_service:s0 tclass=service_manager permissive=0

2)service_contexts指定服务实例客体上下文

在aosp源码中system/sepolicy/private/service_contexts对所有的hal层服务和fw层服务进行了上下文的定义,也是这个地方进行了与前文Context.java的关联

  • 客体名称:usagestats,他的本质是一个继承SystemServer的实例对象,因此他是一个客体资源,本质还是一个死的东西。
  • 客体上下文:u:object_r:usagestats_service:s0,客体上下文,详情后面介绍。

这里的服务名和服务对应的上下文,其实是一个客体资源。如何理解他是一个客体资源呢?这里可以把他想象成她是一个XXX服务的实例对象,因此它绝对不可能是主体即我们的system_server进程。system_server进程将此服务实例对象传递到servicemanager中调用add将其注册到系统级服务里面,因此这里的实例对象其实就是一个比较抽象的客体资源。

3)service.te关联服务实例客体上下文属性

前文绑定了客体的上下文:u:object_r:usagestats_service:s0。那么usagestats_service是在哪里定义的呢?答案就在system/sepolicy/public/service.te:

此文件每一行的都以type开头,其语法规则如下:

type usagestats_service, app_api_service, ephemeral_app_api_service, system_server_service, service_manager_type;
# 其语法为:type <新类型名>, <属性1>, <属性2>, ..., <属性N>;  
# 其中type‌字段:是SELinux策略关键字,用于声明一个新的客体类型(Object Type)
# 其中<新类型名>:就是声明的新的客体类型的名称,上面就是声明了新的客体上下文,名字叫做usagestats_service
# 其中属性1-N:用来给新声明的客体上下文赋予对应的规则和权限,可以简单的理解为继承,属性1-N他们是同级的,并没有什么关联,都被定义在attributes文件中
# 其中app_api_service属性的权限说明:允许普通应用通过Binder接口调用服务
# 其中ephemeral_app_api_service属性的权限说明:限制临时应用(如单次使用或短期权限应用)的接口访问权限
# 其中system_server_service属性的权限说明:仅允许system_server(系统核心进程)绑定或管理服务
# 其中service_manager_type属性的权限说明:服务需注册到servicemanager其他进程需find权限才能发现该服务

如上语法解析,声明了一个新的客体上下文,叫做usagestats_service,他同时继承了app_api_service/ephemeral_app_service/system_server_service/service_manager_type具有的权限,其中我们这里最重要的是service_manager_type所有具有的权限。即客体上下文被指定为usagestats_service之后的所有客体资源,都具有service_manager_type带来的能力,能够被add到servicemanager维护的系统服务列表里面。

4)attributes的定义

上一节讲解的type属性的定义,都在attributes文件里面,这里我们暂不深究其语法。

原生aosp路径为:system/sepolicy/public/attributes

5)system_server.te配置访问策略

这里我们回到avc权限被拒绝的地方,

# selinux拒绝add的AVC日志:

[  281.740040] .(4)[457:servicemanager]SELinux: avc:  denied  { add } for pid=10936 uid=1000 name=tinno_can scontext=u:r:system_server:s0 tcontext=u:object_r:default_android_service:s0 tclass=service_manager permissive=0

#触发的neverallow的selinux规则语句:

allow system_server default_android_service:service_manager add;

#允许system_server进程对客体上下文default_android_service的服务对象实例,拥有service_manager场景下的添加操作。default_android_service是一个通用的服务客体资源。

#改进之后的selinux规则语句:

allow system_server tinno_can_service:service_manager add;

#允许system_server进程对客体上下文tinno_can_service这个服务对象实例,拥有service_manager场景下的添加操作,即能够将tinno_can_service对应的XXXService对象实例添加到service_manager维护的列表中。

如上演示的是新增自定义服务的配置方式。回到usagestats_service这个案例,system_server.te文件中并没有这样的语句配置,取而代之的是add_service。如下代码:

经过验证如下配置即可解决前文提到的SystemServer CRASH问题:

add_service(system_server, system_server_service);

四、SystemServer dumpsys解读

1、SystemServer的dump

2、其他服务的dump

SystemServer:
  Runtime restart: false
  Start count: 1
  Runtime start-up time: +8s0ms
  Runtime start-elapsed time: +8s0ms

SystemServiceManager:
  Current phase: 1000
  Current user not set!
  1 target users: 0(full)
  172 started services:
    com.transsion.hubcore.server.TranBootstrapServiceManagerService
    com.android.server.security.FileIntegrityService
    com.android.server.pm.Installer
    com.android.server.os.DeviceIdentifiersPolicyService
    com.android.server.uri.UriGrantsManagerService.Lifecycle
    com.android.server.powerstats.PowerStatsService
    com.android.server.permission.access.AccessCheckingService
    com.android.server.wm.ActivityTaskManagerService.Lifecycle
    com.android.server.am.ActivityManagerService.Lifecycle
    ......

com.android.server.Watchdog:
  WatchdogTimeoutMillis=60000

SystemServerInitThreadPool:
  has instance: false
  number of threads: 8
  service: java.util.concurrent.ThreadPoolExecutor@7bf04fb[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 351]
  is shutdown: true
  no pending tasks

AdServices:
  mAdServicesModuleName: com.google.android.adservices
  mAdServicesModuleVersion: 341131050
  mHandlerThread: Thread[AdServicesManagerServiceHandler,5,main]
  mAdServicesPackagesRolledBackFrom: {}
  mAdServicesPackagesRolledBackTo: {}
  ShellCmd enabled: false
  UserInstanceManager
    mAdServicesBaseDir: /data/system/adservices
    mConsentManagerMapLocked: {}
    mAppConsentManagerMapLocked: {}
    mRollbackHandlingManagerMapLocked: {}
    mBlockedTopicsManagerMapLocked={}
    TopicsDbHelper
      CURRENT_DATABASE_VERSION: 1
      mDbFile: /data/system/adservices_topics.db
      mDbVersion: 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

诸神黄昏EX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值