在Android 11 Zygote启动流程有提到,Zygote通过forkSystemServer,fork出SystemServer进程,并在SystemServer进程中调用handleSystemServerProcess 返回一个 Runnable
//......
/* For child process */
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
zygoteServer.closeServerSocket();
//这里返回一个Runnable ,然后在ZygoteInit的main函数中调用此Runnable 的run方法,启动systemserver
return handleSystemServerProcess(parsedArgs);
}
然后调用Runnable 的run方法
//......
if (startSystemServer) {
Runnable r = forkSystemServer(abiList, zygoteSocketName, 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;
}
}
//......
那就由handleSystemServerProcess开始分析,看看返回的Runnable是什么类型
/*env |grep SYSTEMSERVERCLASSPATH
SYSTEMSERVERCLASSPATH=/system/framework/com.android.location.provider.jar:/system/framework/services.jar:/system/framework/ethernet-service.jar:/apex/com.android.permission/javalib/service-permission.jar:/apex/com.android.ipsec/javalib/android.net.ipsec.ike.jar*/
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
//......
final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
if (systemServerClasspath != null) {
performSystemServerDexOpt(systemServerClasspath);//做odex
//......
}
if (parsedArgs.mInvokeWith != null) {
//......
throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
} else {
ClassLoader cl = null;
if (systemServerClasspath != null) {
cl = createPathClassLoader(systemServerClasspath, parsedArgs.mTargetSdkVersion);
Thread.currentThread().setContextClassLoader(cl);
}
/*
* Pass the remaining arguments to SystemServer.
*/
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mDisabledCompatChanges,
parsedArgs.mRemainingArgs, cl);
}
先对相关文件夹下的包做odex,然后创建ClassLoader,执行zygoteInit方法
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();
RuntimeInit.commonInit(); //主要是设置默认的异常捕获方法
ZygoteInit.nativeZygoteInit();//开启binder线程池
return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
classLoader);
}
在zygoteInit方法中,主演完成三个工作:
- 调用RuntimeInit的commonInit方法
- 调用ZygoteInit的nativeZygoteInit方法
- 调用RuntimeInit的applicationInit方法
RuntimeInit.commonInit
@UnsupportedAppUsage
protected static final void commonInit() {
if (DEBUG) Slog.d(TAG, "Entered RuntimeInit!");
/*
* set handlers; these apply to all threads in the VM. Apps can replace
* the default handler, but not the pre handler.
*/
LoggingHandler loggingHandler = new LoggingHandler();
RuntimeHooks.setUncaughtExceptionPreHandler(loggingHandler);
Thread.setDefaultUncaughtExceptionHandler(new KillApplicationHandler(loggingHandler));
//......
通过调用setDefaultUncaughtExceptionHandler,设置线程默认的异常捕获方法
ZygoteInit.nativeZygoteInit
nativeZygoteInit对应的JNI函数为com_android_internal_os_ZygoteInit_nativeZygoteInit
//frameworks\base\core\jni\AndroidRuntime.cpp
int register_com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env)
{
const JNINativeMethod methods[] = {
{ "nativeZygoteInit", "()V",
(void*) com_android_internal_os_ZygoteInit_nativeZygoteInit },
};
return jniRegisterNativeMethods(env, "com/android/internal/os/ZygoteInit",
methods, NELEM(methods));
}
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
gCurRuntime->onZygoteInit();
}
调用gCurRuntime的onZygoteInit函数,gCurRuntime是AppRuntime对象(AppRuntime继承自AndroidRuntime,在app_main.cpp的main函数中初始化),在onZygoteInit 函数中开启线程池
virtual void onZygoteInit()
{
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
proc->startThreadPool();
}
RuntimeInit.applicationInit
protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
//......
final Arguments args = new Arguments(argv);
// The end of of the RuntimeInit event (see #zygoteInit).
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
// Remaining arguments are passed to the start class's static main
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
通过findStaticMain查找 startClass中的main函数。追溯函数调用,这个startClass是 com.android.server.SystemServer
protected 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 });//查找main方法
} 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);
}
//......
return new MethodAndArgsCaller(m, argv);
}
封装成MethodAndArgsCaller 对象返回。所以前面提的返回的Runnable是什么类型,这里就知道了,是MethodAndArgsCaller类型
public MethodAndArgsCaller(Method method, String[] args) {
mMethod = method;
mArgs = args;
}
调用 Runnable的run方法即调用MethodAndArgsCaller的run方法
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);
}
}
然后就执行到了 com.android.server.SystemServer的 main方法
//frameworks\base\services\java\com\android\server\SystemServer.java
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
try {
t.traceBegin("InitBeforeStartServices");
//......
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
SystemServiceRegistry.sEnableServiceNotFoundWtf = true;
// Initialize native services.
System.loadLibrary("android_servers");
//......
// Initialize the system context.
createSystemContext();
//......
} finally {
t.traceEnd(); // InitBeforeStartServices
}
// Start services.
try {
t.traceBegin("StartServices");
startBootstrapServices(t);
startCoreServices(t);
startOtherServices(t);
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
t.traceEnd(); // StartServices
}
// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
run方法中主要完成以下工作
- 开启消息队列
- 加载libandroid_servers库
- 创建上下文对象
- 开启服务
总结
在SystemServer的启动过程中,主要完成以下工作
- 对特定目录下的包做odex
- 设置默认的异常捕获器
- 开启binder线程池
- 启动服务
try {
t.traceBegin("StartServices");
startBootstrapServices(t);
startCoreServices(t);
startOtherServices(t);
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
t.traceEnd(); // StartServices
}
标签:11,Runnable,ex,RuntimeInit,new,Android,main,android,SystemServer
From: https://blog.csdn.net/littleyards/article/details/136658830