概述

SystemServer进程主要用于创建系统服务,我们熟悉的AMS、WMS、PMS都是由SystemServer创建的。关于这些系统服务我们后来再讲。本文我们先来熟悉并了解SystemServer进程是如何启动的,他在启动时做了哪些重要的工作。

源码分析

Zygote启动SyetemServer进程

在上一篇文章中我们讲到在ZygoteInit.java的startSystemServer函数中启动了SyetemServer进程,如下所示。

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
/**
* 代码位于:/framework/base/core/java/com/android/internal/os/ZygoteInit.java
* This is the entry point for a Zygote process. It creates the Zygote server, loads resources,
* and handles other tasks related to preparing the process for forking into applications.
*
* This process is started with a nice value of -20 (highest priority). All paths that flow
* into new processes are required to either set the priority to the default value or terminate
* before executing any non-system code. The native side of this occurs in SpecializeCommon,
* while the Java Language priority is changed in ZygoteInit.handleSystemServerProcess,
* ZygoteConnection.handleChildProc, and Zygote.usapMain.
*
* @param argv Command line arguments used to specify the Zygote's configuration.
*/
@UnsupportedAppUsage
public static void main(String argv[]) {
//用来管理和子进程通信的socket服务端
ZygoteServer zygoteServer = null;

// Mark zygote start. This ensures that thread creation will throw
// an error.
//这里其实只是设置一个标志位,为创建Java线程时做判断处理,如果是zygote进程,则不需要开启线程
ZygoteHooks.startZygoteNoThreadCreation();

// Zygote goes into its own process group.
try {
//为zygote进程设置pgid(Process Group ID),
// 详见:`https://stackoverflow.com/questions/41498383/what-do-the-identifiers-pid-ppid-sid-pgid-uid-euid-mean`
Os.setpgid(0, 0);
} catch (ErrnoException ex) {
throw new RuntimeException("Failed to setpgid(0,0)", ex);
}

Runnable caller;
try {
// Store now for StatsLogging later.
final long startTime = SystemClock.elapsedRealtime();
//获取系统属性,判断系统重启完成
final boolean isRuntimeRestarted = "1".equals(
SystemProperties.get("sys.boot_completed"));
//判断当前进程是64位程序还是32位程序,并设置标记
String bootTimeTag = Process.is64Bit() ? "Zygote64Timing" : "Zygote32Timing";
TimingsTraceLog bootTimingsTraceLog = new TimingsTraceLog(bootTimeTag,
Trace.TRACE_TAG_DALVIK);
bootTimingsTraceLog.traceBegin("ZygoteInit");
RuntimeInit.preForkInit();

// 解析参数前的默认参数值
boolean startSystemServer = false;
String zygoteSocketName = "zygote";
String abiList = null;
boolean enableLazyPreload = false;
//对参数进行解析
for (int i = 1; i < argv.length; i++) {
//参数重包含`start-system-server`
if ("start-system-server".equals(argv[i])) {
//设置标志为位true
startSystemServer = true;
} else if ("--enable-lazy-preload".equals(argv[i])) {
enableLazyPreload = true;
} else if (argv[i].startsWith(ABI_LIST_ARG)) {
//获取支持的架构列表
abiList = argv[i].substring(ABI_LIST_ARG.length());
} else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
zygoteSocketName = argv[i].substring(SOCKET_NAME_ARG.length());
} else {
throw new RuntimeException("Unknown command line argument: " + argv[i]);
}
}

final boolean isPrimaryZygote = zygoteSocketName.equals(Zygote.PRIMARY_SOCKET_NAME);
if (!isRuntimeRestarted) {
if (isPrimaryZygote) {
FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__ZYGOTE_INIT_START,
startTime);
} else if (zygoteSocketName.equals(Zygote.SECONDARY_SOCKET_NAME)) {
FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SECONDARY_ZYGOTE_INIT_START,
startTime);
}
}
//如果支持架构为空,直接抛出异常
if (abiList == null) {
throw new RuntimeException("No ABI list supplied.");
}

// In some configurations, we avoid preloading resources and classes eagerly.
// In such cases, we will preload things prior to our first fork.
if (!enableLazyPreload) {
bootTimingsTraceLog.traceBegin("ZygotePreload");
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
SystemClock.uptimeMillis());
preload(bootTimingsTraceLog);
EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
SystemClock.uptimeMillis());
bootTimingsTraceLog.traceEnd(); // ZygotePreload
}

// Do an initial gc to clean up after startup
bootTimingsTraceLog.traceBegin("PostZygoteInitGC");
// 调用ZygoteHooks.gcAndFinalize()进行垃圾回收
gcAndFinalize();
bootTimingsTraceLog.traceEnd(); // PostZygoteInitGC

bootTimingsTraceLog.traceEnd(); // ZygoteInit
//jni调用初始化zygote的状态,是否为isPrimaryZygote
Zygote.initNativeState(isPrimaryZygote);
//结束zygote创建,其实内部是调用`runtime`给`zygote_no_threads_`赋值为false,为创建本地线程做准备
ZygoteHooks.stopZygoteNoThreadCreation();
//创建zygoteServer,为其他进程初始化创建时与zygote通信做准备
zygoteServer = new ZygoteServer(isPrimaryZygote);

//判断是否需要startSystemServer
if (startSystemServer) {
//通过fork的方式开启zygote的子进程,systemServer,并返回一个Runnale对象
Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);

// {@code r == null} in the parent (zygote) process, and {@code r != null} in the
// child (system_server) process.
//如果是zygote进程,则r==null,如果不是zygote进程,也就是systemServer进程,则执行下面的代码
if (r != null) {
r.run();
return;
}
}

Log.i(TAG, "Accepting command socket connections");

// The select loop returns early in the child process after a fork and
// loops forever in the zygote.
// zygote进程进入死循环中,来获取子进程发送的消息
caller = zygoteServer.runSelectLoop(abiList);
} catch (Throwable ex) {
//如果发生异常,则说明zygote初始化失败,zygoteServer也需要关闭
Log.e(TAG, "System zygote died with exception", ex);
throw ex;
} finally {
//如果发生异常,则说明zygote初始化失败,zygoteServer也需要关闭
if (zygoteServer != null) {
zygoteServer.closeServerSocket();
}
}

// We're in the child process and have exited the select loop. Proceed to execute the
// command.
if (caller != null) {
caller.run();
}
}

下面,我们来看一下forkSystemServer的方法的具体实现,如下所示:

ZygoteInit.forkSystemServer

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
/**
* 代码位于:/framework/base/core/java/com/android/internal/os/ZygoteInit.java
* 为forkSystemServer进程准备参数,并且创建system server进程
*/
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
//Linux使用POSIX capabilities代替传统的信任状模型
//设置进程权能
long capabilities = posixCapabilitiesAsBits(
OsConstants.CAP_IPC_LOCK, //允许锁定共享内存片段
OsConstants.CAP_KILL,//允许对不属于自己的进程发送信号
OsConstants.CAP_NET_ADMIN,// 允许执行网络管理任务:接口、防火墙和路由等
OsConstants.CAP_NET_BIND_SERVICE,//允许绑定到小于1024的端口
OsConstants.CAP_NET_BROADCAST,//允许网络广播和多播访问
OsConstants.CAP_NET_RAW,//允许网络广播和多播访问
OsConstants.CAP_SYS_MODULE,//插入和删除内核模块
OsConstants.CAP_SYS_NICE,//允许提升优先级,设置其它进程的优先级
OsConstants.CAP_SYS_PTRACE,//允许配置进程记帐
OsConstants.CAP_SYS_TIME, //允许改变系统时钟
OsConstants.CAP_SYS_TTY_CONFIG,//允许配置TTY设备
OsConstants.CAP_WAKE_ALARM,
OsConstants.CAP_BLOCK_SUSPEND
);
/* Containers run without some capabilities, so drop any caps that are not available. */
StructCapUserHeader header = new StructCapUserHeader(
OsConstants._LINUX_CAPABILITY_VERSION_3, 0);
//用户权能数据
StructCapUserData[] data;
try {
//获取进程权能,存储到data中
data = Os.capget(header);
} catch (ErrnoException ex) {
throw new RuntimeException("Failed to capget()", ex);
}
capabilities &= ((long) data[0].effective) | (((long) data[1].effective) << 32);
/*使用硬编码的方式定义出启动system server的参数字符串args*/
/* Hardcoded command line to start the system server */
String args[] = {
"--setuid=1000", // 用户ID
"--setgid=1000", // 用户组ID
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,"
+ "1024,1032,1065,3001,3002,3003,3006,3007,3009,3010,3011",
"--capabilities=" + capabilities + "," + capabilities,//进程权能
"--nice-name=system_server",//进程niceName
"--runtime-args",
"--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
"com.android.server.SystemServer",
};
ZygoteArguments parsedArgs = null;
//processId,进程id
int pid;

try {
//创建ZygoteArguments对象,把args解析为需要的参数
parsedArgs = new ZygoteArguments(args);
Zygote.applyDebuggerSystemProperty(parsedArgs);
Zygote.applyInvokeWithSystemProperty(parsedArgs);

if (Zygote.nativeSupportsTaggedPointers()) {
/* Enable pointer tagging in the system server. Hardware support for this is present
* in all ARMv8 CPUs. */
parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_TBI;
}

/* Enable gwp-asan on the system server with a small probability. This is the same
* policy as applied to native processes and system apps. */
parsedArgs.mRuntimeFlags |= Zygote.GWP_ASAN_LEVEL_LOTTERY;

if (shouldProfileSystemServer()) {
parsedArgs.mRuntimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
}
//通过fork创建SystemServer
/* Request to fork the system server process */
pid = Zygote.forkSystemServer(
parsedArgs.mUid, parsedArgs.mGid,
parsedArgs.mGids,
parsedArgs.mRuntimeFlags,
null,
parsedArgs.mPermittedCapabilities,
parsedArgs.mEffectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
//pid为0,则说明是zygote进程,进行最后的收尾工作
/* For child process */
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}

zygoteServer.closeServerSocket();
return handleSystemServerProcess(parsedArgs);
}

return null;
}

在startSystemServer函数中调用forkSystemServer来启动SyetemServer进程。这里就看出来Zgote进程的作用就是来forkSystemServer进程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 代码位于:/framework/base/core/java/com/android/internal/os/Zygote.java
* Zygote.forkSystemServer()是调用nativeForkSystemServer进行创建systemServer的进程函数
*/
static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
// 内部调用ART的Runtime对zygote的线程池的线程进行清理
ZygoteHooks.preFork();
//JNI调用,真正创建systemServer进程的函数
int pid = nativeForkSystemServer(
uid, gid, gids, runtimeFlags, rlimits,
permittedCapabilities, effectiveCapabilities);

// Set the Java Language thread priority to the default value for new apps.
//
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);

ZygoteHooks.postForkCommon();
return pid;
}

private static native int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);
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
/**
* 代码位于:frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
* JNIEnv* env
**/
static jint com_android_internal_os_Zygote_nativeForkSystemServer(
JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
jlong effective_capabilities) {

std::vector<int> fds_to_close(MakeUsapPipeReadFDVector()),
fds_to_ignore(fds_to_close);

fds_to_close.push_back(gUsapPoolSocketFD);

if (gUsapPoolEventFD != -1) {
fds_to_close.push_back(gUsapPoolEventFD);
fds_to_ignore.push_back(gUsapPoolEventFD);
}

if (gSystemServerSocketFd != -1) {
fds_to_close.push_back(gSystemServerSocketFd);
fds_to_ignore.push_back(gSystemServerSocketFd);
}
//从zygote进程fork出子进程,并返回processId
// 第二个参数:is_system_server 判断是不是fork SystemServer进程
pid_t pid = ForkCommon(env, true,
fds_to_close,
fds_to_ignore,
true);
if (pid == 0) {
// System server prcoess does not need data isolation so no need to
// know pkg_data_info_list.
SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
permitted_capabilities, effective_capabilities,
MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
false, nullptr, nullptr, /* is_top_app= */ false,
/* pkg_data_info_list */ nullptr,
/* whitelisted_data_info_list */ nullptr, false, false);
} else if (pid > 0) {
// The zygote process checks whether the child process has died or not.
ALOGI("System server process %d has been created", pid);
gSystemServerPid = pid;
//..............
}
}
return pid;
}
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
/**
* 代码位于:/framework/base/core/java/com/android/internal/os/ZygoteInit.java
* Finish remaining work for the newly forked system server process.
*/
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
// set umask to 0077 so new files and directories will default to owner-only permissions.
Os.umask(S_IRWXG | S_IRWXO);
// 进行SystemServer启动之前的参数解析
if (parsedArgs.mNiceName != null) {
Process.setArgV0(parsedArgs.mNiceName);
}

// ...........

WrapperInit.execApplication(parsedArgs.mInvokeWith,
parsedArgs.mNiceName, parsedArgs.mTargetSdkVersion,
VMRuntime.getCurrentInstructionSet(), null, args);

throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
} else {
ClassLoader cl = null;
if (systemServerClasspath != null) {
// systemServerClassPath和targetSdkVersion创建了一个PathClassLoader
cl = createPathClassLoader(systemServerClasspath, parsedArgs.mTargetSdkVersion);

Thread.currentThread().setContextClassLoader(cl);
}

/*
* Pass the remaining arguments to SystemServer.
* 将其余参数传递给SystemServer。
*/
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mDisabledCompatChanges,
parsedArgs.mRemainingArgs, cl);
}

/* should never reach here */
}

最后调用到了zygoteInit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 代码位于:/framework/base/core/java/com/android/internal/os/ZygoteInit.java
*/
public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
if (RuntimeInit.DEBUG) {
Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
}

Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
RuntimeInit.redirectLogStreams();
// 调用Runtime的commonInit的方法
RuntimeInit.commonInit();
// 这个调用ZygoteInit的NativeZygoteInit()的方法
ZygoteInit.nativeZygoteInit();
// 最终要的方法,调用的RuntimeInit.applicationInit()
return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
classLoader);
}

方法调用了到了Native层的nativeZygoteInit

1
2
3
4
5
6
7
8
/**
* 代码位于:framwork/base/core/jni/AndroidRuntime.cpp
**/
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz){
// gCurRuntime是AndroidRuntime类型的指针,
// 具体指向的是其子类AppRuntime,它在app_main.cpp中定义
gCurRuntime->onZygoteInit();
}
1
2
3
4
5
6
7
8
9
/**
*
*/
virtual void onZygoteInit(){
// 启动线程池
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
proc->startThreadPool();
}

SystemServer.startOtherServices

StartWindowManagerService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 如下逻辑启动WindowManagerService
t.traceBegin("StartWindowManagerService");
// WMS needs sensor service ready
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_SENSOR_SERVICE);
// 调用WindowManmagerService的main函数
wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
// 然后把WindowManmagerService添加到ServiceManager中
ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
t.traceEnd();

t.traceBegin("SetWindowManagerService");
mActivityManagerService.setWindowManager(wm);
t.traceEnd();

t.traceBegin("WindowManagerServiceOnInitReady");
wm.onInitReady();
t.traceEnd();