• Android SystemServer进程解析


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

    一、SystemServer进程主函数流程

    1、主函数三部曲

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

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

    1)初始化上下文
    1. //frameworks/base/services/java/com/android/server/SystemServer.java
    2. private void run() {
    3. TimingsTraceAndSlog t = new TimingsTraceAndSlog();
    4. try {
    5. t.traceBegin("InitBeforeStartServices");
    6. //.....一些属性的初始化....
    7. // The system server should never make non-oneway calls
    8. Binder.setWarnOnBlocking(true);
    9. // The system server should always load safe labels
    10. PackageItemInfo.forceSafeLabels();
    11. // Default to FULL within the system server.
    12. SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;
    13. // Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
    14. SQLiteCompatibilityWalFlags.init(null);
    15. // Here we go!
    16. Slog.i(TAG, "Entered the Android system server!");
    17. final long uptimeMillis = SystemClock.elapsedRealtime(); //记录开始启动的时间错,调试系统启动时间的时候需要关注
    18. // Mmmmmm... more memory!
    19. VMRuntime.getRuntime().clearGrowthLimit();
    20. // Some devices rely on runtime fingerprint generation, so make sure we've defined it before booting further.
    21. Build.ensureFingerprintProperty();
    22. // Within the system server, it is an error to access Environment paths without explicitly specifying a user.
    23. Environment.setUserRequired(true);
    24. // Within the system server, any incoming Bundles should be defused to avoid throwing BadParcelableException.
    25. BaseBundle.setShouldDefuse(true);
    26. // Within the system server, when parceling exceptions, include the stack trace
    27. Parcel.setStackTraceParceling(true);
    28. // Ensure binder calls into the system always run at foreground priority.
    29. BinderInternal.disableBackgroundScheduling(true);
    30. // Increase the number of binder threads in system_server
    31. BinderInternal.setMaxThreads(sMaxBinderThreads);
    32. // Prepare the main looper thread (this thread).
    33. android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);
    34. android.os.Process.setCanSelfBackground(false);
    35. Looper.prepareMainLooper();
    36. Looper.getMainLooper().setSlowLogThresholdMs(SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
    37. SystemServiceRegistry.sEnableServiceNotFoundWtf = true;
    38. // Initialize native services.
    39. System.loadLibrary("android_servers");
    40. // Allow heap / perf profiling.
    41. initZygoteChildHeapProfiling();
    42. // Check whether we failed to shut down last time we tried. This call may not return.
    43. performPendingShutdown();
    44. // Initialize the system context.
    45. createSystemContext();
    46. // Call per-process mainline module initialization.
    47. ActivityThread.initializeMainlineModules();
    48. } finally {
    49. t.traceEnd(); // InitBeforeStartServices
    50. }
    2)启动系统所有服务
    1. //frameworks/base/services/java/com/android/server/SystemServer.java
    2. // Start services.
    3. try {
    4. t.traceBegin("StartServices");
    5. startBootstrapServices(t); //启动BOOT服务(即没有这些服务系统无法运行)
    6. startCoreServices(t); //启动核心服务
    7. startOtherServices(t); //启动其他服务
    8. startApexServices(t); //启动APEX服务,此服务必现要在前面的所有服务启动之后才能启动,为了防止OTA相关问题
    9. // Only update the timeout after starting all the services so that we use
    10. // the default timeout to start system server.
    11. updateWatchdogTimeout(t);
    12. } catch (Throwable ex) {
    13. Slog.e("System", "******************************************");
    14. Slog.e("System", "************ Failure starting system services", ex);
    15. throw ex;
    16. } finally {
    17. t.traceEnd(); // StartServices
    18. }
    19. /**
    20. * Starts system services defined in apexes.
    21. *

      Apex services must be the last category of services to start. No other service must be

    22. * starting after this point. This is to prevent unnecessary stability issues when these apexes
    23. * are updated outside of OTA; and to avoid breaking dependencies from system into apexes.
    24. */
    25. private void startApexServices(@NonNull TimingsTraceAndSlog t) {
    26. t.traceBegin("startApexServices");
    27. // TODO(b/192880996): get the list from "android" package, once the manifest entries are migrated to system manifest.
    28. List services = ApexManager.getInstance().getApexSystemServices();
    29. for (ApexSystemServiceInfo info : services) {
    30. String name = info.getName();
    31. String jarPath = info.getJarPath();
    32. t.traceBegin("starting " + name);
    33. if (TextUtils.isEmpty(jarPath)) {
    34. mSystemServiceManager.startService(name);
    35. } else {
    36. mSystemServiceManager.startServiceFromJar(name, jarPath);
    37. }
    38. t.traceEnd();
    39. }
    40. // make sure no other services are started after this point
    41. mSystemServiceManager.sealStartedServices();
    42. t.traceEnd(); // startApexServices
    43. }

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

    • startBootstrapServices:启动一些关键引导服务,这些服务耦合到一起
    • startCoreServices:启动一些关键引导服务,这些服务没有耦合到一起
    • startOtherServices:启动其他一些杂七杂八的服务
    • startApexServices:启动apex类的服务,其实就是mainline那些东西,详情参考请点击我
    3)进入loop循环
    1. //frameworks/base/services/java/com/android/server/SystemServer.java
    2. StrictMode.initVmDefaults(null);
    3. if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
    4. final long uptimeMillis = SystemClock.elapsedRealtime();
    5. final long maxUptimeMillis = 60 * 1000;
    6. if (uptimeMillis > maxUptimeMillis) {
    7. Slog.wtf(SYSTEM_SERVER_TIMING_TAG, "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
    8. }
    9. }
    10. // Loop forever.
    11. Looper.loop();
    12. 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

    1. SystemServer:
    2. Runtime restart: false
    3. Start count: 1
    4. Runtime start-up time: +8s0ms
    5. Runtime start-elapsed time: +8s0ms
    6. SystemServiceManager:
    7. Current phase: 1000
    8. Current user not set!
    9. 1 target users: 0(full)
    10. 172 started services:
    11. com.transsion.hubcore.server.TranBootstrapServiceManagerService
    12. com.android.server.security.FileIntegrityService
    13. com.android.server.pm.Installer
    14. com.android.server.os.DeviceIdentifiersPolicyService
    15. com.android.server.uri.UriGrantsManagerService.Lifecycle
    16. com.android.server.powerstats.PowerStatsService
    17. com.android.server.permission.access.AccessCheckingService
    18. com.android.server.wm.ActivityTaskManagerService.Lifecycle
    19. com.android.server.am.ActivityManagerService.Lifecycle
    20. ......
    21. com.android.server.Watchdog:
    22. WatchdogTimeoutMillis=60000
    23. SystemServerInitThreadPool:
    24. has instance: false
    25. number of threads: 8
    26. service: java.util.concurrent.ThreadPoolExecutor@7bf04fb[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 351]
    27. is shutdown: true
    28. no pending tasks
    29. AdServices:
    30. mAdServicesModuleName: com.google.android.adservices
    31. mAdServicesModuleVersion: 341131050
    32. mHandlerThread: Thread[AdServicesManagerServiceHandler,5,main]
    33. mAdServicesPackagesRolledBackFrom: {}
    34. mAdServicesPackagesRolledBackTo: {}
    35. ShellCmd enabled: false
    36. UserInstanceManager
    37. mAdServicesBaseDir: /data/system/adservices
    38. mConsentManagerMapLocked: {}
    39. mAppConsentManagerMapLocked: {}
    40. mRollbackHandlingManagerMapLocked: {}
    41. mBlockedTopicsManagerMapLocked={}
    42. TopicsDbHelper
    43. CURRENT_DATABASE_VERSION: 1
    44. mDbFile: /data/system/adservices_topics.db
    45. mDbVersion: 1

  • 相关阅读:
    MySql 数据类型选择与优化
    cpp中的内存管理 静态存储 内存分配与链接性的讨论
    科学计算与仿真-高斯牛顿法的非线性最小二乘问题简单介绍与应用
    Java注解
    分页存储逻辑地址转物理地址
    2024.6.13刷题记录
    【嵌入式开发】UART
    【数学建模】层次分析
    浅析RocketMQ-MappedFileQueue和MappedFile
    架构学习——Redis内存数据库学习要点
  • 原文地址:https://blog.csdn.net/qq_27672101/article/details/136746558