背景
在zygote进程初始化的过程中,除了启动虚拟机、注册JNI、预加载类和资源、创建socket服务外,还会fork()出SystemServer进程。
这个过程可以大体分为两个部分:
- SystemServer的拉起
- SystemServer的初始化阶段一
- SystemServer的初始化阶段二
一、SystemServer的拉起
Zygote进程对SystemServer的fork()逻辑:
...
// 1 开始创建
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();
//2 创建成功 继续执行剩余初始化工作
return handleSystemServerProcess(parsedArgs);
}
...
1.1 Zygote.forkSystemServer()
static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
ZygoteHooks.preFork();
int pid = nativeForkSystemServer(
uid, gid, gids, runtimeFlags, rlimits,
permittedCapabilities, effectiveCapabilities);
// Set the Java Language thread priority to the default value for new apps.
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
ZygoteHooks.postForkCommon();
return pid;
}
职责:
在Zygote.java类中调用了native方法:nativeForkSystemServer() 来创建SystemServer进程。
1.2 nativeForkSystemServer()
对应native层的jni方法:
frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
static jint com_android_internal_os_Zygote_nativeForkSystemServer(
JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
jlong effective_capabilities) {
...
// 1 内部调用了fork()方法 创建进程
pid_t pid = zygote::ForkCommon(env, true,
fds_to_close,
fds_to_ignore,
true);
if (pid == 0) {
System server 进程创建成功
// System server prcoess does not need data isolation so no need to
// know pkg_data_info_list.
SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits, permitted_capabilities,
effective_capabilities, MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
false, nullptr, nullptr, /* is_top_app= */ false,
/* pkg_data_info_list */ nullptr,
/* allowlisted_data_info_list */ nullptr, false, false);
} else if (pid > 0) {
...
}
return pid;
}
职责:
内部通过fork()创建出了system server 进程,返回进程id。
至此,system server进程才被创建出来,接下来就是真正初始的工作了。
二、SystemServer的初始化阶段一
2.1 handleSystemServerProcess()
创建完成后,我们又回到ZygoteInit.java类中,继续完成剩余的工作。
/**
* Finish remaining work for the newly forked system server process.
*/
为新创建的systemServer进程 完成剩余的初始化工作
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
...
} else {
ClassLoader cl = null;
if (systemServerClasspath != null) {
//根据systemServer的类路径, 创建classloader
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);
}
}
职责:
- 创建classloader设置给当前线程。 当前线程是system server进程的主线程。
- 调用
ZygoteInit.zygoteInit()
2.2 zygoteInit()
[ ZygoteInit.java]
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);
}
2.3 commonInit()
[RuntimeInit.java]
protected static final void commonInit() {
if (DEBUG) Slog.d(TAG, "Entered RuntimeInit!");
// 给VM中的所以线程设置异常捕获 当然app可以替换
LoggingHandler loggingHandler = new LoggingHandler();
RuntimeHooks.setUncaughtExceptionPreHandler(loggingHandler);
Thread.setDefaultUncaughtExceptionHandler(new KillApplicationHandler(loggingHandler));
// 设置时区信息
RuntimeHooks.setTimeZoneIdSupplier(() -> SystemProperties.get("persist.sys.timezone"));
//重置log配置
LogManager.getLogManager().reset();
new AndroidConfig();
//设置HttpURLConnection 的http 客户端
String userAgent = getDefaultUserAgent();
System.setProperty("http.agent", userAgent);
// 设置socket的tag,用来流量监控
NetworkManagementSocketTagger.install();
...
initialized = true;
}
2.4 nativeZygoteInit()
这是一个jni方法,位于: [frameworks/base/core/jni/AndroidRuntime.cpp]
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
gCurRuntime->onZygoteInit();
}
继续看AndroidRuntime.cpp 的 onZygoteInit()
virtual void onZygoteInit()
{
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
// 开启了Binder线程
proc->startThreadPool();
}
ProcessState是单例模式,内部通过open()打开/dev/binder驱动设备,利用mmap()把驱动设备和内核的内存空间建立映射关系。binder驱动的fd值赋值给ProcessState中的mDriver成员,用来与binder驱动进行交互。此处,开启了一个binder线程,通过talkWitchDriver()不断的交互。
2.5 applicationInit()
protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
// If the application calls System.exit(), terminate the process
// immediately without running any shutdown hooks. It is not possible to
// shutdown an Android application gracefully. Among other things, the
// Android runtime shutdown hooks close the Binder driver, which can cause
// leftover running threads to crash before the process actually exits.
nativeSetExitWithoutCleanup(true);
VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);
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():
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);
}
...
return new MethodAndArgsCaller(m, argv);
}
2.6 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 {
// 通过反射调用了 SystemServer.java类的main方法
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.java类的main()方法。
第一阶段主要内容总结:
- 创建classLoader
- 通用init工作: 设置线程异常捕获,设置时区、设置http user-client、设置socket的tag监控流量等。
开启binder线程 重要!!- 反射调用SystemServer的main()方法
至此,第一阶段的初始化工作完成,接着进入核心阶段。
三、SystemServer的初始化阶段二
首先看SystemServer.java的main()方法:
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
...
// 1 把当前线程作为主线程,绑定looper
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
SystemServiceRegistry.sEnableServiceNotFoundWtf = true;
// 加载android_servers.so库
System.loadLibrary("android_servers");
// 初始化系统上下文
createSystemContext();
...
// 创建系统服务的管理者
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.start();
...
// Start services.
//启动服务
try {
t.traceBegin("StartServices");
startBootstrapServices(t);
startCoreServices(t);
startOtherServices(t);
}
...
// 初始化VM的严格模式
StrictMode.initVmDefaults(null);
// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
主要职责:
- 初始化主线程looper
- 加载android_servers.so库
- 创建系统上下文
- 创建serviceManager对象,并加载本地服务
- 启动服务 如AMS PMS等
3.1 createSystemContext()
private void createSystemContext() {
// 内部会创建ActivityThread对象:
//“ActivityThread thread = new ActivityThread();
//thread.attach(true, 0);”
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
这个过程会创建很多对象: ActivityThread,Instrumentation, ContextImpl,LoadedApk,Application。如下:
public static ActivityThread systemMain() {
// The system process on low-memory devices do not get to use hardware
// accelerated drawing, since this can add too much overhead to the
// process.
ActivityThread thread = new ActivityThread();
// 这里
thread.attach(true, 0);
return thread;
}
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
...
} else {
// Don't set application object here -- if the system crashes,
// we can't display an alert, we just want to die die die.
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
}
3.2 SystemServiceManager
SystemServiceManager管理者service服务的生命周期,LocalServices类维护了全局的ArrayMap容器来存储SystemServiceManager对象。
3.3 startBootstrapServices(t)
这个方法开启的都是非常关键性的服务,且相互依赖性强,因此,放在一起启动。
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
...
Installer installer = mSystemServiceManager.startService(Installer.class);
...
// Activity manager runs the show.
//Activity 管理
// TODO: Might need to move after migration to WM.
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
//AMS
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();
...
//PMS
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
...
mActivityManagerService.initPowerManagement();
...
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
//PMS
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
.....
}
以上只列出了部分系统服务:AMS、PowerManagerService、PackageManagerService、Sensor等。
3.4 startCoreServices(t)
...
mSystemServiceManager.startService(BatteryService.class);
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
// 跟踪binder调用中的CPU耗时
mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);
//GPU和GPU驱动service
t.traceBegin("GpuService");
mSystemServiceManager.startService(GpuService.class);
...
3.5 startOtherServices(t)
inputManager = new InputManagerService(context);
wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
mActivityManagerService.setWindowManager(wm);
wm.onInitReady();
mDisplayManagerService.windowManagerAndInputReady();
mActivityManagerService.systemReady{
...
}
开启一系列的服务,且最终以XXXService.systemReady()结尾,如 AMS.systemReady()。至此,system server的所以服务都在主线程启动了,随后进入loop等待消息。
四、总结
system server进程从zygote进程fork()出来后的初始化工作可大体分为两个部分:
-
native部分通过jni方法创建binder线程,用于响应其他进程的binder请求。 -
java部分通过反射调用SystemServer.java类的main()方法- 创建
ActivityThread、ContextImpl、Application、Instrumentation、LoadApk对象, 同时回调进程Application的onCreate()方法(每个进程都有的呀,很nice) - 开启Android系统需要的各种服务
- 创建
looper对象,进入循环
- 创建
鉴于个人能力有限,如有错误之处,还望指正。
参考: