Zygote 进程是 Android 系统的第一个 Java 进程(即虚拟机进程),Zygote 是所有 Java 进程的父进程,Zygote 进程本身是由 init 进程孵化而来的。SystemServer 进程,是由 Zygote 进程 fork 而来,SystemServer 是 Zygote 孵化的第一个进程,SystemServer 负责启动和管理整个 Java framework,包含 ActivityManager,WindowManager,PackageManager,PowerManager 等服务。

SystemServer

  • 涉及源码
    • frameworks/base/services/java/com/android/server/SystemServer.java
    • frameworks/base/services/core/java/com/android/server/SystemService.java
    • frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

SystemServer 生成流程

略。

SystemServer 启动流程

main()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// The main entry point from zygote.
public static void main(String[] args) {
    new SystemServer().run();
}

public SystemServer() {
    // Check for factory test mode.
    mFactoryTestMode = FactoryTest.getMode();
    // Remember if it's runtime restart(when sys.boot_completed is already set) or reboot
    mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));
    // 系统开机到当前的时间总数,保证一直计时
    mRuntimeStartElapsedTime = SystemClock.elapsedRealtime();
    // 系统开机到当前的时间总数;深度睡眠时会暂停计时,所以不包括深度睡眠时间
    mRuntimeStartUptime = SystemClock.uptimeMillis();
}

run()

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
private void run() {
    try {
        traceBeginAndSlog("InitBeforeStartServices");
        // If a device's clock is before 1970 (before 0), a lot of
        // APIs crash dealing with negative numbers, notably
        // java.io.File#setLastModified, so instead we fake it and
        // hope that time from cell towers or NTP fixes it shortly.
        // 如果当前时间早于  1970 年,将当前时间设为  1970 年
        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
        }

        // Default the timezone property to GMT if not set.
        // 如果没有设置时区,将时区设为  GMT
        String timezoneProperty =  SystemProperties.get("persist.sys.timezone");
        if (timezoneProperty == null || timezoneProperty.isEmpty()) {
            SystemProperties.set("persist.sys.timezone", "GMT");
        }

        // If the system has "persist.sys.language" and friends set, replace them with
        // "persist.sys.locale". Note that the default locale at this point is calculated
        // using the "-Duser.locale" command line flag. That flag is usually populated by
        // AndroidRuntime using the same set of system properties, but only the system_server
        // and system apps are allowed to set them.
        //
        // NOTE: Most changes made here will need an equivalent change to
        // core/jni/AndroidRuntime.cpp
        // 将  language 属性转换为  locale 属性
        if (!SystemProperties.get("persist.sys.language").isEmpty()) {
            final String languageTag = Locale.getDefault().toLanguageTag();

            SystemProperties.set("persist.sys.locale", languageTag);
            SystemProperties.set("persist.sys.language", "");
            SystemProperties.set("persist.sys.country", "");
            SystemProperties.set("persist.sys.localevar", "");
        }

        // The system server should never make non-oneway calls
        // 阻塞同步  Binder 调用,只允许异步调用
        Binder.setWarnOnBlocking(true);
        // The system server should always load safe labels
        PackageItemInfo.setForceSafeLabels(true);

        // 初始化  SettingsProvider
        // Default to FULL within the system server.
        SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;
        // Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
        SQLiteCompatibilityWalFlags.init(null);

        // Here we go!
        Slog.i(TAG, "Entered the Android system server!");
        int uptimeMillis = (int) SystemClock.elapsedRealtime();
        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, VuptimeMillis);
        if (!mRuntimeRestart) {
            MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
        }

        // In case the runtime switched since last boot (such as when
        // the old runtime was removed in an OTA), set the system
        // property so that it is in sync. We can | xq oqi't do this in
        // libnativehelper's JniInvocation::Init code where we already
        // had to fallback to a different runtime because it is
        // running as root and we need to be the system user to set
        // the property. http://b/11463182
        // 当初切换虚拟机是无缝切换的,只更改了库文件,现在一般默认都是:libart.so,
        // OTA 后可能切换虚拟机所有需更新该值
        SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());

        // Mmmmmm... more memory!
        // 解除内存增长限制
        VMRuntime.getRuntime().clearGrowthLimit();
        // 设置内存利用率
        // The system server has to run all of the time, so it needs to be
        // as efficient as possible with its memory usage.
        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

        // Some devices rely on runtime fingerprint generation, so make sure
        // we've defined it before booting further.
        // 确保指纹值生成
        Build.ensureFingerprintProperty();

        // Within the system server, it is an error to access Environment paths without
        // explicitly specifying a user.
        // 针对特定用户获取环境变量才有意义
        Environment.setUserRequired(true);

        // Within the system server, any incoming Bundles should be defused
        // to avoid throwing BadParcelableException.
        // 去掉传入  SystemServer 的  Bundles,避免引起  BadParcelableException 异常
        BaseBundle.setShouldDefuse(true);

        // Within the system server, when parceling exceptions, include the stack trace
        // 抛出异常时,输出堆栈信息
        Parcel.setStackTraceParceling(true);

        // Ensure binder calls into the system always run at foreground priority.
        // 确保始终使用前台优先级进行  Binder 调用
        BinderInternal.disableBackgroundScheduling(true);

        // Increase the number of binder threads in system_server
        // 设置  Binder 最大线程数
        BinderInternal.setMaxThreads(sMaxBinderThreads);

        // Prepare the main looper thread (this thread).
        // 准备主  looper 线程
        android.os.Process.setThreadPriority(
                                             android.os.Process.THREAD_PRIORITY_FOREGROUND);
        android.os.Process.setCanSelfBackground(false);
        Looper.prepareMainLooper();
        Looper.getMainLooper().setSlowLogThresholdMs(
                                                     SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);

        // Initialize native services.
        // 初始化  native 服务
        System.loadLibrary("android_servers");

        // Check whether we failed to shut down last time we tried.
        // This call may not return.
        // 检查上次关机是否失败,该调用可能没有返回值;当" sys.shutdown.requested"值不为空,则会重启或者关机
        performPendingShutdown();

        // Initialize the system context.
        // 初始化系统上下文,该过程会创建对象有  ActivityThread,Instrumentation, ContextImpl,LoadedApk,Application。
        createSystemContext();

        // Create the system service manager.
        // 创建  SystemServiceManager 对象并启动
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setStartInfo(mRuntimeRestart,
                                           mRuntimeStartElapsedTime, mRuntimeStartUptime);
        // 保存到  LocalServices 中,供  SystemServer 中其它服务本地调用
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        // Prepare the thread pool for init tasks that can be parallelized
        // 初始化线程池
        SystemServerInitThreadPool.get();
    } finally {
        traceEnd();  // InitBeforeStartServiddces
    }

    // Start services.
    try {
        traceBeginAndSlog("StartServices");
        // 启动系统服务
        startBootstrapServices();
        startCoreServices();
        startOtherServices();
        SystemServerInitThreadPool.shutdown();
    } catch (Throwable ex) {
        throw ex;
    } finally {
        traceEnd();
    }

    StrictMode.initVmDefaults(null);

    if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
        int uptimeMillis = (int) SystemClock.elapsedRealtime();
        MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
        final int MAX_UPTIME_MILLIS = 60 * 1000;
        if (uptimeMillis > MAX_UPTIME_MILLIS) {
            Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
                     "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
        }
    }

    // Loop forever.
    // 处理消息
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

startBootstrapServices()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
private void startBootstrapServices() {
    // 读取系统配置
    SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
    // 启动服务:Installer
    Installer installer = mSystemServiceManager.startService(Installer.class);

    // 启动服务:DeviceIdentifiersPolicyService
    mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
    // 启动服务:ActivityManagerService
    mActivityManagerService = mSystemServiceManager.startService(
                                                                 ActivityManagerService.Lifecycle.class).getService();
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);

    // 启动服务:PowerManagerService
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
    mActivityManagerService.initPowerManagement();
    // 启动服务:RecoverySystemService
    mSystemServiceManager.startService(RecoverySystemService.class);

    // Now that we have the bare essentials of the OS up and running, take
    // note that we just booted, which might send out a rescue party if
    // we're stuck in a runtime restart loop.
    // 标记启动
    RescueParty.noteBoot(mSystemContext);

    // 启动服务:LightsService
    mSystemServiceManager.startService(LightsService.class);

    // Package manager isn't started yet; need to use SysProp not hardware feature
    // 启动服务:SidekickService
    if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
        mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
    }

    // 启动服务:DisplayManagerService
    mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

    mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

    // Only run "core" apps if we're encrypting the device.
    String cryptState = SystemProperties.get("vold.decrypt");
    if (ENCRYPTING_STATE.equals(cryptState)) {
        mOnlyCore = true;
    } else if (ENCRYPTED_STATE.equals(cryptState)) {
        mOnlyCore = true;
    }

    // 启动服务:PackageManagerService
    mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                                                        mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    mFirstBoot = mPackageManagerService.isFirstBoot();
    mPackageManager = mSystemContext.getPackageManager();
    // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
    // A/B artifacts after boot, before anything else might touch/need them.
    // Note: this isn't needed during decryption (we don't have /data anyways).
    // 启动服务:OtaDexoptService
    if (!mOnlyCore) {
        boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
                                                               false);
        if (!disableOtaDexopt) {
            OtaDexoptService.main(mSystemContext, mPackageManagerService);
        }
    }

    // 启动服务:UserManagerService
    mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
    AttributeCache.init(mSystemContext);
    mActivityManagerService.setSystemProcess();

    // DisplayManagerService needs to setup android.display scheduling related policies
    // since setSystemProcess() would have overridden policies due to setProcessGroup
    mDisplayManagerService.setupSchedulerPolicies();

    // 启动服务:OverlayManagerService
    OverlayManagerService overlayManagerService = new OverlayManagerService(
                                                                            mSystemContext, installer);
    mSystemServiceManager.startService(overlayManagerService);

    if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {
        // DisplayManager needs the overlay immediately.
        overlayManagerService.updateSystemUiContext();
        LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();
    }

    // The sensor service needs access to package manager service, app ops
    // service, and permissions service, therefore we start it after them.
    // Start sensor service in a separate thread. Completion should be checked
    // before using it.
    // 启动服务:SensorService
    mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
            startSensorService();
        }, START_SENSOR_SERVICE);
}

startCoreServices()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
private void startCoreServices() {
    // 启动服务:BatteryService
    mSystemServiceManager.startService(BatteryService.class);
    // 启动服务:UsageStatsService
    mSystemServiceManager.startService(UsageStatsService.class);
    mActivityManagerService.setUsageStatsManager(
                                                 LocalServices.getService(UsageStatsManagerInternal.class));
    // 启动服务:WebViewUpdateService
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
        mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
    }
    // 启动服务:BinderCallsStatsService
    // Tracks cpu time spent in binder calls
    BinderCallsStatsService.start();
}

startOtherServices()

启动剩余服务,并调用相关服务的 systemReady() 方法,后调用 ActivityManagerService.systemReady()

SystemServiceManager.startBootPhase()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public void startBootPhase(final int phase) {
    if (phase <= mCurrentPhase) {
        throw new IllegalArgumentException("Next phase must be larger than previous");
    }
    mCurrentPhase = phase;

    try {
        final int serviceLen = mServices.size();
        for (int i = 0; i < serviceLen; i++) {
            final SystemService service = mServices.get(i);
            long time = SystemClock.elapsedRealtime();
            try {
                // 依次调用本地服务的相应方法
                service.onBootPhase(mCurrentPhase);
            } catch (Exception ex) {
            }
            warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onBootPhase");
        }
    } finally {
    }
}

服务启动阶段

SystemServiceManager.startBootPhase() 该方法总调用了七次,服务启动被分为八阶段。因为有些服务的创建和初始化需依赖其它服务的创建或初始化,所以服务需分阶段创建及初始化来处理服务之间的依赖关系。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public final class SystemServer {

    private void startBootstrapServices() {
        // 0.phase0: 创建四大引导服务: ActivityManagerService PowerManagerService LightsService DisplayManagerService
        // ......
        // 1.phase100: 在初始化  PackageManagerService 之前,我们需要启动  DisplayManagerService
        mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
        // ......
    }

    private void startCoreServices() {
        // ......
    }

    private void startOtherServices() {
        // ......
        // 2.phase480
        mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
        // 3.phase500
        mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
        // 各大服务执行  systemReady()
        // ......
        // 4.phase520
        mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);
        // 最后调用  ActivityManagerService.systemReady()
        // ......
        mActivityManagerService.systemReady(() -> {
                // 5.phase550
                mSystemServiceManager.startBootPhase(SystemService.PHASE_ACTIVITY_MANAGER_READY);
                // ......
                // 6.phase600
                mSystemServiceManager.startBootPhase(SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
            }, BOOT_TIMINGS_TRACE_LOG);
    }
}

public class ActivityManagerService extends IActivityManager.Stub
    implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    // .....
    final void finishBooting() {
        // .....
        // 7.phase1000: 到此,系统服务启动阶段完成就绪,system_server 进程启动完成则进入  Looper.loop()状态,
        // 随时待命,等待消息队列  MessageQueue 中的消息到来,则马上进入执行状态。
        mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED);
        // .....
    }
    // .....
}