Zygote是所有Android中所有应用的鼻祖。Zygote fork的第一个进程就是SystemServer,其在手机中的进程名为 system_server。Zygote和SystemServer这两个进程任何一个进程的死亡,都会导致JAVA世界的崩塌。SystemServer 进程承载着整个framework的核心服务,例如创建 ActivityManagerService、PowerManagerService、DisplayManagerService、PackageManagerService、WindowManagerService、LauncherAppsService等80多个核心系统服务。这些服务以不同的线程方式存在于system_server这个进程中。下面来看下SystemServer进程创建的流程。
//frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
819 public static void main(String argv[]) {
820 ZygoteServer zygoteServer = null
........
902 if (startSystemServer) {
//fork system server
903 Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
904
905 // {@code r == null} in the parent (zygote) process, and {@code r != null} in the
906 // child (system_server) process.
907 if (r != null) {
//启动SystemServer.java的main函数
908 r.run();
909 return;
910 }
911 }
........
724 private static Runnable forkSystemServer(String abiList, String socketName,
725 ZygoteServer zygoteServer) {
.............
//准备参数,为fork system_server准备,pid=1000,gid=1000,进程名nick-name=system_server
753 String args[] = {
754 "--setuid=1000",
755 "--setgid=1000",
756 "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,"
757 + "1024,1032,1065,3001,3002,3003,3006,3007,3009,3010",
758 "--capabilities=" + capabilities + "," + capabilities,
759 "--nice-name=system_server",
760 "--runtime-args",
761 "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
762 "com.android.server.SystemServer",
763 };
764 ZygoteArguments parsedArgs = null;
765
766 int pid;
767
768 try {
//按照ZygoteArguments要求进行封装
769 parsedArgs = new ZygoteArguments(args);
770 Zygote.applyDebuggerSystemProperty(parsedArgs);
771 Zygote.applyInvokeWithSystemProperty(parsedArgs);
772
773 boolean profileSystemServer = SystemProperties.getBoolean(
774 "dalvik.vm.profilesystemserver", false);
775 if (profileSystemServer) {
776 parsedArgs.mRuntimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
777 }
778
779 /* Request to fork the system server process */
//fork SystemServer进程,详情见part1
780 pid = Zygote.forkSystemServer(
781 parsedArgs.mUid, parsedArgs.mGid,
782 parsedArgs.mGids,
783 parsedArgs.mRuntimeFlags,
784 null,
785 parsedArgs.mPermittedCapabilities,
786 parsedArgs.mEffectiveCapabilities);
787 } catch (IllegalArgumentException ex) {
788 throw new RuntimeException(ex);
789 }
790
791 /* For child process */
//fork函数会返回2次,pid=0意味着子进程system_server创建成功
792 if (pid == 0) {
//如果机器支持32位应用,需要等待32位的zygote连接成功
793 if (hasSecondZygote(abiList)) {
794 waitForSecondaryZygote(socketName);
795 }
796
//由于fork时会拷贝socket,因此,在fork出system_server进程后,需要关闭Zygote原有的socket
797 zygoteServer.closeServerSocket();
//SystemServer正式与Zygote分开,在自己的进程中继续运行。详情见part2
798 return handleSystemServerProcess(parsedArgs);
799 }
800
801 return null;
802 }
forkSystemServer这个函数可以分为2部分来看,第一部分fork SystemServer进程,第二部分就是SystemServer进程创建成功之后,正式与Zygote分开,代码开始运行在SystemServer中。下面分开来看下这两部分。
//frameworks/base/core/java/com/android/internal/os/Zygote.java
335 public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
336 int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
337 ZygoteHooks.preFork();
338 // Resets nice priority for zygote process.
339 resetNicePriority();
//JNI调用,最终调用native方法com_android_internal_os_Zygote_nativeForkSystemServer
340 int pid = nativeForkSystemServer(
341 uid, gid, gids, runtimeFlags, rlimits,
342 permittedCapabilities, effectiveCapabilities);
343 // Enable tracing as soon as we enter the system_server.
344 if (pid == 0) {
345 Trace.setTracingEnabled(true, runtimeFlags);
346 }
347 ZygoteHooks.postForkCommon();
348 return pid;
349 }
//JNI注册时的映射关系
static const JNINativeMethod gMethods[] = {
{ "nativeForkSystemServer", "(II[II[[IJJ)I",
(void *) com_android_internal_os_Zygote_nativeForkSystemServer },
}
所以最终执行的是com_android_internal_os_Zygote_nativeForkSystemServer。
//frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
1386 static jint com_android_internal_os_Zygote_nativeForkSystemServer(
1387 JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
1388 jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
1389 jlong effective_capabilities) {
1390 std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
1391 fds_to_ignore(fds_to_close);
1392
1393 fds_to_close.push_back(gUsapPoolSocketFD);
1394
1395 if (gUsapPoolEventFD != -1) {
1396 fds_to_close.push_back(gUsapPoolEventFD);
1397 fds_to_ignore.push_back(gUsapPoolEventFD);
1398 }
1399
//从Zygote孵化出一个进程的使用程序
1400 pid_t pid = ForkCommon(env, true,
1401 fds_to_close,
1402 fds_to_ignore);
//pid=0 表示Zygote fork SystemServer成功
1403 if (pid == 0) {
1404 SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
1405 permitted_capabilities, effective_capabilities,
1406 MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
1407 false, nullptr, nullptr);
//进入父进程,即zygote进程
1408 } else if (pid > 0) {
1409 // The zygote process checks whether the child process has died or not.
1410 ALOGI("System server process %d has been created", pid);
1411 gSystemServerPid = pid;
1412 // There is a slight window that the system server process has crashed
1413 // but it went unnoticed because we haven't published its pid yet. So
1414 // we recheck here just to make sure that all is well.
1415 int status;
1416 if (waitpid(pid, &status, WNOHANG) == pid) {//判断子进程是否死掉, 如果死掉重启zygote
1417 ALOGE("System server process %d has died. Restarting Zygote!", pid);
1418 RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
1419 }
1420
904 static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
905 const std::vector<int>& fds_to_close,
906 const std::vector<int>& fds_to_ignore) {
//设置子进程的signal
907 SetSignalHandlers();
908
909 // Curry a failure function.
910 auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
911 nullptr, _1);
912
913 // Temporarily block SIGCHLD during forks. The SIGCHLD handler might
914 // log, which would result in the logging FDs we close being reopened.
915 // This would cause failures because the FDs are not whitelisted.
916 //
917 // Note that the zygote process is single threaded at this point.
//在fork的过程中,临时锁住SIGCHLD
918 BlockSignal(SIGCHLD, fail_fn);
919
920 // Close any logging related FDs before we start evaluating the list of
921 // file descriptors.
922 __android_log_close();
923 stats_log_close();
924
925 // If this is the first fork for this zygote, create the open FD table. If
926 // it isn't, we just need to check whether the list of open files has changed
927 // (and it shouldn't in the normal case).
928 if (gOpenFdTable == nullptr) {
929 gOpenFdTable = FileDescriptorTable::Create(fds_to_ignore, fail_fn);
930 } else {
931 gOpenFdTable->Restat(fds_to_ignore, fail_fn);
932 }
933
934 android_fdsan_error_level fdsan_error_level = android_fdsan_get_error_level();
935
//fork子进程,采用copy on write方式,这里执行一次会返回2次
//pid=0 表示zygote fork SystemServer成功
//pid>0 表示SystemServer 的真正的PID
936 pid_t pid = fork();
937
938 if (pid == 0) {
939 // The child process.
940 PreApplicationInit();
941
942 // Clean up any descriptors which must be closed immediately
943 DetachDescriptors(env, fds_to_close, fail_fn);
944
945 // Invalidate the entries in the USAP table.
946 ClearUsapTable();
947
948 // Re-open all remaining open file descriptors so that they aren't shared
949 // with the zygote across a fork.
950 gOpenFdTable->ReopenOrDetach(fail_fn);
951
952 // Turn fdsan back on.
953 android_fdsan_set_error_level(fdsan_error_level);
954 } else {
955 ALOGD("Forked child process %d", pid);
956 }
957
958 // We blocked SIGCHLD prior to a fork, we unblock it here.
//解锁,fork结束
959 UnblockSignal(SIGCHLD, fail_fn);
960
961 return pid;
962 }
965 static void SpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray gids,
966 jint runtime_flags, jobjectArray rlimits,
967 jlong permitted_capabilities, jlong effective_capabilities,
968 jint mount_external, jstring managed_se_info,
969 jstring managed_nice_name, bool is_system_server,
970 bool is_child_zygote, jstring managed_instruction_set,
971 jstring managed_app_data_dir) {
........
1009 if (!is_system_server && getuid() == 0) {
//对于非system_server子进程,则创建进程组
1010 const int rc = createProcessGroup(uid, getpid());
1011 if (rc == -EROFS) {
1012 ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?");
1013 } else if (rc != 0) {
1014 ALOGE("createProcessGroup(%d, %d) failed: %s", uid, /* pid= */ 0, strerror(-rc));
1015 }
1016 }
1017
1018 SetGids(env, gids, fail_fn);//设置group
1019 SetRLimits(env, rlimits, fail_fn);//设置资源limit
........
//selinux上下文
1095 if (selinux_android_setcontext(uid, is_system_server, se_info_ptr, nice_name_ptr) == -1) {
1096 fail_fn(CREATE_ERROR("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed",
1097 uid, is_system_server, se_info_ptr, nice_name_ptr));
1098 }
1099
1100 // Make it easier to debug audit logs by setting the main thread's name to the
1101 // nice name rather than "app_process".
1102 if (nice_name.has_value()) {
//设置线程名为system_server
1103 SetThreadName(nice_name.value());
1104 } else if (is_system_server) {
1105 SetThreadName("system_server");
1106 }
1107
1108 // Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
1109 UnsetChldSignalHandler();
1110
1111 if (is_system_server) {
//对应Zygote.java 的callPostForkSystemServerHooks()
1112 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkSystemServerHooks);
1113 if (env->ExceptionCheck()) {
1114 fail_fn("Error calling post fork system server hooks.");
1115 }
1116
1117 // Prefetch the classloader for the system server. This is done early to
1118 // allow a tie-down of the proper system server selinux domain.
//对应ZygoteInit.java 的 createSystemServerClassLoader()
//预取系统服务器的类加载器。这样做是为了尽早地绑定适当的系统服务器selinux域。
1119 env->CallStaticVoidMethod(gZygoteInitClass, gCreateSystemServerClassLoader);
1120 if (env->ExceptionCheck()) {
1121 // Be robust here. The Java code will attempt to create the classloader
1122 // at a later point (but may not have rights to use AoT artifacts).
1123 env->ExceptionClear();
1124 }
1125
1126 // TODO(oth): Remove hardcoded label here (b/117874058).
1127 static const char* kSystemServerLabel = "u:r:system_server:s0";
1128 if (selinux_android_setcon(kSystemServerLabel) != 0) {
1129 fail_fn(CREATE_ERROR("selinux_android_setcon(%s)", kSystemServerLabel));
1130 }
1131 }
1132
//等价于调用zygote.java 的callPostForkChildHooks()
1133 env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
1134 is_system_server, is_child_zygote, managed_instruction_set);
1135
1136 if (env->ExceptionCheck()) {
1137 fail_fn("Error calling post fork hooks.");
1138 }
1139 }
至此第一部分结束,SystemServer进程创建完成后,就会重新启动垃圾回收后台进程。之后回到ZygoteInit中,SystemServer进程就与Zygote进程正式分道扬镳,pid=0为子进程,以后的代码都运行在了SystemServer进程中了。我们回到ZygoteInit继续执行handleSystemProcess出来fork生成的SystemServer进程。
//frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
480 private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
481 // set umask to 0077 so new files and directories will default to owner-only permissions.
482 Os.umask(S_IRWXG | S_IRWXO);
483
//设置进程名为"system_server"
484 if (parsedArgs.mNiceName != null) {
485 Process.setArgV0(parsedArgs.mNiceName);
486 }
487 //获取systemServerClasspath
//systemServerClasspath = /system/framework/services.jar:/system/framework/ethernet-service.jar:/system/framework/wifi-service.jar
//Android提供了一个专门验证与优化dex文件的工具dexopt,之后会
//将这三个jar从路径中获取出来,判断是否要进行dexopt优化.
488 final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
489 if (systemServerClasspath != null) {
//执行dex优化操作
490 if (performSystemServerDexOpt(systemServerClasspath)) {
491 // Throw away the cached classloader. If we compiled here, the classloader would
492 // not have had AoT-ed artifacts.
493 // Note: This only works in a very special environment where selinux enforcement is
494 // disabled, e.g., Mac builds.
495 sCachedSystemServerClassLoader = null;
496 }
497 // Capturing profiles is only supported for debug or eng builds since selinux normally
498 // prevents it.
499 boolean profileSystemServer = SystemProperties.getBoolean(
500 "dalvik.vm.profilesystemserver", false);
501 if (profileSystemServer && (Build.IS_USERDEBUG || Build.IS_ENG)) {
502 try {
503 prepareSystemServerProfile(systemServerClasspath);
504 } catch (Exception e) {
505 Log.wtf(TAG, "Failed to set up system server profile", e);
506 }
507 }
508 }
509
510 if (parsedArgs.mInvokeWith != null) {
511 String[] args = parsedArgs.mRemainingArgs;
512 // If we have a non-null system server class path, we'll have to duplicate the
513 // existing arguments and append the classpath to it. ART will handle the classpath
514 // correctly when we exec a new process.
515 if (systemServerClasspath != null) {
516 String[] amendedArgs = new String[args.length + 2];
517 amendedArgs[0] = "-cp";
518 amendedArgs[1] = systemServerClasspath;
519 System.arraycopy(args, 0, amendedArgs, 2, args.length);
520 args = amendedArgs;
521 }
522
523 WrapperInit.execApplication(parsedArgs.mInvokeWith,
524 parsedArgs.mNiceName, parsedArgs.mTargetSdkVersion,
525 VMRuntime.getCurrentInstructionSet(), null, args);
526
527 throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
528 } else {
//创建classLoader, 最后,将启动SystemServer的参数解析完剩余的
//参数“com.android.server.SystemServer”保存在remainingArgs中,
529 createSystemServerClassLoader();
530 ClassLoader cl = sCachedSystemServerClassLoader;
531 if (cl != null) {
532 Thread.currentThread().setContextClassLoader(cl);
533 }
534
535 /*
536 * Pass the remaining arguments to SystemServer.
537 */
538 return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
539 parsedArgs.mRemainingArgs, cl);
540 }
541
542 /* should never reach here */
543 }
544
972 public static final Runnable zygoteInit(int targetSdkVersion, String[] argv,
973 ClassLoader classLoader) {
974 if (RuntimeInit.DEBUG) {
975 Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
976 }
977
978 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
979 RuntimeInit.redirectLogStreams();//重定向log输出
980
981 RuntimeInit.commonInit();//通用的一些初始化
982 ZygoteInit.nativeZygoteInit();// zygote初始化
//应用初始化
983 return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
984
//JNI调用com_android_internal_os_ZygoteInit_nativeZygoteInit
//frameworks/base/core/jni/AndroidRuntime.cpp
295 int register_com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env)
296 {
297 const JNINativeMethod methods[] = {
298 { "nativeZygoteInit", "()V",
299 (void*) com_android_internal_os_ZygoteInit_nativeZygoteInit },
300 };
301 return jniRegisterNativeMethods(env, "com/android/internal/os/ZygoteInit",
302 methods, NELEM(methods));
303 }
268 static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
269 {
270 gCurRuntime->onZygoteInit();
271 }
//frameworks/base/cmds/app_process/app_main.cpp
92 virtual void onZygoteInit()
93 {
94 sp<ProcessState> proc = ProcessState::self();
95 ALOGV("App process: starting thread pool.\n");
96 proc->startThreadPool();//启动binder线程池
97 }
//frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
343 protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
344 ClassLoader classLoader) {
345 // If the application calls System.exit(), terminate the process
346 // immediately without running any shutdown hooks. It is not possible to
347 // shutdown an Android application gracefully. Among other things, the
348 // Android runtime shutdown hooks close the Binder driver, which can cause
349 // leftover running threads to crash before the process actually exits.
350 nativeSetExitWithoutCleanup(true);
351
352 // We want to be fairly aggressive about heap utilization, to avoid
353 // holding on to a lot of memory that isn't needed.
//设置虚拟机的内存利用率参数值为0.75
354 VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
355 VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
356
357 final Arguments args = new Arguments(argv);
358
359 // The end of of the RuntimeInit event (see #zygoteInit).
360 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
361
362 // Remaining arguments are passed to the start class's static main
//经过applicationInit中的Arguments构造方法,args.startClass的值就是com.android.server.SystemServer。
363 return findStaticMain(args.startClass, args.startArgs, classLoader);
364 }
284 protected static Runnable findStaticMain(String className, String[] argv,
285 ClassLoader classLoader) {
286 Class<?> cl;
287
288 try {
//拿到com.android.server.SystemServer 的类对象
289 cl = Class.forName(className, true, classLoader);
290 } catch (ClassNotFoundException ex) {
291 throw new RuntimeException(
292 "Missing class when invoking static main " + className,
293 ex);
294 }
295
296 Method m;
297 try {
//得到SystemServer的main()方法
298 m = cl.getMethod("main", new Class[] { String[].class });
299 } catch (NoSuchMethodException ex) {
300 throw new RuntimeException(
301 "Missing static main on " + className, ex);
302 } catch (SecurityException ex) {
303 throw new RuntimeException(
304 "Problem getting static main on " + className, ex);
305 }
306
307 int modifiers = m.getModifiers();
308 if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
309 throw new RuntimeException(
310 "Main method is not public and static on " + className);
311 }
312
313 /*
314 * This throw gets caught in ZygoteInit.main(), which responds
315 * by invoking the exception's run() method. This arrangement
316 * clears up all the stack frames that were required in setting
317 * up the process.
318 */
//把MethodAndArgsCaller的对象返回给ZygoteInit.main()。这样做好处是能清空栈帧
//提高栈帧利用率,清除了设置进程所需的所有堆栈帧
319 return new MethodAndArgsCaller(m, argv);
320 }
478 static class MethodAndArgsCaller implements Runnable {
479 /** method to call */
480 private final Method mMethod;
481
482 /** argument array */
483 private final String[] mArgs;
484
485 public MethodAndArgsCaller(Method method, String[] args) {
486 mMethod = method;
487 mArgs = args;
488 }
489
490 public void run() {
491 try {
根据传递过来的参数,可知此处通过反射机制调用的是SystemServer.main()方法
492 mMethod.invoke(null, new Object[] { mArgs });
493 } catch (IllegalAccessException ex) {
494 throw new RuntimeException(ex);
495 } catch (InvocationTargetException ex) {
496 Throwable cause = ex.getCause();
497 if (cause instanceof RuntimeException) {
498 throw (RuntimeException) cause;
499 } else if (cause instanceof Error) {
500 throw (Error) cause;
501 }
502 throw new RuntimeException(ex);
503 }
504 }
505 }
506 }
在ZygoteInit.java中的main方法调用run,就会反射调用SystemServer.main()方法。
//frameworks/base/services/java/com/android/server/SystemServer.java
348 public static void main(String[] args) {
//new 一个SystemServer对象,再调用该对象的run()方法
349 new SystemServer().run();
350 }
370 private void run() {
371 try {
372 traceBeginAndSlog("InitBeforeStartServices");
373
374 // Record the process start information in sys props.
375 SystemProperties.set(SYSPROP_START_COUNT, String.valueOf(mStartCount));
376 SystemProperties.set(SYSPROP_START_ELAPSED, String.valueOf(mRuntimeStartElapsedTime));
377 SystemProperties.set(SYSPROP_START_UPTIME, String.valueOf(mRuntimeStartUptime));
378
379 EventLog.writeEvent(EventLogTags.SYSTEM_SERVER_START,
380 mStartCount, mRuntimeStartUptime, mRuntimeStartElapsedTime);
381
382 // If a device's clock is before 1970 (before 0), a lot of
383 // APIs crash dealing with negative numbers, notably
384 // java.io.File#setLastModified, so instead we fake it and
385 // hope that time from cell towers or NTP fixes it shortly.
//首先判断系统当前时间,为防止一些和时间相关的初始化出错,若当前时间小于1970年1月1日,设置系统当前时间为该时间点。
386 if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
387 Slog.w(TAG, "System clock is before 1970; setting to 1970.");
388 SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
389 }
390
391 //
392 // Default the timezone property to GMT if not set.
393 //
394 String timezoneProperty = SystemProperties.get("persist.sys.timezone");
395 if (timezoneProperty == null || timezoneProperty.isEmpty()) {
396 Slog.w(TAG, "Timezone not set; setting to GMT.");
397 SystemProperties.set("persist.sys.timezone", "GMT");
398 }
399
400 // If the system has "persist.sys.language" and friends set, replace them with
401 // "persist.sys.locale". Note that the default locale at this point is calculated
402 // using the "-Duser.locale" command line flag. That flag is usually populated by
403 // AndroidRuntime using the same set of system properties, but only the system_server
404 // and system apps are allowed to set them.
405 //
406 // NOTE: Most changes made here will need an equivalent change to
407 // core/jni/AndroidRuntime.cpp
//设置系统的语言环境等
408 if (!SystemProperties.get("persist.sys.language").isEmpty()) {
409 final String languageTag = Locale.getDefault().toLanguageTag();
410
411 SystemProperties.set("persist.sys.locale", languageTag);
412 SystemProperties.set("persist.sys.language", "");
413 SystemProperties.set("persist.sys.country", "");
414 SystemProperties.set("persist.sys.localevar", "");
415 }
416
417 // The system server should never make non-oneway calls
418 Binder.setWarnOnBlocking(true);
419 // The system server should always load safe labels
420 PackageItemInfo.forceSafeLabels();
421
422 // Default to FULL within the system server.
423 SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;
424
425 // Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
426 SQLiteCompatibilityWalFlags.init(null);
427
428 // Here we go!
429 Slog.i(TAG, "Entered the Android system server!");
430 int uptimeMillis = (int) SystemClock.elapsedRealtime();
431 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
432 if (!mRuntimeRestart) {
433 MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
434 }
435
436 // In case the runtime switched since last boot (such as when
437 // the old runtime was removed in an OTA), set the system
438 // property so that it is in sync. We can | xq oqi't do this in
439 // libnativehelper's JniInvocation::Init code where we already
440 // had to fallback to a different runtime because it is
441 // running as root and we need to be the system user to set
442 // the property. http://b/11463182
//设置当前虚拟机的运行库路径
443 SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
444
445 // Mmmmmm... more memory!
446 VMRuntime.getRuntime().clearGrowthLimit();
447
448 // The system server has to run all of the time, so it needs to be
449 // as efficient as possible with its memory usage.
//设置虚拟机堆内存
450 VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
451
452 // Some devices rely on runtime fingerprint generation, so make sure
453 // we've defined it before booting further.
454 Build.ensureFingerprintProperty();
455
456 // Within the system server, it is an error to access Environment paths without
457 // explicitly specifying a user.
458 Environment.setUserRequired(true);
459
460 // Within the system server, any incoming Bundles should be defused
461 // to avoid throwing BadParcelableException.
462 BaseBundle.setShouldDefuse(true);
463
464 // Within the system server, when parceling exceptions, include the stack trace
465 Parcel.setStackTraceParceling(true);
466
467 // Ensure binder calls into the system always run at foreground priority.
468 BinderInternal.disableBackgroundScheduling(true);
469
470 // Increase the number of binder threads in system_server
471 BinderInternal.setMaxThreads(sMaxBinderThreads);
472
473 // Prepare the main looper thread (this thread).
474 android.os.Process.setThreadPriority(
475 android.os.Process.THREAD_PRIORITY_FOREGROUND);
476 android.os.Process.setCanSelfBackground(false);
477 Looper.prepareMainLooper();
478 Looper.getMainLooper().setSlowLogThresholdMs(
479 SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
480
481 // Initialize native services.
482 System.loadLibrary("android_servers");
483
484 // Debug builds - allow heap profiling.
485 if (Build.IS_DEBUGGABLE) {
486 initZygoteChildHeapProfiling();
487 }
488
489 // Check whether we failed to shut down last time we tried.
490 // This call may not return.
491 performPendingShutdown();
492
493 // Initialize the system context.
//创建System的context,详情见下
494 createSystemContext();
495
496 // Create the system service manager.
//创建SystemServiceManager,负责服务的启动
497 mSystemServiceManager = new SystemServiceManager(mSystemContext);
498 mSystemServiceManager.setStartInfo(mRuntimeRestart,
499 mRuntimeStartElapsedTime, mRuntimeStartUptime);
500 LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
501 // Prepare the thread pool for init tasks that can be parallelized
502 SystemServerInitThreadPool.get();
503 } finally {
504 traceEnd(); // InitBeforeStartServices
505 }
506
507 // Start services.
508 try {
//开始启动服务
509 traceBeginAndSlog("StartServices");
510 startBootstrapServices();
511 startCoreServices();
512 startOtherServices();
513 SystemServerInitThreadPool.shutdown();
514 } catch (Throwable ex) {
515 Slog.e("System", "******************************************");
516 Slog.e("System", "************ Failure starting system services", ex);
517 throw ex;
518 } finally {
519 traceEnd();
520 }
521
522 StrictMode.initVmDefaults(null);
523
524 if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
525 int uptimeMillis = (int) SystemClock.elapsedRealtime();
526 MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
527 final int MAX_UPTIME_MILLIS = 60 * 1000;
528 if (uptimeMillis > MAX_UPTIME_MILLIS) {
529 Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
530 "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
531 }
532 }
533
534 // Diagnostic to ensure that the system is in a base healthy state. Done here as a common
535 // non-zygote process.
536 if (!VMRuntime.hasBootImageSpaces()) {
537 Slog.wtf(TAG, "Runtime is not running with a boot image!");
538 }
539
540 // Loop forever.
541 Looper.loop();
542 throw new RuntimeException("Main thread loop unexpectedly exited");
543 }
main里面做的事情大概如下。
检验时间:如果当前时间早于1970年,则设置当前时间为1970年,防止初始化出错。
设置系统的语言环境等
设置当前虚拟机的运行库路径为persist.sys.dalvik.vm.lib.2
设置虚拟机的堆内存,虚拟机堆利用率为0.8
调用prepareMainLooper()初始化当前线程的Looper
加载libandroid_servers.so库
调用createSystemContext()创建System的context
创建大管家SystemServiceManager的对象mSystemServiceManager,负责系统Service的管理
调用startBootstrapServices();startCoreServices();startOtherServices(),创建和运行系统中所有的服务
调用Looper.loop(),开启消息循环;
我们重点关注下创建context,SystemServiceManager和开启服务3个地方。
//frameworks/base/services/java/com/android/server/SystemServer.java
//createSystemContext中创建了2个Context,一个是mSystemContext,另一个是systemUiContext。
608 private void createSystemContext() {
609 ActivityThread activityThread = ActivityThread.systemMain();
610 mSystemContext = activityThread.getSystemContext();
611 mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
612
613 final Context systemUiContext = activityThread.getSystemUiContext();
614 systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
615 }
SystemServer进程中运行的Service很多,有八十多种,每一个服务都要经历创建、启动。所以google搞了一个SystemServiceManager(系统服务管理者)。被SystemServiceManager管理的服务都必须继承com.android.server.SystemService或者该服务中的Lifecycle要继承com.android.server.SystemService。要启动某项服务,只要传相应的字节码其内部就会自动帮忙创建并且启动。
创建好了SystemServiceManager,就开始启动服务了。系统服务大概分成三类,引导服务,核心服务,其他服务,分别对于三个方法,startBootstrapServices、startCoreServices、startOtherServices。
启动引导服务,有ActivityManagerService, PowerManagerService, LightsService, DisplayManagerService, PackageManagerService, UserManagerService, sensor服务.
/frameworks/base/services/java/com/android/server/SystemServer.java
491 private void startBootstrapServices() {
.......
501 traceBeginAndSlog("StartInstaller");
502 Installer installer = mSystemServiceManager.startService(Installer.class);
503 traceEnd();
504
505 // In some cases after launching an app we need to access device identifiers,
506 // therefore register the device identifier policy before the activity manager.
507 traceBeginAndSlog("DeviceIdentifiersPolicyService");
508 mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
509 traceEnd();
510
511 // Activity manager runs the show.
512 traceBeginAndSlog("StartActivityManager");
513 mActivityManagerService = mSystemServiceManager.startService(
514 ActivityManagerService.Lifecycle.class).getService();
515 mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
516 mActivityManagerService.setInstaller(installer);
517 traceEnd();
.......
523 traceBeginAndSlog("StartPowerManager");
524 mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
525 traceEnd();
.......
545 // Manages LEDs and display backlight so we need it to bring up the display.
546 traceBeginAndSlog("StartLightsService");
547 mSystemServiceManager.startService(LightsService.class);
548 traceEnd();
549
550 // Display manager is needed to provide display metrics before package manager
551 // starts up.
552 traceBeginAndSlog("StartDisplayManager");
553 mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
554 traceEnd();
555
556 // We need the default display before we can initialize the package manager.
557 traceBeginAndSlog("WaitForDisplay");
558 mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
559 traceEnd();
560
.......
577 mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
578 mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
579 mFirstBoot = mPackageManagerService.isFirstBoot();
580 mPackageManager = mSystemContext.getPackageManager();
.......
604 traceBeginAndSlog("StartUserManagerService");
605 mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
606 traceEnd();
607
608 // Initialize attribute cache used to cache resources from packages.
609 traceBeginAndSlog("InitAttributerCache");
610 AttributeCache.init(mSystemContext);
611 traceEnd();
612
613 // Set up the Application instance for the system process and get started.
614 traceBeginAndSlog("SetSystemProcess");
615 mActivityManagerService.setSystemProcess();
616 traceEnd();
617
618 // DisplayManagerService needs to setup android.display scheduling related policies
619 // since setSystemProcess() would have overridden policies due to setProcessGroup
620 mDisplayManagerService.setupSchedulerPolicies();
621
622 // Manages Overlay packages
623 traceBeginAndSlog("StartOverlayManagerService");
624 mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));
.......
638 }
启动核心服务BatteryService,UsageStatsService,WebViewUpdateService、BugreportManagerService、GpuService等
/frameworks/base/services/java/com/android/server/SystemServer.java
641 * Starts some essential services that are not tangled up in the bootstrap process.
642 */
643 private void startCoreServices() {
644 // Records errors and logs, for example wtf()
645 traceBeginAndSlog("StartDropBoxManager");
646 mSystemServiceManager.startService(DropBoxManagerService.class);
647 traceEnd();
648
649 traceBeginAndSlog("StartBatteryService");
650 // Tracks the battery level. Requires LightService.
651 mSystemServiceManager.startService(BatteryService.class);
652 traceEnd();
653
654 // Tracks application usage stats.
655 traceBeginAndSlog("StartUsageService");
656 mSystemServiceManager.startService(UsageStatsService.class);
657 mActivityManagerService.setUsageStatsManager(
658 LocalServices.getService(UsageStatsManagerInternal.class));
659 traceEnd();
660
661 // Tracks whether the updatable WebView is in a ready state and watches for update installs.
662 traceBeginAndSlog("StartWebViewUpdateService");
663 mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
664 traceEnd();
665 }
启动其他服务,其他服务为一些非紧要和一些不需要立即启动的服务。
/**
668 * Starts a miscellaneous grab bag of stuff that has yet to be refactored
669 * and organized.
670 */
671 private void startOtherServices() {
......
722 try {
......
778 // The AccountManager must come before the ContentService
779 traceBeginAndSlog("StartAccountManagerService");
780 mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
781 traceEnd();
782
783 traceBeginAndSlog("StartContentService");
784 mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);
785 traceEnd();
786
787 traceBeginAndSlog("InstallSystemProviders");
788 mActivityManagerService.installSystemProviders();
789 traceEnd();
790
791 traceBeginAndSlog("StartVibratorService");
792 vibrator = new VibratorService(context);
793 ServiceManager.addService("vibrator", vibrator);
794 traceEnd();
......
802
803 traceBeginAndSlog("StartAlarmManagerService");
804 mSystemServiceManager.startService(AlarmManagerService.class);
805 traceEnd();
806
807 traceBeginAndSlog("InitWatchdog");
808 final Watchdog watchdog = Watchdog.getInstance();
809 watchdog.init(context, mActivityManagerService);
810 traceEnd();
811
812 traceBeginAndSlog("StartInputManagerService");
813 inputManager = new InputManagerService(context);
814 traceEnd();
815
816 traceBeginAndSlog("StartWindowManagerService");
817 // WMS needs sensor service ready
818 ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
819 mSensorServiceStart = null;
820 wm = WindowManagerService.main(context, inputManager,
821 mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
822 !mFirstBoot, mOnlyCore, new PhoneWindowManager());
823 ServiceManager.addService(Context.WINDOW_SERVICE, wm);
824 ServiceManager.addService(Context.INPUT_SERVICE, inputManager);
825 traceEnd();
826
827 // Start receiving calls from HIDL services. Start in in a separate thread
828 // because it need to connect to SensorManager. This have to start
829 // after START_SENSOR_SERVICE is done.
830 SystemServerInitThreadPool.get().submit(() -> {
831 traceBeginAndSlog(START_HIDL_SERVICES);
832 startHidlServices();
833 traceEnd();
834 }, START_HIDL_SERVICES);
835
......
1561 // Needed by DevicePolicyManager for initialization
1562 traceBeginAndSlog("StartBootPhaseLockSettingsReady");
1563 mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
1564 traceEnd();
1565
1566 traceBeginAndSlog("StartBootPhaseSystemServicesReady");
1567 mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
1568 traceEnd();
1569
......
}
这一步骤启动了很多的服务,为了出了问题可以快速定位,启动过程中加入了startBootPhase这个方法,通过这个方法将Sytem启动划分成几个阶段,不同的阶段干了不同的事情,前面一个阶段的事情完成了才可以进入下一个阶段。这样在系统启动出现问题的时候也方便我们进行定位处理。
//frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
143 public void startBootPhase(final int phase) {
144 if (phase <= mCurrentPhase) {
145 throw new IllegalArgumentException("Next phase must be larger than previous");
146 }
147 mCurrentPhase = phase;
148
149 Slog.i(TAG, "Starting phase " + mCurrentPhase);
150 try {
151 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "OnBootPhase " + phase);
152 final int serviceLen = mServices.size();
153 for (int i = 0; i < serviceLen; i++) {
154 final SystemService service = mServices.get(i);
155 long time = SystemClock.elapsedRealtime();
156 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, service.getClass().getName());
157 try {
158 service.onBootPhase(mCurrentPhase);
159 } catch (Exception ex) {
160 throw new RuntimeException("Failed to boot service "
161 + service.getClass().getName()
162 + ": onBootPhase threw an exception during phase "
163 + mCurrentPhase, ex);
164 }
165 warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onBootPhase");
166 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
167 }
168 } finally {
169 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
170 }
171 }
SystemServer中定义了如下几个阶段:
总结下SystemServer启动工作的主要内容:
SystemServer是Zygote进程启动的第一个进程,进程名为"system_server",主要用来启动系统中的服务
SystemServer进程的main入口中,首先会初始化一些系统变量,加载类库,创建Context对象,创建SystemServiceManager对象等,
启动系统中的服务,启动的服务分为 引导服务(Boot Service)、核心服务(Core Service)和其他服务(Other Service)三大类,共90多个服务
启动的服务都单独运行在SystemServer的各自线程中,同属于SystemServer进程