当前位置:   article > 正文

Android FrameWork(三)SystemServer(下)_systemserverinitthreadpool: shutdown requested

systemserverinitthreadpool: shutdown requested

    上次说到,从Zygote.forkSystemServer()一直到SystemServer.main()。这篇博客,将从SystemServer的main方法开始说起。没看过SystemServer(一)的可以先去看一下:Android FrameWork之SystemServer(一)

 一.SystemServer.main()

    首先,SystemServer.java的路径如下:/frameworks/base/services/java/com/android/server/SystemServer.java。我们看一下其main()方法:

  1. /**
  2. * The main entry point from zygote.
  3. */
  4. public static void main(String[] args) {
  5. new SystemServer().run();
  6. }

    非常简短的方法,创建一个SystemServerd对象,然后调用其run()方法。

二.SystemServer.run()

    run()方法是一个很长的方法,其实也还好,注释占了很大一部分篇幅,源码如下:

  1. private void run() {
  2. try {
  3. traceBeginAndSlog("InitBeforeStartServices");
  4. // If a device's clock is before 1970 (before 0), a lot of
  5. // APIs crash dealing with negative numbers, notably
  6. // java.io.File#setLastModified, so instead we fake it and
  7. // hope that time from cell towers or NTP fixes it shortly.
  8. if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
  9. Slog.w(TAG, "System clock is before 1970; setting to 1970.");
  10. SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
  11. }
  12. //
  13. // Default the timezone property to GMT if not set.
  14. //
  15. String timezoneProperty = SystemProperties.get("persist.sys.timezone");
  16. if (timezoneProperty == null || timezoneProperty.isEmpty()) {
  17. Slog.w(TAG, "Timezone not set; setting to GMT.");
  18. SystemProperties.set("persist.sys.timezone", "GMT");
  19. }
  20. // If the system has "persist.sys.language" and friends set, replace them with
  21. // "persist.sys.locale". Note that the default locale at this point is calculated
  22. // using the "-Duser.locale" command line flag. That flag is usually populated by
  23. // AndroidRuntime using the same set of system properties, but only the system_server
  24. // and system apps are allowed to set them.
  25. //
  26. // NOTE: Most changes made here will need an equivalent change to
  27. // core/jni/AndroidRuntime.cpp
  28. if (!SystemProperties.get("persist.sys.language").isEmpty()) {
  29. final String languageTag = Locale.getDefault().toLanguageTag();
  30. SystemProperties.set("persist.sys.locale", languageTag);
  31. SystemProperties.set("persist.sys.language", "");
  32. SystemProperties.set("persist.sys.country", "");
  33. SystemProperties.set("persist.sys.localevar", "");
  34. }
  35. // The system server should never make non-oneway calls
  36. Binder.setWarnOnBlocking(true);
  37. // The system server should always load safe labels
  38. PackageItemInfo.setForceSafeLabels(true);
  39. // Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
  40. SQLiteCompatibilityWalFlags.init(null);
  41. // Here we go!
  42. Slog.i(TAG, "Entered the Android system server!");
  43. int uptimeMillis = (int) SystemClock.elapsedRealtime();
  44. EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
  45. if (!mRuntimeRestart) {
  46. MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
  47. }
  48. // In case the runtime switched since last boot (such as when
  49. // the old runtime was removed in an OTA), set the system
  50. // property so that it is in sync. We can | xq oqi't do this in
  51. // libnativehelper's JniInvocation::Init code where we already
  52. // had to fallback to a different runtime because it is
  53. // running as root and we need to be the system user to set
  54. // the property. http://b/11463182
  55. SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
  56. // Mmmmmm... more memory!
  57. VMRuntime.getRuntime().clearGrowthLimit();
  58. // The system server has to run all of the time, so it needs to be
  59. // as efficient as possible with its memory usage.
  60. VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
  61. // Some devices rely on runtime fingerprint generation, so make sure
  62. // we've defined it before booting further.
  63. Build.ensureFingerprintProperty();
  64. // Within the system server, it is an error to access Environment paths without
  65. // explicitly specifying a user.
  66. Environment.setUserRequired(true);
  67. // Within the system server, any incoming Bundles should be defused
  68. // to avoid throwing BadParcelableException.
  69. BaseBundle.setShouldDefuse(true);
  70. // Within the system server, when parceling exceptions, include the stack trace
  71. Parcel.setStackTraceParceling(true);
  72. // Ensure binder calls into the system always run at foreground priority.
  73. BinderInternal.disableBackgroundScheduling(true);
  74. // Increase the number of binder threads in system_server
  75. BinderInternal.setMaxThreads(sMaxBinderThreads);
  76. // Prepare the main looper thread (this thread).
  77. android.os.Process.setThreadPriority(
  78. android.os.Process.THREAD_PRIORITY_FOREGROUND);
  79. android.os.Process.setCanSelfBackground(false);
  80. Looper.prepareMainLooper();
  81. Looper.getMainLooper().setSlowLogThresholdMs(
  82. SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
  83. // Initialize native services.
  84. System.loadLibrary("android_servers");
  85. // Check whether we failed to shut down last time we tried.
  86. // This call may not return.
  87. performPendingShutdown();
  88. // Initialize the system context.
  89. createSystemContext();
  90. // Create the system service manager.
  91. mSystemServiceManager = new SystemServiceManager(mSystemContext);
  92. mSystemServiceManager.setStartInfo(mRuntimeRestart,
  93. mRuntimeStartElapsedTime, mRuntimeStartUptime);
  94. LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
  95. // Prepare the thread pool for init tasks that can be parallelized
  96. SystemServerInitThreadPool.get();
  97. } finally {
  98. traceEnd(); // InitBeforeStartServices
  99. }
  100. // Start services.
  101. try {
  102. traceBeginAndSlog("StartServices");
  103. startBootstrapServices();
  104. startCoreServices();
  105. startOtherServices();
  106. SystemServerInitThreadPool.shutdown();
  107. } catch (Throwable ex) {
  108. Slog.e("System", "******************************************");
  109. Slog.e("System", "************ Failure starting system services", ex);
  110. throw ex;
  111. } finally {
  112. traceEnd();
  113. }
  114. StrictMode.initVmDefaults(null);
  115. if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
  116. int uptimeMillis = (int) SystemClock.elapsedRealtime();
  117. MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
  118. final int MAX_UPTIME_MILLIS = 60 * 1000;
  119. if (uptimeMillis > MAX_UPTIME_MILLIS) {
  120. Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
  121. "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
  122. }
  123. }
  124. // Loop forever.
  125. Looper.loop();
  126. throw new RuntimeException("Main thread loop unexpectedly exited");
  127. }

    run()方法主要做了哪些工作?让我们一起跟着源码和注释分析一下:

    (1)如果系统时间早于1970年,则设置系统时间为1970年

  1. if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
  2. Slog.w(TAG, "System clock is before 1970; setting to 1970.");
  3. SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
  4. }

    (2)如果时区没有设置,设置时区为GMT(格林尼治标准时间)

  1. if (timezoneProperty == null || timezoneProperty.isEmpty()) {
  2. Slog.w(TAG, "Timezone not set; setting to GMT.");
  3. SystemProperties.set("persist.sys.timezone", "GMT");
  4. }

    (3)设置语言,国家,地区等(只有system server或者系统app才能修改)

  1. if (!SystemProperties.get("persist.sys.language").isEmpty()) {
  2. final String languageTag = Locale.getDefault().toLanguageTag();
  3. SystemProperties.set("persist.sys.locale", languageTag);
  4. SystemProperties.set("persist.sys.language", "");
  5. SystemProperties.set("persist.sys.country", "");
  6. SystemProperties.set("persist.sys.localevar", "");
  7. }

    (4)变更库文件,因为默认使用的是libart.so

SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());

    (5)清除内存增长上限,为启动过程提供更多的内存空间

VMRuntime.getRuntime().clearGrowthLimit();

    (6)设置内存可能的利用率为0.8

VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

    (7)在开机完成前定义指纹信息

Build.ensureFingerprintProperty();

    (8)设置Binder的优先级和最大线程数

  1. BinderInternal.disableBackgroundScheduling(true);
  2. BinderInternal.setMaxThreads(sMaxBinderThreads);

    (9)准备主线程Looper

  1. // Prepare the main looper thread (this thread).
  2. android.os.Process.setThreadPriority(
  3. android.os.Process.THREAD_PRIORITY_FOREGROUND);
  4. android.os.Process.setCanSelfBackground(false);
  5. Looper.prepareMainLooper();
  6. Looper.getMainLooper().setSlowLogThresholdMs(
  7. SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);

    (10)初始化系统上下文

createSystemContext();

    (11)创建System Service Manager

  1. mSystemServiceManager = new SystemServiceManager(mSystemContext);
  2. mSystemServiceManager.setStartInfo(mRuntimeRestart,
  3. mRuntimeStartElapsedTime, mRuntimeStartUptime);
  4. LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

     (12)启动各种系统服务

  1. traceBeginAndSlog("StartServices");
  2. startBootstrapServices();
  3. startCoreServices();
  4. startOtherServices();
  5. SystemServerInitThreadPool.shutdown();

    (13)循环执行

  1. // Loop forever.
  2. Looper.loop();

三.startBootstrapServices()

    做的主要工作是启动一些服务,例如我们常说的:ActivityManagerService, PowerManagerService,DisplayManagerService, PackageManagerService等。

  1. /**
  2. * Starts the small tangle of critical services that are needed to get
  3. * the system off the ground. These services have complex mutual dependencies
  4. * which is why we initialize them all in one place here. Unless your service
  5. * is also entwined in these dependencies, it should be initialized in one of
  6. * the other functions.
  7. */
  8. private void startBootstrapServices() {
  9. Slog.i(TAG, "Reading configuration...");
  10. final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
  11. traceBeginAndSlog(TAG_SYSTEM_CONFIG);
  12. SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
  13. traceEnd();
  14. // Wait for installd to finish starting up so that it has a chance to
  15. // create critical directories such as /data/user with the appropriate
  16. // permissions. We need this to complete before we initialize other services.
  17. traceBeginAndSlog("StartInstaller");
  18. Installer installer = mSystemServiceManager.startService(Installer.class);
  19. traceEnd();
  20. // In some cases after launching an app we need to access device identifiers,
  21. // therefore register the device identifier policy before the activity manager.
  22. traceBeginAndSlog("DeviceIdentifiersPolicyService");
  23. mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
  24. traceEnd();
  25. // Activity manager runs the show.
  26. traceBeginAndSlog("StartActivityManager");
  27. mActivityManagerService = mSystemServiceManager.startService(
  28. ActivityManagerService.Lifecycle.class).getService();
  29. mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
  30. mActivityManagerService.setInstaller(installer);
  31. traceEnd();
  32. // Power manager needs to be started early because other services need it.
  33. // Native daemons may be watching for it to be registered so it must be ready
  34. // to handle incoming binder calls immediately (including being able to verify
  35. // the permissions for those calls).
  36. traceBeginAndSlog("StartPowerManager");
  37. mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
  38. traceEnd();
  39. // Now that the power manager has been started, let the activity manager
  40. // initialize power management features.
  41. traceBeginAndSlog("InitPowerManagement");
  42. mActivityManagerService.initPowerManagement();
  43. traceEnd();
  44. // Bring up recovery system in case a rescue party needs a reboot
  45. traceBeginAndSlog("StartRecoverySystemService");
  46. mSystemServiceManager.startService(RecoverySystemService.class);
  47. traceEnd();
  48. // Now that we have the bare essentials of the OS up and running, take
  49. // note that we just booted, which might send out a rescue party if
  50. // we're stuck in a runtime restart loop.
  51. RescueParty.noteBoot(mSystemContext);
  52. // Manages LEDs and display backlight so we need it to bring up the display.
  53. traceBeginAndSlog("StartLightsService");
  54. mSystemServiceManager.startService(LightsService.class);
  55. traceEnd();
  56. traceBeginAndSlog("StartSidekickService");
  57. // Package manager isn't started yet; need to use SysProp not hardware feature
  58. if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
  59. mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
  60. }
  61. traceEnd();
  62. // Display manager is needed to provide display metrics before package manager
  63. // starts up.
  64. traceBeginAndSlog("StartDisplayManager");
  65. mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
  66. traceEnd();
  67. // We need the default display before we can initialize the package manager.
  68. traceBeginAndSlog("WaitForDisplay");
  69. mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
  70. traceEnd();
  71. // Only run "core" apps if we're encrypting the device.
  72. String cryptState = SystemProperties.get("vold.decrypt");
  73. if (ENCRYPTING_STATE.equals(cryptState)) {
  74. Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
  75. mOnlyCore = true;
  76. } else if (ENCRYPTED_STATE.equals(cryptState)) {
  77. Slog.w(TAG, "Device encrypted - only parsing core apps");
  78. mOnlyCore = true;
  79. }
  80. // Start the package manager.
  81. if (!mRuntimeRestart) {
  82. MetricsLogger.histogram(null, "boot_package_manager_init_start",
  83. (int) SystemClock.elapsedRealtime());
  84. }
  85. traceBeginAndSlog("StartPackageManagerService");
  86. mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
  87. mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
  88. mFirstBoot = mPackageManagerService.isFirstBoot();
  89. mPackageManager = mSystemContext.getPackageManager();
  90. traceEnd();
  91. if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
  92. MetricsLogger.histogram(null, "boot_package_manager_init_ready",
  93. (int) SystemClock.elapsedRealtime());
  94. }
  95. // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
  96. // A/B artifacts after boot, before anything else might touch/need them.
  97. // Note: this isn't needed during decryption (we don't have /data anyways).
  98. if (!mOnlyCore) {
  99. boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
  100. false);
  101. if (!disableOtaDexopt) {
  102. traceBeginAndSlog("StartOtaDexOptService");
  103. try {
  104. OtaDexoptService.main(mSystemContext, mPackageManagerService);
  105. } catch (Throwable e) {
  106. reportWtf("starting OtaDexOptService", e);
  107. } finally {
  108. traceEnd();
  109. }
  110. }
  111. }
  112. traceBeginAndSlog("StartUserManagerService");
  113. mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
  114. traceEnd();
  115. // Initialize attribute cache used to cache resources from packages.
  116. traceBeginAndSlog("InitAttributerCache");
  117. AttributeCache.init(mSystemContext);
  118. traceEnd();
  119. // Set up the Application instance for the system process and get started.
  120. traceBeginAndSlog("SetSystemProcess");
  121. mActivityManagerService.setSystemProcess();
  122. traceEnd();
  123. // DisplayManagerService needs to setup android.display scheduling related policies
  124. // since setSystemProcess() would have overridden policies due to setProcessGroup
  125. mDisplayManagerService.setupSchedulerPolicies();
  126. // Manages Overlay packages
  127. traceBeginAndSlog("StartOverlayManagerService");
  128. mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));
  129. traceEnd();
  130. // The sensor service needs access to package manager service, app ops
  131. // service, and permissions service, therefore we start it after them.
  132. // Start sensor service in a separate thread. Completion should be checked
  133. // before using it.
  134. mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
  135. TimingsTraceLog traceLog = new TimingsTraceLog(
  136. SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
  137. traceLog.traceBegin(START_SENSOR_SERVICE);
  138. startSensorService();
  139. traceLog.traceEnd();
  140. }, START_SENSOR_SERVICE);
  141. }

四.startCoreServices

     启动一些核心的服务:BatteryService,UsageStatsService,WebViewUpdateService。

  1. /**
  2. * Starts some essential services that are not tangled up in the bootstrap process.
  3. */
  4. private void startCoreServices() {
  5. traceBeginAndSlog("StartBatteryService");
  6. // Tracks the battery level. Requires LightService.
  7. mSystemServiceManager.startService(BatteryService.class);
  8. traceEnd();
  9. // Tracks application usage stats.
  10. traceBeginAndSlog("StartUsageService");
  11. mSystemServiceManager.startService(UsageStatsService.class);
  12. mActivityManagerService.setUsageStatsManager(
  13. LocalServices.getService(UsageStatsManagerInternal.class));
  14. traceEnd();
  15. // Tracks whether the updatable WebView is in a ready state and watches for update installs.
  16. if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
  17. traceBeginAndSlog("StartWebViewUpdateService");
  18. mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
  19. traceEnd();
  20. }
  21. // Tracks cpu time spent in binder calls
  22. traceBeginAndSlog("StartBinderCallsStatsService");
  23. BinderCallsStatsService.start();
  24. traceEnd();
  25. }

    SystemServer还会启动一些其他的服务,代码太多,不再一一去看。

    最后,总结一下。System Server是zygote进程fork的第一个进程,是android 基本服务的提供者,FrameWork关键的系统服务全由此创建而来。可以说,整个android系统的业务都是围绕system server而展开。一旦SystemServer挂了,整个手机系统也就挂了。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/227806?site
推荐阅读
相关标签
  

闽ICP备14008679号