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在執(zhí)行的話,那么就會返回一個Runnable r 對象,并且執(zhí)行r.run()函數(shù),也就是system_server的執(zhí)行將會在run函數(shù)中。我們來看看這個Runnable r怎么被創(chuàng)建出來的?
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
//啟動system server進程的命令參數(shù)
/* 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 {
//將命令參數(shù)轉(zhuǎn)換為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;
}
這里有一個很關(guān)鍵的地方,就是聲明了一個字符串數(shù)組作為啟動system_server的一些命令參數(shù),并把這個數(shù)組轉(zhuǎn)換為一個 ZygoteConnection.Arguments parsedArgs,最后一個字符串我們先記住"com.android.server.SystemServer",我們很容易就聯(lián)想到這個是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);
....
接著調(diào)用handleSystemServerProcess方法,傳入我們的parsedArgs參數(shù)。
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方法中又調(diào)用了ZygoteInit.zygoteInit作為返回值,并傳入我們之前傳入的參數(shù)parsedArgs.remainingArgs。和一個 ClassLoader cl。在這里我們很容易就猜到了parsedArgs.remainingArgs這個參數(shù)就是包含了我們的全類名"com.android.server.SystemServer"。繼續(xù)調(diào)用
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);
}
追到了最后,調(diào)用了findStaticMain函數(shù),從函數(shù)的名稱我們就知道就是為了尋找靜態(tài)的 main函數(shù)。也就是com.android.server.SystemServer中的main函數(shù)。接著調(diào)用返回了一個MethodAndArgsCaller對象,構(gòu)造MethodAndArgsCaller對象的時候傳入了我們的method和argv,也就是main函數(shù)的方法名和參數(shù)。我們在看看具體的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函數(shù)中,通過mMethod執(zhí)行了com.android.server.SystemServer中的main函數(shù)。那么回到最開始的代碼
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進程啟動的時候會執(zhí)行run函數(shù),那么最終就會執(zhí)行com.android.server.SystemServer類中的main函數(shù)。所以SystemServer的啟動我們就需要在main函數(shù)中分析。
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、加載本地服務(wù)的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、創(chuàng)建系統(tǒng)上下文
createSystemContext();
// Create the system service manager.
//4、創(chuàng)建系統(tǒng)服務(wù)的管理者
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、啟動三種類型的服務(wù)
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、調(diào)用Looper進入無線循環(huán),等等Handler的Message
Looper.loop();
}
- 調(diào)用ooper.prepareMainLooper() 準備Looper。
- 加載本地服務(wù)的庫 System.loadLibrary("android_servers");
- 創(chuàng)建系統(tǒng)的上下文 createSystemContext();
- 創(chuàng)建管理系統(tǒng)服務(wù)的管理SystemServiceManager
- 準備一個線程池用于初始化工作
- 啟動service,包含三種類型的服務(wù)
- Looper.loop();進入無線循環(huán)
SystemServer的main函數(shù)主要是就執(zhí)行了以上的一些流程,最核心的就是啟動了很多類型的Service,下一篇文章我們就分析一些Service的啟動原理,尤其是最關(guān)鍵的ActivityManagerService。