当前位置:   article > 正文

Android10 系统进程SystemServer_system_server进程 binder 线程

system_server进程 binder 线程

1、Android10 源码编译相关问题

2、Android10 系统进程Zygote启动

3、Android10 系统进程SystemServer

4、Android10 launcher启动流程

5、Android10 系统发送开机广播时机

6、Android10 AppComponentFactory源码梳理

7、Android10 InputManagerService事件输入输出

8、Android10 InputManagerService本地实现

9、Android10 SystemUI系统手势导航


        在上一节Android10 系统进程Zygote启动中主要是说了Zygote进程启动,在其中有说到Zygote进程会创建SystemServer进程,并执行其中的main()函数。SystemServer进程承载整个Android framework层的核心服务,这里就先来看看/frameworks/base/services/java/com/android/server/SystemServer.java的main()函数:

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

创建一个SystemServer对象,并执行它的run()方法:

  1. private void run() {
  2. try {
  3. traceBeginAndSlog("InitBeforeStartServices");
  4. // Record the process start information in sys props.
  5. //在创建这个对象的时候会初始化如下属性,这里再把这些属性设置到系统中
  6. SystemProperties.set(SYSPROP_START_COUNT, String.valueOf(mStartCount));//设置开机的次数
  7. SystemProperties.set(SYSPROP_START_ELAPSED, String.valueOf(mRuntimeStartElapsedTime));
  8. SystemProperties.set(SYSPROP_START_UPTIME, String.valueOf(mRuntimeStartUptime));
  9. EventLog.writeEvent(EventLogTags.SYSTEM_SERVER_START,
  10. mStartCount, mRuntimeStartUptime, mRuntimeStartElapsedTime);
  11. //如果一个设备的时钟是在1970年之前(0年之前),
  12. //那么很多api 都会因为处理负数而崩溃,尤其是java.io.File#setLastModified
  13. //我把把时间设置为1970
  14. if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
  15. Slog.w(TAG, "System clock is before 1970; setting to 1970.");
  16. SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
  17. }
  18. //如果时区不存在,设置时区为GMT
  19. String timezoneProperty = SystemProperties.get("persist.sys.timezone");
  20. if (timezoneProperty == null || timezoneProperty.isEmpty()) {
  21. Slog.w(TAG, "Timezone not set; setting to GMT.");
  22. SystemProperties.set("persist.sys.timezone", "GMT");
  23. }
  24. //变更虚拟机的库文件,对于Android 10.0默认采用的是libart.so
  25. SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
  26. // Mmmmmm... more memory!
  27. //清除vm内存增长上限,由于启动过程需要较多的虚拟机内存空间
  28. VMRuntime.getRuntime().clearGrowthLimit();
  29. ...
  30. //系统服务器必须一直运行,所以它需要尽可能高效地使用内存
  31. //设置内存的可能有效使用率为0.8
  32. VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
  33. //一些设备依赖于运行时指纹生成,所以在进一步启动之前,请确保我们已经定义了它。
  34. Build.ensureFingerprintProperty();
  35. //访问环境变量前,需要明确地指定用户
  36. //在system_server中,任何传入的包都应该被解除,以避免抛出BadParcelableException。
  37. BaseBundle.setShouldDefuse(true);
  38. //在system_server中,当打包异常时,信息需要包含堆栈跟踪
  39. Parcel.setStackTraceParceling(true);
  40. //确保当前系统进程的binder调用,总是运行在前台优先级(foreground priority)
  41. BinderInternal.disableBackgroundScheduling(true);
  42. //设置system_server中binder线程的最大数量,最大值为31
  43. BinderInternal.setMaxThreads(sMaxBinderThreads);
  44. //准备主线程lopper,即在当前线程运行
  45. android.os.Process.setThreadPriority(
  46. android.os.Process.THREAD_PRIORITY_FOREGROUND);
  47. android.os.Process.setCanSelfBackground(false);
  48. Looper.prepareMainLooper();
  49. Looper.getMainLooper().setSlowLogThresholdMs(
  50. SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
  51. //加载android_servers.so库,初始化native service
  52. System.loadLibrary("android_servers");
  53. // Debug builds - allow heap profiling.
  54. //如果是Debug版本,允许堆内存分析
  55. if (Build.IS_DEBUGGABLE) {
  56. initZygoteChildHeapProfiling();
  57. }
  58. //检测上次关机过程是否失败,这个调用可能不会返回
  59. performPendingShutdown();
  60. //初始化系统上下文
  61. createSystemContext();
  62. //创建系统服务管理--SystemServiceManager
  63. mSystemServiceManager = new SystemServiceManager(mSystemContext);
  64. mSystemServiceManager.setStartInfo(mRuntimeRestart,
  65. mRuntimeStartElapsedTime, mRuntimeStartUptime);
  66. //将mSystemServiceManager添加到本地服务的成员sLocalServiceObjects
  67. LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
  68. // Prepare the thread pool for init tasks that can be parallelized
  69. //为可以并行化的init任务准备线程池
  70. SystemServerInitThreadPool.get();
  71. } finally {
  72. traceEnd(); // InitBeforeStartServices
  73. }
  74. // Start services.
  75. //启动服务
  76. try {
  77. traceBeginAndSlog("StartServices");
  78. startBootstrapServices(); // 启动引导服务
  79. startCoreServices(); // 启动核心服务
  80. startOtherServices(); // 启动其他服务
  81. SystemServerInitThreadPool.shutdown(); //停止线程池
  82. } catch (Throwable ex) {
  83. Slog.e("System", "******************************************");
  84. Slog.e("System", "************ Failure starting system services", ex);
  85. throw ex;
  86. } finally {
  87. traceEnd();
  88. }
  89. //为当前的虚拟机初始化VmPolicy
  90. StrictMode.initVmDefaults(null);
  91. ...
  92. // Loop forever.
  93. //死循环执行
  94. Looper.loop();
  95. throw new RuntimeException("Main thread loop unexpectedly exited");
  96. }

这里主要是初始化一些系统变量、创建系统上下文、创建系统服务管理对象SystemServiceManager,最后才是去启动系统服务,这里启动系统服务又分为三类:引导服务、核心服务、其他服务,下面来进入里面去看看:

创建系统上下文

  1. private void createSystemContext() {
  2. //创建systemserver进程的上下文信息
  3. ActivityThread activityThread = ActivityThread.systemMain();
  4. mSystemContext = activityThread.getSystemContext();
  5. //设置主题
  6. mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
  7. //获取systemui上下文信息,并设置主题
  8. final Context systemUiContext = activityThread.getSystemUiContext();
  9. systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
  10. }

 该过程会创建对象有ActivityThread,Instrumentation, ContextImpl,LoadedApk,Application,这可以有个注意的地方,创建ActivityThread是通过它的systemMain()方法,而正常通过ActivityThread创建应用进程是通过它的main()方法。

创建系统服务管理对象SystemServiceManager

        SystemServiceManager这个对象主要作用是用于创建 已经管理系统服务,下面将这个类简化下:

  1. public class SystemServiceManager {
  2. private static final String TAG = "SystemServiceManager";
  3. private final Context mContext;
  4. // Services that should receive lifecycle events.
  5. private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
  6. SystemServiceManager(Context context) {
  7. mContext = context;
  8. }
  9. /*
  10. * Loads and initializes a class from the given classLoader. Returns the class.
  11. */
  12. @SuppressWarnings("unchecked")
  13. private static Class<SystemService> loadClassFromLoader(String className,
  14. ClassLoader classLoader) {
  15. try {
  16. return (Class<SystemService>) Class.forName(className, true, classLoader);
  17. } catch (ClassNotFoundException ex) {
  18. throw new RuntimeException("Failed to create service " + className
  19. + " from class loader " + classLoader.toString() + ": service class not "
  20. + "found, usually indicates that the caller should "
  21. + "have called PackageManager.hasSystemFeature() to check whether the "
  22. + "feature is available on this device before trying to start the "
  23. + "services that implement it. Also ensure that the correct path for the "
  24. + "classloader is supplied, if applicable.", ex);
  25. }
  26. }
  27. /**
  28. * Creates and starts a system service. The class must be a subclass of
  29. * {@link com.android.server.SystemService}.
  30. *
  31. * @param serviceClass A Java class that implements the SystemService interface.
  32. * @return The service instance, never null.
  33. * @throws RuntimeException if the service fails to start.
  34. */
  35. public <T extends SystemService> T startService(Class<T> serviceClass) {
  36. try {
  37. final String name = serviceClass.getName();
  38. Slog.i(TAG, "Starting " + name);
  39. Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);
  40. // Create the service.
  41. if (!SystemService.class.isAssignableFrom(serviceClass)) {
  42. throw new RuntimeException("Failed to create " + name
  43. + ": service must extend " + SystemService.class.getName());
  44. }
  45. final T service;
  46. try {
  47. Constructor<T> constructor = serviceClass.getConstructor(Context.class);
  48. service = constructor.newInstance(mContext);
  49. } catch (InstantiationException ex) {
  50. throw new RuntimeException("Failed to create service " + name
  51. + ": service could not be instantiated", ex);
  52. } catch (IllegalAccessException ex) {
  53. throw new RuntimeException("Failed to create service " + name
  54. + ": service must have a public constructor with a Context argument", ex);
  55. } catch (NoSuchMethodException ex) {
  56. throw new RuntimeException("Failed to create service " + name
  57. + ": service must have a public constructor with a Context argument", ex);
  58. } catch (InvocationTargetException ex) {
  59. throw new RuntimeException("Failed to create service " + name
  60. + ": service constructor threw an exception", ex);
  61. }
  62. startService(service);
  63. return service;
  64. } finally {
  65. Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
  66. }
  67. }
  68. public void startService(@NonNull final SystemService service) {
  69. // Register it.
  70. mServices.add(service);
  71. // Start it.
  72. long time = SystemClock.elapsedRealtime();
  73. try {
  74. service.onStart();
  75. } catch (RuntimeException ex) {
  76. throw new RuntimeException("Failed to start service " + service.getClass().getName()
  77. + ": onStart threw an exception", ex);
  78. }
  79. warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
  80. }
  81. }

这个对象里面有一个mServices集合,这个集合主要保存的就是系统服务,可以看到,所有的系统服务都需要继承com.android.server.SystemService,并且通过反射的方式去实例化系统服务对象,最后会调用系统服务的onStart()方法,关于实例化的系统服务对象,可以通过过滤SystemServiceManager来查看打印的系统服务日志。

启动系统服务

        启动系统服务会分为三类,主要是通过三个方法来依次启动:

  1. startBootstrapServices(); // 启动引导服务
  2. startCoreServices(); // 启动核心服务
  3. startOtherServices(); // 启动其他服务

这里主要是来看下startBootStrapServices(),其他的两个实现方法差不多:

  1. private void startBootstrapServices() {
  2. traceBeginAndSlog("StartWatchdog");
  3. //启动watchdog
  4. //尽早启动watchdog,如果在早起启动时发生死锁,我们可以让system_server崩溃,从而进行详细分析
  5. final Watchdog watchdog = Watchdog.getInstance();
  6. watchdog.start();
  7. traceEnd();
  8. ...
  9. //阻塞等待installd完成启动,以便有机会创建具有适当权限的关键目录,如/data/user。
  10. //我们需要在初始化其他服务之前完成此任务。
  11. traceBeginAndSlog("StartInstaller");
  12. Installer installer = mSystemServiceManager.startService(Installer.class);
  13. traceEnd();
  14. ...
  15. //启动服务ActivityManagerService,并为其设置mSystemServiceManager和installer
  16. traceBeginAndSlog("StartActivityManager");
  17. ActivityTaskManagerService atm = mSystemServiceManager.startService(
  18. ActivityTaskManagerService.Lifecycle.class).getService();
  19. mActivityManagerService = ActivityManagerService.Lifecycle.startService(
  20. mSystemServiceManager, atm);
  21. mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
  22. mActivityManagerService.setInstaller(installer);
  23. mWindowManagerGlobalLock = atm.getGlobalLock();
  24. traceEnd();
  25. //启动服务PowerManagerService
  26. //Power manager需要尽早启动,因为其他服务需要它。
  27. //本机守护进程可能正在监视它的注册,
  28. //因此它必须准备好立即处理传入的绑定器调用(包括能够验证这些调用的权限)。
  29. traceBeginAndSlog("StartPowerManager");
  30. mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
  31. traceEnd();
  32. ...
  33. //初始化power management
  34. traceBeginAndSlog("InitPowerManagement");
  35. mActivityManagerService.initPowerManagement();
  36. traceEnd();
  37. //启动recovery system,以防需要重新启动
  38. traceBeginAndSlog("StartRecoverySystemService");
  39. mSystemServiceManager.startService(RecoverySystemService.class);
  40. traceEnd();
  41. ...
  42. //启动服务LightsService
  43. //管理led和显示背光,所以我们需要它来打开显示
  44. traceBeginAndSlog("StartLightsService");
  45. mSystemServiceManager.startService(LightsService.class);
  46. traceEnd();
  47. ...
  48. //启动服务DisplayManagerService
  49. //显示管理器需要在包管理器之前提供显示指标
  50. traceBeginAndSlog("StartDisplayManager");
  51. mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
  52. traceEnd();
  53. //在初始化package manager之前,需要默认的显示.
  54. traceBeginAndSlog("WaitForDisplay");
  55. mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
  56. traceEnd();
  57. //当设备正在加密时,仅运行核心
  58. String cryptState = VoldProperties.decrypt().orElse("");
  59. if (ENCRYPTING_STATE.equals(cryptState)) {
  60. Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
  61. mOnlyCore = true;
  62. } else if (ENCRYPTED_STATE.equals(cryptState)) {
  63. Slog.w(TAG, "Device encrypted - only parsing core apps");
  64. mOnlyCore = true;
  65. }
  66. ...
  67. //启动服务PackageManagerService
  68. traceBeginAndSlog("StartPackageManagerService");
  69. try {
  70. Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
  71. mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
  72. mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
  73. } finally {
  74. Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
  75. }
  76. ...
  77. //启动服务UserManagerService,新建目录/data/user/
  78. traceBeginAndSlog("StartUserManagerService");
  79. mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
  80. traceEnd();
  81. // Set up the Application instance for the system process and get started.
  82. //为系统进程设置应用程序实例并开始。
  83. //设置AMS
  84. traceBeginAndSlog("SetSystemProcess");
  85. mActivityManagerService.setSystemProcess();
  86. traceEnd();
  87. //使用一个ActivityManager实例完成watchdog设置并监听重启,
  88. //只有在ActivityManagerService作为一个系统进程正确启动后才能这样做
  89. traceBeginAndSlog("InitWatchdog");
  90. watchdog.init(mSystemContext, mActivityManagerService);
  91. traceEnd();
  92. //传感器服务需要访问包管理器服务、app ops服务和权限服务,
  93. //因此我们在它们之后启动它。
  94. //在单独的线程中启动传感器服务。在使用它之前应该检查完成情况。
  95. mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
  96. TimingsTraceLog traceLog = new TimingsTraceLog(
  97. SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
  98. traceLog.traceBegin(START_SENSOR_SERVICE);
  99. startSensorService(); //启动传感器服务
  100. traceLog.traceEnd();
  101. }, START_SENSOR_SERVICE);
  102. }

从这里可以看出,服务的创建基本都是通过SystemServiceManager的startService()进行创建的,PackageManagerService例外,它是直接调用它的main()方法。关于具体服务的创建,后面讲具体服务的时候说了。

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

闽ICP备14008679号