1、SystemServer进程的启动
接着上一篇源码分析,
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
if (startSystemServer) {
Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
// {@code r == null} in the parent (zygote) process, and {@code r != null} in the
// child (system_server) process.
if (r != null) {
r.run();
return;
}
}
在 zygote进程fork system_server进程的时候注释上明确说了,如果在system_server在执行的话,那么就会返回一个Runnable r 对象,并且执行r.run()函数,也就是system_server的执行将会在run函数中。我们来看看这个Runnable r怎么被创建出来的?
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
//启动system server进程的命令参数
/* Hardcoded command line to start the system server */
String args[] = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1032,3001,3002,3003,3006,3007,3009,3010",
"--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_server",
"--runtime-args",
"com.android.server.SystemServer",
};
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
//将命令参数转换为parsedArgs
parsedArgs = new ZygoteConnection.Arguments(args);
ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
/* Request to fork the system server process */
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
zygoteServer.closeServerSocket();
return handleSystemServerProcess(parsedArgs);
}
return null;
}
这里有一个很关键的地方,就是声明了一个字符串数组作为启动system_server的一些命令参数,并把这个数组转换为一个 ZygoteConnection.Arguments parsedArgs,最后一个字符串我们先记住"com.android.server.SystemServer",我们很容易就联想到这个是SystemServer进程启动的全类名。
String args[] = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1032,3001,3002,3003,3006,3007,3009,3010",
"--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_server",
"--runtime-args",
"com.android.server.SystemServer",
};
.....
parsedArgs = new ZygoteConnection.Arguments(args);
....
接着调用handleSystemServerProcess方法,传入我们的parsedArgs参数。
private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) {
....
ClassLoader cl = null;
if (systemServerClasspath != null) {
cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);
Thread.currentThread().setContextClassLoader(cl);
}
....
/*
* Pass the remaining arguments to SystemServer.
*/
return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
}
/* should never reach here */
}
在handleSystemServerProcess方法中又调用了ZygoteInit.zygoteInit作为返回值,并传入我们之前传入的参数parsedArgs.remainingArgs。和一个 ClassLoader cl。在这里我们很容易就猜到了parsedArgs.remainingArgs这个参数就是包含了我们的全类名"com.android.server.SystemServer"。继续调用
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
......
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}
protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
// Remaining arguments are passed to the start class's static main
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
private static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
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 {
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);
}
/*
* This throw gets caught in ZygoteInit.main(), which responds
* by invoking the exception's run() method. This arrangement
* clears up all the stack frames that were required in setting
* up the process.
*/
return new MethodAndArgsCaller(m, argv);
}
追到了最后,调用了findStaticMain函数,从函数的名称我们就知道就是为了寻找静态的 main函数。也就是com.android.server.SystemServer中的main函数。接着调用返回了一个MethodAndArgsCaller对象,构造MethodAndArgsCaller对象的时候传入了我们的method和argv,也就是main函数的方法名和参数。我们在看看具体的MethodAndArgsCaller类
static class MethodAndArgsCaller 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);
}
}
在MethodAndArgsCaller的run函数中,通过mMethod执行了com.android.server.SystemServer中的main函数。那么回到最开始的代码
if (startSystemServer) {
Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
// {@code r == null} in the parent (zygote) process, and {@code r != null} in the
// child (system_server) process.
if (r != null) {
r.run();
return;
}
}
从这里就可以看出,当SystemServer进程启动的时候会执行run函数,那么最终就会执行com.android.server.SystemServer类中的main函数。所以SystemServer的启动我们就需要在main函数中分析。
2、SystemServer的源码分析
frameworks/base/services/java/com/android/server/SystemServer.java
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
...........
//1、准备looper
Looper.prepareMainLooper();
// Initialize native services.
//2、加载本地服务的native库
System.loadLibrary("android_servers");
// Check whether we failed to shut down last time we tried.
// This call may not return.
performPendingShutdown();
// Initialize the system context.
//3、创建系统上下文
createSystemContext();
// Create the system service manager.
//4、创建系统服务的管理者
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
//5、准备线程池,用于一些初始化工作
SystemServerInitThreadPool.get();
...............
...............
// Start services.
try {
//6、启动三种类型的服务
traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
traceEnd();
}
..................
// Loop forever.
//7、调用Looper进入无线循环,等等Handler的Message
Looper.loop();
}
- 调用ooper.prepareMainLooper() 准备Looper。
- 加载本地服务的库 System.loadLibrary("android_servers");
- 创建系统的上下文 createSystemContext();
- 创建管理系统服务的管理SystemServiceManager
- 准备一个线程池用于初始化工作
- 启动service,包含三种类型的服务
- Looper.loop();进入无线循环
SystemServer的main函数主要是就执行了以上的一些流程,最核心的就是启动了很多类型的Service,下一篇文章我们就分析一些Service的启动原理,尤其是最关键的ActivityManagerService。