system_server
The process is mainly used to create system services, AMS
, WMS
, PMS
and are all created by it. Specifically, SystemServer
after the process is created, it mainly does the following work:
- Start
Binder
the thread pool so that it can communicate with other processes; - Create
SystemServiceManager
, used to create, start and manage the life cycle of system services; - Start various system services;
1 Zygote
processing system_server
process
As mentioned in the Zygote process startup processZygoteInit.main
, in the method, the process forkSystemServer
is started by calling the method system_server
, some related timing diagrams:
ZygoteInit.forkSystemServer
The code looks like this:
// /frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
...
/* For child process 当前运行在 system_server 进程中 */
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
// 关闭 Zygote 进程创建的 Socket
zygoteServer.closeServerSocket(); // 1
return handleSystemServerProcess(parsedArgs); // 2
}
return null;
}
system_server
The process copies Zygote
the address space of the process, so it will also be Zygote
created by the process Socket
, which has no use Socket
for the process, so it needs to be closed at the comment . system_server
1
Socket
Next, 2
call handleSystemServerProcess
the method at the comment to start system_server
the process. handleSystemServerProcess
The code for the method looks like this:
// /frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
...
if (parsedArgs.mInvokeWith != null) {
...
} else {
createSystemServerClassLoader(); // 1
ClassLoader cl = sCachedSystemServerClassLoader;
if (cl != null) {
Thread.currentThread().setContextClassLoader(cl);
}
/*
* Pass the remaining arguments to SystemServer.
*/
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mRemainingArgs, cl); // 2
}
}
private static void createSystemServerClassLoader() {
if (sCachedSystemServerClassLoader != null) {
return;
}
final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
// TODO: Should we run optimization here?
if (systemServerClasspath != null) {
sCachedSystemServerClassLoader = createPathClassLoader(
systemServerClasspath, VMRuntime.SDK_VERSION_CUR_DEVELOPMENT);
}
}
1
Created at comment ClassLoader
. 2
The method is called at the comment ZygoteInit.zygoteInit
, and the code is as follows:
// /frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public static final Runnable zygoteInit(int targetSdkVersion, 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();
// 启动 Binder 线程池
ZygoteInit.nativeZygoteInit(); // 1
// 进入 system_server 的 main 方法
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader); // 2
}
1
Call the method at the comment ZygoteInit.nativeZygoteInit
, where Native
the code of the layer is called to start Binder
the thread pool, so that system_server
the process can use to Binder
communicate with other processes. The comment 2
is the method used to system_server
enter main
.
Described below
1 Start Binder
the thread pool
ZygoteInit.nativeZygoteInit()
is a Native
method, you must first understand its corresponding JNI
file, as follows:
// /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));
}
Through the array JNI
of methods
, it can be seen that nativeZygoteInit
the method corresponds to the function of JNI
the file :AndroidRuntime.cpp
com_android_internal_os_ZygoteInit_nativeZygoteInit
// /frameworks/base/core/jni/AndroidRuntime.cpp
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
gCurRuntime->onZygoteInit();
}
gCurRuntime
is AndroidRuntime
a pointer of type, specifically pointing to AndroidRuntime
a subclass of AppRuntime
and app_main.cpp
defined in . Next, look at AppRuntime.onZygoteInit
the method, the code is as follows:
// /frameworks/base/cmds/app_process/app_main.cpp
virtual void onZygoteInit()
{
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
proc->startThreadPool(); // 1
}
The code at comment 1
is used to start a Binder
thread pool so that system_server
processes can use to Binder
communicate with other processes. Therefore, we can know from here ZygoteInit.nativeZygoteInit()
that the function is mainly used to start Binder
the thread pool.
2 access SystemServer.main
method
View RuntimeInit.applicationInit
the source code of the method:
// /frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
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);
}
RuntimeInit.applicationInit
The method is mainly called in the method findStaticMain
:
// /frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
protected static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
Class<?> cl;
try {
// 通过反射得到 SystemServer 类
cl = Class.forName(className, true, classLoader); // 1
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
"Missing class when invoking static main " + className,
ex);
}
Method m;
try {
// 找到 SystemServer 的 main 方法
m = cl.getMethod("main", new Class[] {
String[].class }); // 2
} 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); // 3
}
1
The at the comment className
is com.android.server.SystemServer
, and the returned by reflection cl
is SystemServer
the class. 2
Find the method in the comments SystemServer.main
. Pass the method 3
found at the comment into the .main
MethodAndArgsCaller
// /frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public static void main(String argv[]) {
...
try {
...
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(); // 1
return;
}
}
...
} catch (Throwable ex) {
Log.e(TAG, "System zygote died with exception", ex);
throw ex;
} finally {
if (zygoteServer != null) {
zygoteServer.closeServerSocket();
}
}
...
}
From 1
the code in the comment, we can know that the object ZygoteInit.main
will be obtained in the method MethodAndArgsCaller
, and MethodAndArgsCaller.run()
the method will be called. MethodAndArgsCaller
is Zygote
a static inner class of :
// /frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
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 }); // 1
} 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);
}
}
}
1
The in the comment mMethod
refers to SystemServer.main
the method. After the method is called mMethod.invoke
, SystemServer.main
the method will also be called dynamically.
2 parsing system_server
process
Here is SystemServer.main
the method:
// /frameworks/base/services/java/com/android/server/SystemServer.java
public static void main(String[] args) {
new SystemServer().run();
}
SystemServer.main
Only the method is called in the method SystemServer().run()
:
// /frameworks/base/services/java/com/android/server/SystemServer.java
private void run() {
try {
...
// 创建消息 Looper
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
// Initialize native services. 加载了动态库 libandroid_servers.so
System.loadLibrary("android_servers"); // 1
...
// Initialize the system context. 创建系统的 Context
createSystemContext();
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext); // 2
mSystemServiceManager.setStartInfo(mRuntimeRestart, mRuntimeStartElapsedTime,
mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.get();
} finally {
traceEnd(); // InitBeforeStartServices
}
// Start services.
try {
traceBeginAndSlog("StartServices");
startBootstrapServices(); // 3 启动引导服务
startCoreServices(); // 4 启动核心服务
startOtherServices(); // 5 启动其他服务
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
traceEnd();
}
...
// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
1
The dynamic library is loaded in the comment libandroid_servers.so
. 2
Created in comments SystemServiceManager
, she will create, start and lifecycle manage system services. Reuse services such as start , , and so on in the method 3
at the comment . In the method at the comment then start , , and . The , , etc. services are started in the commented method .startBootstrapServices()
SystemServiceManager
ActivityManagerService
PowerManagerService
PackageManagerService
4
startCoreServices()
DropBoxManagerService
BatteryService
UsageStateService
WebViewUpdateService
5
startOtherServices()
CameraService
AlarmManagerService
VrManagerService
It can be seen from the comments 3
, 4
, that the official system services are divided into three types, namely boot services, core services and other services, among which other services are some non-important services that do not need to be started immediately. There are a total of multiple system services , some of which are as follows:5
100