概括

基于Android7.1源码。

结合一些文章想看一下Android的SystemServer的产生和启动,发现7.1的代码和文章上的不太一样,只玩的源码我也没看过,不知道什么时候开始变得。就做一个记录。

大致流程就是

1
2
3
4
5
6
7
8
9
10
st=>start: Start
e=>end: End
op1=>operation: 系统的第一个用户进程Init进程启动
op2=>operation: 解析init.rc文件
op3=>operation: 从init进程中fork出zygote进程,也就是app_main.cpp文件
op4=>operation: zygote进程调用AppRuntime的start方法启动ZygoteInit,进入java
op5=>operation: ZygoteInit中从zygote进程fork一个system_server进程
op6=>operation: ZygoteInit调用RuntimeInit.zygoteInit方法,找到SystemServer类和他的main方法
op7=>operation: 由ZygoteInit执行SystemServer的main方法
st->op1->op2->op3->op4->op5->op6->op7->e

init进程

init是Android系统中用户级的第一个进程。通过ps命令可以看到,进程ID是1.

既然整个用户系统都是从init开始的,那么SystemService肯定也是从这里创建了。

init进程的入口是main()方法

/system/core/init/init.cpp:

1
2
3
int main(int argc, char** argv) {
parser.ParseConfig("/init.rc");
}

要解析一个init.rc文件

/system/core/rootdir/init.rc:

1
import /init.${ro.zygote}.rc

在这个文件夹下还有这些文件:

init.zygote64.rc为例

/system/core/rootdir/init.zygote64.rc

1
2
3
4
5
6
7
8
9
10
service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
class main
socket zygote stream 660 root system
onrestart write /sys/android_power/request_state wake
onrestart write /sys/power/state on
onrestart restart audioserver
onrestart restart cameraserver
onrestart restart media
onrestart restart netd
writepid /dev/cpuset/foreground/tasks

通过解析这个文件,会从init进程中fork出zygote进程。

zygote进程

zygote对应的源文件是app_main.cpp,这个进程把自己的名字重命名为zygote。

/frameworks/base/cmds/app_process/app_main.cpp:

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
static const char ZYGOTE_NICE_NAME[] = "zygote64";
int main(int argc, char* const argv[]){
AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
while (i < argc) {
const char* arg = argv[i++];
if (strcmp(arg, "--zygote") == 0) {
zygote = true;
niceName = ZYGOTE_NICE_NAME;
}
}
//重命名进程名字
if (!niceName.isEmpty()) {
runtime.setArgv0(niceName.string());
set_process_name(niceName.string());
}
if (zygote) {
runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
} else if (className) {
runtime.start("com.android.internal.os.RuntimeInit", args, zygote);
} else {
fprintf(stderr, "Error: no class name or --zygote supplied.\n");
app_usage();
LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
return 10;
}
}

看到最后又一句runtime.start("com.android.internal.os.ZygoteInit", args, zygote);,把事情交给runtime去做。runtime是AppRuntime,AppRuntime是继承AndroidRuntime的:

/frameworks/base/cmds/app_process/app_main.cpp:

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
class AppRuntime : public AndroidRuntime{
public:AppRuntime(char* argBlockStart, const size_t argBlockLength)
: AndroidRuntime(argBlockStart, argBlockLength)
, mClass(NULL){}
void setClassNameAndArgs(const String8& className, int argc, char * const *argv) {
......
}
virtual void onVmCreated(JNIEnv* env){
......
}
virtual void onStarted(){
......
}
virtual void onZygoteInit(){
......
}
virtual void onExit(int code){
......
}
}

AppRuntime并没有start方法,因此start方法是AndroidRuntime的:

/frameworks/base/core/jni/AndroidRuntime.cpp

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
void AndroidRuntime::start(const char* className, const Vector<String8>& options, bool zygote)
{
//设置ANDROID_ROOT环境变量
const char* rootDir = getenv("ANDROID_ROOT");
if (rootDir == NULL) {
rootDir = "/system";
if (!hasDir("/system")) {
LOG_FATAL("No root directory specified, and /android does not exist.");
return;
}
setenv("ANDROID_ROOT", rootDir, 1);
}
//启动虚拟机
if (startVm(&mJavaVM, &env, zygote) != 0) {
return;
}
onVmCreated(env);
//注册Android的JNI函数
if (startReg(env) < 0) {
ALOGE("Unable to register all android natives\n");
return;
}
//用数组保存类名和参数
stringClass = env->FindClass("java/lang/String");
strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
classNameStr = env->NewStringUTF(className);
env->SetObjectArrayElement(strArray, 0, classNameStr);
for (size_t i = 0; i < options.size(); ++i) {
jstring optionsStr = env->NewStringUTF(options.itemAt(i).string());
assert(optionsStr != NULL);
env->SetObjectArrayElement(strArray, i + 1, optionsStr);
}
//找到这个类,并执行这个类的main方法,前面调用时传入的是`com.android.internal.os.ZygoteInit`
char* slashClassName = toSlashClassName(className);
jclass startClass = env->FindClass(slashClassName);
if (startClass == NULL) {
ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
/* keep going */
} else {
//找到main方法
jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
"([Ljava/lang/String;)V");
if (startMeth == NULL) {
ALOGE("JavaVM unable to find main() in '%s'\n", className);
/* keep going */
} else {
//通过JNI执行main方法,com.android.internal.os.ZygoteInit是一个java类
env->CallStaticVoidMethod(startClass, startMeth, strArray);
}
//zygote退出
if (mJavaVM->DetachCurrentThread() != JNI_OK)
ALOGW("Warning: unable to detach main thread\n");
if (mJavaVM->DestroyJavaVM() != 0)
ALOGW("Warning: VM did not shut down cleanly\n");
}

这个start方法启动AndroidRuntime,先启动虚拟机,然后注册JNI函数,最后通过传进来的第一个参数找到相应的类,并执行他的main()方法。

这时,从native进入java层了。

进入Java代码 ZygoteInit.java

下面就是ZygoteInit的main方法:

/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java:

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
public static void main(String argv[]) {
try {
RuntimeInit.enableDdms();
// 开始 zygote 初始化.
SamplingProfilerIntegration.start();
boolean startSystemServer = false;
String socketName = "zygote";
String abiList = null;
for (int i = 1; i < argv.length; i++) {
if ("start-system-server".equals(argv[i])) {
startSystemServer = true;
} else if (argv[i].startsWith(ABI_LIST_ARG)) {
abiList = argv[i].substring(ABI_LIST_ARG.length());
}
}
//注册一个服务端的socket供zygote使用
registerZygoteSocket(socketName);
//预加载,包括类,资源,等等
preload();
// 结束zygote 初始化.
SamplingProfilerIntegration.writeZygoteSnapshot();
// 进行一次垃圾回收
gcAndFinalize();
if (startSystemServer) {
//启动system_server进程
startSystemServer(abiList, socketName);
}
} catch (MethodAndArgsCaller caller) {
......
}
}
static void preload() {
Log.d(TAG, "begin preload");
beginIcuCachePinning();
preloadClasses();
preloadResources();
preloadOpenGL();
preloadSharedLibraries();
preloadTextResources();
// Ask the WebViewFactory to do any initialization that must run in the zygote process,
// for memory sharing purposes.
WebViewFactory.prepareWebViewInZygote();
endIcuCachePinning();
warmUpJcaProviders();
Log.d(TAG, "end preload");
}

ZygoteInit的main方法中调用startSystemServer(abiList, socketName)算是启动了system_server进程。

system_server进程的产生

system_server是Android系统Service运行的进程,这个进程死了后,会导致zygote进程重新启动.

startSystemServer也是ZygoteInit的方法:

/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java:

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
private static boolean startSystemServer(String abiList, String socketName)
throws MethodAndArgsCaller, RuntimeException {
/* 硬编码命令行启动系统服务器 */
String args[] = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1032,3001,3002,3003,3006,3007,3009,3010",
"--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_server", //进程名system_server
"--runtime-args",
"com.android.server.SystemServer",//启动类 SystemServer
};
ZygoteConnection.Arguments parsedArgs = null;
try {
//把上面的命令转为Arguments对象
parsedArgs = new ZygoteConnection.Arguments(args);
/* 从Zygote进程中fork一个system server 子进程 */
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
handleSystemServerProcess(parsedArgs);
}
return true;
}

从Zygote进程中fork一个system server 子进程,那么Zygote.forkSystemServer做了什么,怎么启动SystemServer的呢?

/frameworks/base/core/java/com/android/internal/os/Zygote.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
VM_HOOKS.preFork();
int pid = nativeForkSystemServer(
uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);
// Enable tracing as soon as we enter the system_server.
if (pid == 0) {
Trace.setTracingEnabled(true);
}
VM_HOOKS.postForkCommon();
return pid;
}
native private static int nativeForkSystemServer(int uid, int gid, int[] gids, int debugFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);

调用了native方法nativeForkSystemServe,这个方位定义在com_android_internal_os_Zygote.cpp

/frameworks/base/core/jni/com_android_internal_os_Zygote.cpp:

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
static jint com_android_internal_os_Zygote_nativeForkSystemServer(
JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
jlong effectiveCapabilities) {
pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
debug_flags, rlimits,
permittedCapabilities, effectiveCapabilities,
MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
NULL, NULL);
if (pid > 0) {
gSystemServerPid = pid;
if (waitpid(pid, &status, WNOHANG) == pid) {
RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
}
}
return pid;
}
static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
jint debug_flags, jobjectArray javaRlimits,
jlong permittedCapabilities, jlong effectiveCapabilities,
jint mount_external,
jstring java_se_info, jstring java_se_name,
bool is_system_server, jintArray fdsToClose,
jstring instructionSet, jstring dataDir) {
pid_t pid = fork();
return pid;
}

system_server进程的执行

上面fork了一个进程后,返回了pid,在回到ZygoteInit的startSystemServer方法:

/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private static boolean startSystemServer(String abiList, String socketName)
throws MethodAndArgsCaller, RuntimeException {
/* 硬编码命令行启动系统服务器 */
try {
//把上面的命令转为Arguments对象
parsedArgs = new ZygoteConnection.Arguments(args);
/* 从Zygote进程中fork一个system server 子进程 */
pid = Zygote.forkSystemServer(
);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
if (pid == 0) {
handleSystemServerProcess(parsedArgs);
}
return true;
}

通过Zygote.forkSystemServer方法之后,system_server进程就产生了。下面就该这个进程干活了。

system_server进程生成后,执行了handleSystemServerProcess(parsedArgs)方法:

/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private static void handleSystemServerProcess(
ZygoteConnection.Arguments parsedArgs)
throws ZygoteInit.MethodAndArgsCaller {
if (parsedArgs.invokeWith != null) {
} else {
ClassLoader cl = null;
if (systemServerClasspath != null) {
cl = createSystemServerClassLoader(systemServerClasspath,parsedArgs.targetSdkVersion);
Thread.currentThread().setContextClassLoader(cl);
}
/* 将参数传递给SystemServer. */
RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
}
}

下面是RuntimeInit.zygoteInit:

/frameworks/base/core/java/com/android/internal/os/RuntimeInit.java

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
public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
throws ZygoteInit.MethodAndArgsCaller {
if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from zygote");
commonInit();
nativeZygoteInit();
applicationInit(targetSdkVersion, argv, classLoader);
}
private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
throws ZygoteInit.MethodAndArgsCaller {
nativeSetExitWithoutCleanup(true);
// 将参数传递给类的主方法 main(),也就是com.android.server.SystemServer的main方法。
invokeStaticMain(args.startClass, args.startArgs, classLoader);
}
private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
throws ZygoteInit.MethodAndArgsCaller {
Class<?> cl;
try {
cl = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
"Missing class when invoking static main " + className,ex);
}
Method m;
try {
//找到main方法
m = cl.getMethod("main", new Class[] { String[].class });
} catch (NoSuchMethodException ex) {
throw new RuntimeException(
"Missing static main on " + className, ex);
} catch (SecurityException ex) {
throw new RuntimeException(
"Problem getting static main on " + className, ex);
}
int modifiers = m.getModifiers();
if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
throw new RuntimeException(
"Main method is not public and static on " + className);
}
//然后并没哟着这里执行,而是抛出了异常。
throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}

上面说是执行main方法,但是真正功能只是找到了main方法,然后并没有执行,而是抛出了一个异常ZygoteInit.MethodAndArgsCaller。这是ZygoteInit内部定义的一个异常。

/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java:

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
public static class MethodAndArgsCaller extends Exception
implements Runnable {
/** method to call */
private final Method mMethod;
/** argument array */
private final String[] mArgs;
public MethodAndArgsCaller(Method method, String[] args) {
mMethod = method;
mArgs = args;
}
public void run() {
try {
mMethod.invoke(null, new Object[] { mArgs });
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
Throwable cause = ex.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
}
throw new RuntimeException(ex);
}
}
}

这个异常会一直向上抛,一直到ZygoteInit的main方法里才会捕捉处理:

/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String argv[]) {
try {
if (startSystemServer) {
startSystemServer(abiList, socketName);
}
} catch (MethodAndArgsCaller caller) {
caller.run();
} catch (Throwable ex) {
Log.e(TAG, "Zygote died with exception", ex);
closeServerSocket();
throw ex;
}
}

看到上面的caller.run(),结合上面的MethodAndArgsCaller,这里才是真正执行SystemServer.main()方法的地方。

SystemServer.main()

这下终于进入SystemServer了

直接看进入的main方法,就一句:

/frameworks/base/services/java/com/android/server/SystemServer.java

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
private static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; // 1hr
public static void main(String[] args) {
new SystemServer().run();
}
public SystemServer() {
// Check for factory test mode.
mFactoryTestMode = FactoryTest.getMode();
}
private void run() {
try {
// 调整系统时间
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
//这里系统已经欢迎我们来到Android system server了。!。
// Here we go!
Slog.i(TAG, "Entered the Android system server!");
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis());
// 性能采样分析,输出到文件.一小时执行一次
if (SamplingProfilerIntegration.isEnabled()) {
SamplingProfilerIntegration.start();
mProfilerSnapshotTimer = new Timer();
mProfilerSnapshotTimer.schedule(new TimerTask() {
@Override
public void run() {
SamplingProfilerIntegration.writeSnapshot("system_server", null);
}
}, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
}
//这里开启了一个Looper
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();
System.loadLibrary("android_servers");
performPendingShutdown();
//初始化系统Context
createSystemContext();
// 创建SystemServiceManager
mSystemServiceManager = new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
// 启动一些系统服务.
try {
startBootstrapServices();
startCoreServices();
startOtherServices();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
private void createSystemContext() {
//创建系统的Context是在ActivityThread中完成的。
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
}