Android 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那些东西,详情参考请点击我
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、顺序启动服务

二、SystemServer正常启动日志

1、SystemServerTiming日志封装

2、SystemServer启动阶段OnBootPhase

3、SystemServer无法找到服务

4、Slow operation

三、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

相关推荐

  1. 使用druid对sql进行血缘

    2024-03-16 09:02:02       29 阅读
  2. InterLM代码

    2024-03-16 09:02:02       45 阅读
  3. UV、PV

    2024-03-16 09:02:02       65 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-16 09:02:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-16 09:02:02       101 阅读
  3. 在Django里面运行非项目文件

    2024-03-16 09:02:02       82 阅读
  4. Python语言-面向对象

    2024-03-16 09:02:02       91 阅读

热门阅读

  1. WPF触发器与模板

    2024-03-16 09:02:02       37 阅读
  2. Go 构建高效的二叉搜索树联系簿

    2024-03-16 09:02:02       43 阅读
  3. C语言经典面试题目(八)

    2024-03-16 09:02:02       47 阅读
  4. HCI命令

    2024-03-16 09:02:02       30 阅读
  5. 大白话聊聊:DevOps

    2024-03-16 09:02:02       38 阅读
  6. 关于设计和搭建Devops平台的20道高级面试题

    2024-03-16 09:02:02       37 阅读
  7. 简单分析SpringMVC的处理请求流程

    2024-03-16 09:02:02       42 阅读
  8. C语言课后作业 20 题+考研上机应用题

    2024-03-16 09:02:02       34 阅读
  9. SpringMVC—异常处理

    2024-03-16 09:02:02       39 阅读
  10. MySQL `COALESCE` 函数

    2024-03-16 09:02:02       36 阅读
  11. docker compose部署opensearch集群

    2024-03-16 09:02:02       40 阅读
  12. Qt 数据结构介绍

    2024-03-16 09:02:02       36 阅读
  13. QCheckbox的toggled(bool)和clicked(bool)信号

    2024-03-16 09:02:02       33 阅读