SystemServer系统服务启动
SystemServer进程用来在创建系统服务,比如AMS、WMS、PMS等。熟悉一下Android系统服务的启动流程。总的启动时序图如下:
接着《Zyoget进程的启动》,同样在ZygoteInit的main方法中:
@UnsupportedAppUsage
public static void main(String argv[]) {
...
try {
zygoteServer = new ZygoteServer(isPrimaryZygote);
if (startSystemServer) {
Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
if (r != null) {
r.run();
return;
}
}
}
...
}调用Runnable forkSystemServer(String abiList, String socketName,ZygoteServer zygoteServer)方法
/**
* 为SystemServer进程准备参数和派生。
*/
private static Runnable forkSystemServer(String abiList, String socketName,ZygoteServer zygoteServer) {
pid = Zygote.forkSystemServer(
parsedArgs.mUid, parsedArgs.mGid,
parsedArgs.mGids,
parsedArgs.mRuntimeFlags,
null,
parsedArgs.mPermittedCapabilities,
parsedArgs.mEffectiveCapabilities);
...
/* 对于子进程 */
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
zygoteServer.closeServerSocket();
return handleSystemServerProcess(parsedArgs);
}
return null;
}接着调用Zygote静态方法forkSystemServer(),接着又会到Native层调用底层的nativeForkSystemServer方法fork出一个Server进程。
public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
ZygoteHooks.preFork();
// Resets nice priority for zygote process.
resetNicePriority();
int pid = nativeForkSystemServer(
uid, gid, gids, runtimeFlags, rlimits,
permittedCapabilities, effectiveCapabilities);
// Enable tracing as soon as we enter the system_server.
if (pid == 0) {
Trace.setTracingEnabled(true, runtimeFlags);
}
ZygoteHooks.postForkCommon();
return pid;
}再回到主调用链上继续,forkSystemServer(String abiList, String socketName,ZygoteServer zygoteServer)方法返回Runnable通过:
return handleSystemServerProcess(parsedArgs);进入handleSystemServerProcess(ZygoteArguments parsedArgs)方法
/**
* 完成新分支的SystemServer进程的剩余工作。
*/
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
// 将umask设置为0077,以便新文件和目录将默认为仅所有者权限。
Os.umask(S_IRWXG | S_IRWXO);
if (parsedArgs.mInvokeWith != null) {
...
} else {
...
/*
* 将其余参数传递给SystemServer。
*/
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,parsedArgs.mRemainingArgs, cl);
}
/* should never reach here */
}又回到ZygoteInit中的Runnable zygoteInit(...)方法
/**
* The main function called when started through the zygote process. This could be unified with
* main(), if the native code in nativeFinishInit() were rationalized with Zygote startup.
*/
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
...
RuntimeInit.commonInit();
ZygoteInit.nativeZygoteInit();
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}RuntimeInit中的静态方法Runnable applicationInit(int targetSdkVersion, String[] argv,ClassLoader classLoader)
protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
...
return findStaticMain(args.startClass, args.startArgs, classLoader);
}findStaticMain方法用来查找SystemServer类的class,并包装到MethodAndArgsCaller中返回该对象:
/**
* 在类“ className”上调用静态“ main(argv [])方法。
* 将各种失败的异常转换为RuntimeException,并假设它们随后将导致VM实例退出。
*
*/
protected static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
...
Method m;
...
/*
* 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);
}注意:以前的源码是直接抛出该类型的异常,在ZygoteInit.main()调用处捕获该异常并执行run()方法运行加载SystemServer。这样做的目的,源码注释也解释的很清楚:此异常被ZygoteInit.main()捕获,该异常通过调用异常的run()方法进行响应。 这种安排清除了设置过程所需的所有堆栈框架。虽然代码该成了return,但是注释还在。
回到ZygoteInit.main()方法中,果然是调用run()方法。
Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
if (r != null) {
r.run();
return;
}MethodAndArgsCaller类定义在RuntimeInit中,run()方法也没有特别的地方,就是通过反射调用SystemServer的main()方法运行。
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);
}
}
}进入SystemServer的main()方法
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}调用类中的私有方法:run()这才是真正最终初始化系统中各种服务的方法。
private void run() {
try {
...
Looper.prepareMainLooper();
// Initialize native services.
System.loadLibrary("android_servers");
// Debug builds - allow heap profiling.
if (Build.IS_DEBUGGABLE) {
initZygoteChildHeapProfiling();
}
// Check whether we failed to shut down last time we tried.
// This call may not return.
performPendingShutdown();
// Initialize the system context.
createSystemContext();
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.get();
}
// Start services.
try {
traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
SystemServerInitThreadPool.shutdown();
}
...
// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}不难看到其中准备工作:
①MainLooper
②初始化SystemServiceManager,
③初始化系统Context
④加载各种系统服务(引导服务、核心服务和其它服务)
至此,Android系统的SystemServer启动完成。这其中也启动了很多熟知的关键服务,比如AMS,详细启动参考《AMS服务的启动》。


