Android 源码学习 SystemServer启动原理
望舒课堂 SystemServer进程启动原理学习记录整理。 参考文章: Android系统启动流程(三)解析SyetemServer进程启动过程
SystemServer简介
SystemServer是Android系统的核心之一,大部分Android提供的服务都在该进程中。
Zygote处理SystemServer进程
zygote处理SystemServer时序图
ZygoteInit
AppRuntime
RuntimeInit
MethodAndArgsCaller
SystemServer
main
forkSystemServer
handleSystemServerProcess
zygoteInit
onZygoteInit
applicationInit
findStaticMain
new
new
zygoteInit调用回调的run
run
main
ZygoteInit
AppRuntime
RuntimeInit
MethodAndArgsCaller
SystemServer
ZygoteInit.java
/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java zygoteInit的关键代码:
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);
......
}
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
if (parsedArgs.mInvokeWith != null) {
......
} else {
ClassLoader cl = null;
if (systemServerClasspath != null) {
cl = createPathClassLoader(systemServerClasspath, parsedArgs.mTargetSdkVersion);
Thread.currentThread().setContextClassLoader(cl);
}
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mDisabledCompatChanges,
parsedArgs.mRemainingArgs, cl);
}
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();
return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
classLoader);
}
private static final native void nativeZygoteInit();
}
nativeZygoteInit();调用的是native方法,位于AppRuntime /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 AndroidRuntime* gCurRuntime = NULL;
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
gCurRuntime->onZygoteInit();
}
onZygoteInit 是虚方法 具体实现在AndroidRuntime的子类AppRuntime中
/frameworks/base/core/jni/include/android_runtime/AndroidRuntime.h
virtual void onZygoteInit() { }
具体代码还是在app_main中 /frameworks/base/cmds/app_process/app_main.cpp
class AppRuntime : public AndroidRuntime{
......
virtual void onZygoteInit()
{
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
proc->startThreadPool();
}
......
}
RuntimeInit.java
/frameworks/base/core/java/com/android/internal/os/RuntimeInit.java ZygoteInit.zygoteInit 方法 返回RuntimeInit.applicationInit
protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
......
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
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 });
} 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);
}
return new MethodAndArgsCaller(m, argv);
}
static class MethodAndArgsCaller implements Runnable {
private final Method mMethod;
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 执行回调
/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public static void main(String argv[]) {
......
zygoteServer = new ZygoteServer(isPrimaryZygote);
if (startSystemServer) {
Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
if (r != null) {
r.run();
return;
}
Log.i(TAG, "Accepting command socket connections");
caller = zygoteServer.runSelectLoop(abiList);
} catch (Throwable ex) {
Log.e(TAG, "System zygote died with exception", ex);
throw ex;
} finally {
if (zygoteServer != null) {
zygoteServer.closeServerSocket();
}
}
if (caller != null) {
caller.run();
}
}
}
解析SystemServer进程
/frameworks/base/services/java/com/android/server/SystemServer.java
经过ZygoteInit启动SystemServer启动,进入SystemServer的main方法 关键方法:
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
......
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
......
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();
}
......
}
系统服务
列举部分系统服务。 表格截取刘望舒的文章。
| centered 文本居中 | right-aligned 文本居右 |
引导服务 | 作用 |
---|
Installer | 系统安装apk时的一个服务类,启动完成Installer服务之后才能启动其他的系统服务 | ActivityManagerService | 负责四大组件的启动、切换、调度。 | PowerManagerService | 计算系统中和Power相关的计算,然后决策系统应该如何反应 | LightsService | 管理和显示背光LED | DisplayManagerService | 用来管理所有显示设备 | UserManagerService | 多用户模式管理 | SensorService | 为系统提供各种感应器服务 | PackageManagerService | 用来对apk进行安装、解析、删除、卸载等等操作 |
核心服务 | 作用 |
---|
BatteryService | 管理电池相关的服务 | UsageStatsService | 收集用户使用每一个APP的频率、使用时常 | WebViewUpdateService | WebView更新服务 |
其他服务 | 作用 |
---|
CameraService | 摄像头相关服务 | AlarmManagerService | 全局定时器管理服务 | InputManagerService | 管理输入事件 | WindowManagerService | 窗口管理服务 | VrManagerService | VR模式管理服务 | BluetoothService | 蓝牙管理服务 | NotificationManagerService | 通知管理服务 | DeviceStorageMonitorService | 存储相关管理服务 | LocationManagerService | 定位管理服务 | AudioService | 音频相关管理服务 |
SystemServiceManager.java
SystemServer里调用SystemServiceManager的startService来启动相应服务 例如DisplayManagerService
t.traceBegin("StartDisplayManager");
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
t.traceEnd();
SystemServiceManager
/frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
关键代码:
public void startService(@NonNull final SystemService service) {
mServices.add(service);
long time = SystemClock.elapsedRealtime();
try {
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
总结
SystemServer进程被创建后,主要做了如下工作:
- 启动Binder线程池,这样就可以与其他进程进行通信
- 创建SystemServiceManager用于对系统的服务创建、启动和生命周期管理。
- 启动各种系统服务
|