当前位置:   article > 正文

system_server进程创建流程_systemserver创建过程

systemserver创建过程

system_server 进程是 Zygote 进程 fork 出的第一个进程,它负责管理和启动整个 Framework 层,下面附上android系统启动流程图:

记得上一篇Zygote进程创建里面提到过,forckSystemServer创建system_server进程。

/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java 中代码如下:

下面是forkSystemServer 里面的代码: 

 Zygote.forkSystemServer 返回的是一个int型的pid,如果pid不等于0,代表的是在父进程中执行,即

Zygote进程,如果pid等于0,代表在子进程中执行。

 最终执行handleSystemServerProcess,是在system_server进程中执行。

接下来看handleSystemServerProcess方法

  1. /**
  2. 499 * Finish remaining work for the newly forked system server process.
  3. 500 */
  4. 501 private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
  5. 502 // set umask to 0077 so new files and directories will default to owner-only permissions.
  6. 503 Os.umask(S_IRWXG | S_IRWXO);
  7. 504
  8. 505 if (parsedArgs.mNiceName != null) {
  9. 506 Process.setArgV0(parsedArgs.mNiceName);
  10. 507 }
  11. 508
  12. 509 final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
  13. 510 if (systemServerClasspath != null) {
  14. 511 performSystemServerDexOpt(systemServerClasspath);
  15. 512 // Capturing profiles is only supported for debug or eng builds since selinux normally
  16. 513 // prevents it.
  17. 514 if (shouldProfileSystemServer() && (Build.IS_USERDEBUG || Build.IS_ENG)) {
  18. 515 try {
  19. 516 Log.d(TAG, "Preparing system server profile");
  20. 517 prepareSystemServerProfile(systemServerClasspath);
  21. 518 } catch (Exception e) {
  22. 519 Log.wtf(TAG, "Failed to set up system server profile", e);
  23. 520 }
  24. 521 }
  25. 522 }
  26. 523
  27. 524 if (parsedArgs.mInvokeWith != null) {
  28. 525 String[] args = parsedArgs.mRemainingArgs;
  29. 526 // If we have a non-null system server class path, we'll have to duplicate the
  30. 527 // existing arguments and append the classpath to it. ART will handle the classpath
  31. 528 // correctly when we exec a new process.
  32. 529 if (systemServerClasspath != null) {
  33. 530 String[] amendedArgs = new String[args.length + 2];
  34. 531 amendedArgs[0] = "-cp";
  35. 532 amendedArgs[1] = systemServerClasspath;
  36. 533 System.arraycopy(args, 0, amendedArgs, 2, args.length);
  37. 534 args = amendedArgs;
  38. 535 }
  39. 536
  40. 537 WrapperInit.execApplication(parsedArgs.mInvokeWith,
  41. 538 parsedArgs.mNiceName, parsedArgs.mTargetSdkVersion,
  42. 539 VMRuntime.getCurrentInstructionSet(), null, args);
  43. 540
  44. 541 throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
  45. 542 } else {
  46. 543 ClassLoader cl = null;
  47. 544 if (systemServerClasspath != null) {
  48. 545 cl = createPathClassLoader(systemServerClasspath, parsedArgs.mTargetSdkVersion);
  49. 546
  50. 547 Thread.currentThread().setContextClassLoader(cl);
  51. 548 }
  52. 549
  53. 550 /*
  54. 551 * Pass the remaining arguments to SystemServer.
  55. 552 */
  56. 553 return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
  57. 554 parsedArgs.mDisabledCompatChanges,
  58. 555 parsedArgs.mRemainingArgs, cl);
  59. 556 }
  60. 557
  61. 558 /* should never reach here */
  62. 559 }

 最终执行到ZygoteInit.zygoteInit方法,点进去看一下

  1. /**
  2. 978 * The main function called when started through the zygote process. This could be unified with
  3. 979 * main(), if the native code in nativeFinishInit() were rationalized with Zygote startup.<p>
  4. 980 *
  5. 981 * Current recognized args:
  6. 982 * <ul>
  7. 983 * <li> <code> [--] &lt;start class name&gt; &lt;args&gt;
  8. 984 * </ul>
  9. 985 *
  10. 986 * @param targetSdkVersion target SDK version
  11. 987 * @param disabledCompatChanges set of disabled compat changes for the process (all others
  12. 988 * are enabled)
  13. 989 * @param argv arg strings
  14. 990 */
  15. 991 public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
  16. 992 String[] argv, ClassLoader classLoader) {
  17. 993 if (RuntimeInit.DEBUG) {
  18. 994 Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
  19. 995 }
  20. 996
  21. 997 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
  22. 998 RuntimeInit.redirectLogStreams();
  23. 999
  24. 1000 RuntimeInit.commonInit();
  25. 1001 ZygoteInit.nativeZygoteInit();
  26. 1002 return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
  27. 1003 classLoader);
  28. 1004 }

再看看RuntimeInit.applicationInit方法

  1. protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
  2. 405 String[] argv, ClassLoader classLoader) {
  3. 406 // If the application calls System.exit(), terminate the process
  4. 407 // immediately without running any shutdown hooks. It is not possible to
  5. 408 // shutdown an Android application gracefully. Among other things, the
  6. 409 // Android runtime shutdown hooks close the Binder driver, which can cause
  7. 410 // leftover running threads to crash before the process actually exits.
  8. 411 nativeSetExitWithoutCleanup(true);
  9. 412
  10. 413 VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
  11. 414 VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);
  12. 415
  13. 416 final Arguments args = new Arguments(argv);
  14. 417
  15. 418 // The end of of the RuntimeInit event (see #zygoteInit).
  16. 419 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  17. 420
  18. 421 // Remaining arguments are passed to the start class's static main
  19. 422 return findStaticMain(args.startClass, args.startArgs, classLoader);
  20. 423 }

 最终执行的是findStaticMain方法

  1. /**
  2. 337 * Invokes a static "main(argv[]) method on class "className".
  3. 338 * Converts various failing exceptions into RuntimeExceptions, with
  4. 339 * the assumption that they will then cause the VM instance to exit.
  5. 340 *
  6. 341 * @param className Fully-qualified class name
  7. 342 * @param argv Argument vector for main()
  8. 343 * @param classLoader the classLoader to load {@className} with
  9. 344 */
  10. 345 protected static Runnable findStaticMain(String className, String[] argv,
  11. 346 ClassLoader classLoader) {
  12. 347 Class<?> cl;
  13. 348
  14. 349 try {
  15. 350 cl = Class.forName(className, true, classLoader);
  16. 351 } catch (ClassNotFoundException ex) {
  17. 352 throw new RuntimeException(
  18. 353 "Missing class when invoking static main " + className,
  19. 354 ex);
  20. 355 }
  21. 356
  22. 357 Method m;
  23. 358 try {
  24. 359 m = cl.getMethod("main", new Class[] { String[].class });
  25. 360 } catch (NoSuchMethodException ex) {
  26. 361 throw new RuntimeException(
  27. 362 "Missing static main on " + className, ex);
  28. 363 } catch (SecurityException ex) {
  29. 364 throw new RuntimeException(
  30. 365 "Problem getting static main on " + className, ex);
  31. 366 }
  32. 367
  33. 368 int modifiers = m.getModifiers();
  34. 369 if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
  35. 370 throw new RuntimeException(
  36. 371 "Main method is not public and static on " + className);
  37. 372 }
  38. 373
  39. 374 /*
  40. 375 * This throw gets caught in ZygoteInit.main(), which responds
  41. 376 * by invoking the exception's run() method. This arrangement
  42. 377 * clears up all the stack frames that were required in setting
  43. 378 * up the process.
  44. 379 */
  45. 380 return new MethodAndArgsCaller(m, argv);
  46. 381 }

 再看看 MethodAndArgsCaller

  1. /**
  2. 575 * Helper class which holds a method and arguments and can call them. This is used as part of
  3. 576 * a trampoline to get rid of the initial process setup stack frames.
  4. 577 */
  5. 578 static class MethodAndArgsCaller implements Runnable {
  6. 579 /** method to call */
  7. 580 private final Method mMethod;
  8. 581
  9. 582 /** argument array */
  10. 583 private final String[] mArgs;
  11. 584
  12. 585 public MethodAndArgsCaller(Method method, String[] args) {
  13. 586 mMethod = method;
  14. 587 mArgs = args;
  15. 588 }
  16. 589
  17. 590 public void run() {
  18. 591 try {
  19. 592 mMethod.invoke(null, new Object[] { mArgs });
  20. 593 } catch (IllegalAccessException ex) {
  21. 594 throw new RuntimeException(ex);
  22. 595 } catch (InvocationTargetException ex) {
  23. 596 Throwable cause = ex.getCause();
  24. 597 if (cause instanceof RuntimeException) {
  25. 598 throw (RuntimeException) cause;
  26. 599 } else if (cause instanceof Error) {
  27. 600 throw (Error) cause;
  28. 601 }
  29. 602 throw new RuntimeException(ex);
  30. 603 }
  31. 604 }
  32. 605 }
  33. 606 }

这样一看就知道通过反射来调用方法的

最后回过头来看下顶部的代码图片

返回的Runnable对象,执行run, 执行system_server main 方法,然后return了。

接下来我们看SystemServer main 方法

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

run代码中大致分为11个步骤:

1.设定时间

  1. //
  2. 450 // Default the timezone property to GMT if not set.
  3. 451 //
  4. 452 String timezoneProperty = SystemProperties.get("persist.sys.timezone");
  5. 453 if (timezoneProperty == null || timezoneProperty.isEmpty()) {
  6. 454 Slog.w(TAG, "Timezone not set; setting to GMT.");
  7. 455 SystemProperties.set("persist.sys.timezone", "GMT");
  8. 456 }
  9. 457

2.设定语言

  1. // If the system has "persist.sys.language" and friends set, replace them with
  2. 459 // "persist.sys.locale". Note that the default locale at this point is calculated
  3. 460 // using the "-Duser.locale" command line flag. That flag is usually populated by
  4. 461 // AndroidRuntime using the same set of system properties, but only the system_server
  5. 462 // and system apps are allowed to set them.
  6. 463 //
  7. 464 // NOTE: Most changes made here will need an equivalent change to
  8. 465 // core/jni/AndroidRuntime.cpp
  9. 466 if (!SystemProperties.get("persist.sys.language").isEmpty()) {
  10. 467 final String languageTag = Locale.getDefault().toLanguageTag();
  11. 468
  12. 469 SystemProperties.set("persist.sys.locale", languageTag);
  13. 470 SystemProperties.set("persist.sys.language", "");
  14. 471 SystemProperties.set("persist.sys.country", "");
  15. 472 SystemProperties.set("persist.sys.localevar", "");
  16. 473 }
  17. 474

3.虚拟机库文件路径

  1. // In case the runtime switched since last boot (such as when
  2. 498 // the old runtime was removed in an OTA), set the system
  3. 499 // property so that it is in sync. We can't do this in
  4. 500 // libnativehelper's JniInvocation::Init code where we already
  5. 501 // had to fallback to a different runtime because it is
  6. 502 // running as root and we need to be the system user to set
  7. 503 // the property. http://b/11463182
  8. 504 SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());

4.清除内存使用上限

  1. // Mmmmmm... more memory!
  2. 507 VMRuntime.getRuntime().clearGrowthLimit();

5.设定指纹使用

  1. // Some devices rely on runtime fingerprint generation, so make sure
  2. 510 // we've defined it before booting further.
  3. 511 Build.ensureFingerprintProperty();

6.设定环境变量访问用户条件

  1. // Within the system server, it is an error to access Environment paths without
  2. 514 // explicitly specifying a user.
  3. 515 Environment.setUserRequired(true);

7.设定binder服务永远运行在前台

  1. // Ensure binder calls into the system always run at foreground priority.
  2. 525 BinderInternal.disableBackgroundScheduling(true);

8.设定线程池最大线程数

  1. 527 // Increase the number of binder threads in system_server
  2. 528 BinderInternal.setMaxThreads(sMaxBinderThreads);

9.启动各种服务

  1. // Start services.
  2. 594 try {
  3. 595 t.traceBegin("StartServices");
  4. 596 startBootstrapServices(t);
  5. 597 startCoreServices(t);
  6. 598 startOtherServices(t);
  7. 599 } catch (Throwable ex) {
  8. 600 Slog.e("System", "******************************************");
  9. 601 Slog.e("System", "************ Failure starting system services", ex);
  10. 602 throw ex;
  11. 603 } finally {
  12. 604 t.traceEnd(); // StartServices
  13. 605 }
  14. 606
  15. 607 StrictMode.initVmDefaults(null);
  16. 608
  17. 609 if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
  18. 610 final long uptimeMillis = SystemClock.elapsedRealtime();
  19. 611 FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
  20. 612 FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SYSTEM_SERVER_READY,
  21. 613 uptimeMillis);
  22. 614 final long maxUptimeMillis = 60 * 1000;
  23. 615 if (uptimeMillis > maxUptimeMillis) {
  24. 616 Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
  25. 617 "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
  26. 618 }
  27. 619 }
  28. 620
  29. 621 // Diagnostic to ensure that the system is in a base healthy state. Done here as a common
  30. 622 // non-zygote process.
  31. 623 if (!VMRuntime.hasBootImageSpaces()) {
  32. 624 Slog.wtf(TAG, "Runtime is not running with a boot image!");
  33. 625 }
  34. 626

10.服务开启循环

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

启动系统上下文

  1. // Initialize the system context.
  2. 556 createSystemContext();
  1. private void createSystemContext() {
  2. 696 ActivityThread activityThread = ActivityThread.systemMain();
  3. 697 mSystemContext = activityThread.getSystemContext();
  4. 698 mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
  5. 699
  6. 700 final Context systemUiContext = activityThread.getSystemUiContext();
  7. 701 systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
  8. 702 }

创建SystemServiceManager

  1. 561 // Create the system service manager.
  2. 562 mSystemServiceManager = new SystemServiceManager(mSystemContext);
  3. 563 mSystemServiceManager.setStartInfo(mRuntimeRestart,
  4. 564 mRuntimeStartElapsedTime, mRuntimeStartUptime);
  5. 565 LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
  6. 566 // Prepare the thread pool for init tasks that can be parallelized
  7. 567 SystemServerInitThreadPool.start();

 

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

闽ICP备14008679号