基于安卓 12 源码分析
相关类:
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
frameworks/base/core/java/com/android/internal/os/Zygote.java
frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
frameworks/base/services/java/com/android/server/SystemServer.java
frameworks/base/core/jni/AndroidRuntime.cpp
frameworks/base/cmds/app_process/app_main.cpp
frameworks/base/core/java/android/os/ServiceManager.java
frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
在 ZygoteInit.java 的 main 方法中,启动了 SystemServer 进程:
java
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;
}
}
forkSystemServer 源码:
java
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
// 定义 system_server 进程所需的能力(Linux capabilities)
// 这些能力决定了该进程可以执行哪些特权操作
long capabilities = posixCapabilitiesAsBits(
OsConstants.CAP_IPC_LOCK,// 锁定内存,防止被换出
OsConstants.CAP_KILL,
OsConstants.CAP_NET_ADMIN,
OsConstants.CAP_NET_BIND_SERVICE,
OsConstants.CAP_NET_BROADCAST,// 发送广播包
OsConstants.CAP_NET_RAW,
OsConstants.CAP_SYS_MODULE,
OsConstants.CAP_SYS_NICE,
OsConstants.CAP_SYS_PTRACE,
OsConstants.CAP_SYS_TIME,// 修改系统时间
OsConstants.CAP_SYS_TTY_CONFIG,
OsConstants.CAP_WAKE_ALARM,// 设置唤醒闹钟
OsConstants.CAP_BLOCK_SUSPEND
);
/* Containers run without some capabilities, so drop any caps that are not available. */
StructCapUserHeader header = new StructCapUserHeader(
OsConstants._LINUX_CAPABILITY_VERSION_3, 0);
StructCapUserData[] data;
try {
data = Os.capget(header);
} catch (ErrnoException ex) {
throw new RuntimeException("Failed to capget()", ex);
}
capabilities &= ((long) data[0].effective) | (((long) data[1].effective) << 32);
/* Hardcoded command line to start the system server */
// 构造启动 system_server 的参数(硬编码,不可外部修改)
String[] args = {
"--setuid=1000", // UID 1000 = system 用户
"--setgid=1000", // GID 1000 = system 组
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,"
+ "1024,1032,1065,3001,3002,3003,3006,3007,3009,3010,3011,3012",
"--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_server",
"--runtime-args",
"--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
"com.android.server.SystemServer",// 要启动的主类
};
ZygoteArguments parsedArgs;
int pid;
try {
// 将字符串参数解析为 ZygoteArguments 对象
ZygoteCommandBuffer commandBuffer = new ZygoteCommandBuffer(args);
try {
parsedArgs = ZygoteArguments.getInstance(commandBuffer);
} catch (EOFException e) {
throw new AssertionError("Unexpected argument error for forking system server", e);
}
commandBuffer.close();
Zygote.applyDebuggerSystemProperty(parsedArgs);
Zygote.applyInvokeWithSystemProperty(parsedArgs);
if (Zygote.nativeSupportsMemoryTagging()) {
/* The system server has ASYNC MTE by default, in order to allow
* system services to specify their own MTE level later, as you
* can't re-enable MTE once it's disabled. */
String mode = SystemProperties.get("arm64.memtag.process.system_server", "async");
if (mode.equals("async")) {
parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_ASYNC;
} else if (mode.equals("sync")) {
parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_SYNC;
} else if (!mode.equals("off")) {
/* When we have an invalid memory tag level, keep the current level. */
parsedArgs.mRuntimeFlags |= Zygote.nativeCurrentTaggingLevel();
Slog.e(TAG, "Unknown memory tag level for the system server: "" + mode + """);
}
} else if (Zygote.nativeSupportsTaggedPointers()) {
/* Enable pointer tagging in the system server. Hardware support for this is present
* in all ARMv8 CPUs. */
parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_TBI;
}
// ...
// 调用 native 层 fork 出 system_server 进程
pid = Zygote.forkSystemServer(
parsedArgs.mUid, parsedArgs.mGid,
parsedArgs.mGids,
parsedArgs.mRuntimeFlags,
null,
parsedArgs.mPermittedCapabilities,
parsedArgs.mEffectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
// fork 返回后,区分父子进程
// pid == 0 表示当前在 **子进程(system_server)** 中运行
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
// 关闭 Zygote 的 socket(子进程不需要监听新请求)
zygoteServer.closeServerSocket();
// 真正进入 SystemServer.main(),启动各种系统服务。
return handleSystemServerProcess(parsedArgs);
}
return null;
}
Zygote.forkSystemServer 源码:
frameworks/base/core/java/com/android/internal/os/Zygote.java
java
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;
}
private static native int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);
nativeForkSystemServer 是实现在 以下文件中:
frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
前景回顾:
在前面分析 AndroidRuntime::start 代码时,我们知道 startReg 就是注册 JNI 方法 的
c++
// frameworks/base/core/jni/AndroidRuntime.cpp
void AndroidRuntime::start(...) {
...
JniInvocation jni_invocation;
jni_invocation.Init(NULL);
JNIEnv* env;
if (startVm(&mJavaVM, &env, zygote) != 0) {
return;
}
...
// 注册 JNI 方法,包括 com_android_internal_os_Zygote.cpp 里的 native 方法
if (startReg(env) < 0) {
return;
}
...
}
startReg(env)
会调用 register_jni_procs 加载一系列 cpp 文件 其中就包括 register_com_android_internal_os_Zygote:
c++
// frameworks/base/core/jni/AndroidRuntime.cpp
int register_jni_procs(...) {
...
REG_JNI(register_com_android_internal_os_Zygote),
...
}
nativeForkSystemServer 关键源码:
c++
// com_android_internal_os_Zygote.cpp
static jint com_android_internal_os_Zygote_nativeForkSystemServer(
JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
jint runtime_flags, jobjectArray rlimits,
jlong permittedCapabilities, jlong effectiveCapabilities) {
pid_t pid = zygote::ForkCommon(env, /*is_system_server=*/true, ...);
if (pid == 0) {
// 子进程逻辑:进入 system_server
} else if (pid > 0) {
// 父进程逻辑
}
// 返回 pid 给 Java 层
return pid;
}
可以看到 nativeForkSystemServer
最终会调用 ForkCommon()
→ 里面再去调用 Linux 的 fork()
系统调用。
呃.. 分析岔劈了.......
在安卓 10 之前,启动系统服务是通过 ZygoteInit
中抛出一个特殊的异常 ZygoteInit.MethodAndArgsCaller
,最后在 catch
里调用 main()
。到 Android 12 已经变成 直接 return Runnable, 所以应该去找到这个 Runnable。
在 ZygoteInit.java 的 forkSystemServer 方法中,SystemServer 进程调用了 handleSystemServerProcess 去启动 系统服务:
java
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
// ...
/* For child process */
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
zygoteServer.closeServerSocket();
return handleSystemServerProcess(parsedArgs);
}
return null;
}
接着在 handleSystemServerProcess 中 调用 zygoteInit:
java
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
//...
/*
* Pass the remaining arguments to SystemServer.
*/
// 启动 runtime
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mDisabledCompatChanges,
parsedArgs.mRemainingArgs, cl);
}
/* should never reach here */
}
继续调用 RuntimeInit.applicationInit:
java
public static 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、signal 等 native 初始化(对应 app_main.cpp 的 onZygoteInit)
return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
classLoader);
}
然后来到 RuntimeInit.java 中的 applicationInit:
frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
java
protected static Runnable applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
final Arguments args = new Arguments(argv);
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
这里会解析参数,找到启动类:com.android.server.SystemServer
,记住这里的 所有参数就是上面的 构造启动 system_server 的参数,包括写死的 com.android.server.SystemServer
findStaticMain():
java
private static Runnable findStaticMain(String className, String[] argv, ClassLoader classLoader) {
Class<?> cl = Class.forName(className, true, classLoader);
Method m = cl.getMethod("main", new Class[] { String[].class });
return new MethodAndArgsCaller(m, argv);
}
构造一个 MethodAndArgsCaller
(实现了 Runnable) ,持有 SystemServer.main()
的反射方法。
MethodAndArgsCaller:
java
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 (InvocationTargetException ex) {
...
}
}
}
回到 ZygoteInit.main()
:
java
Runnable r = forkSystemServer(...);
if (r != null) {
r.run(); // <--- 这里直接执行 SystemServer.main()
}
至此调用链为:
scss
ZygoteInit.main() [frameworks/base/core/java/com/android/internal/os/ZygoteInit.java]
-> forkSystemServer()
-> handleSystemServerProcess()
-> ZygoteInit.zygoteInit()
-> RuntimeInit.applicationInit()
-> RuntimeInit.findStaticMain()
-> new MethodAndArgsCaller(SystemServer.main)
-> r.run() // MethodAndArgsCaller.run()
-> SystemServer.main() [frameworks/base/services/java/com/android/server/SystemServer.java]
SystemServer.main():
frameworks/base/services/java/com/android/server/SystemServer.java
java
public static void main(String[] args) {
new SystemServer().run();
}
java
private void run() {
TimingsTraceAndSlog t = new TimingsTraceAndSlog();
try {
//...
// 主线程 looper
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
//...
// Initialize native services.
System.loadLibrary("android_servers");
//...
// 初始化系统上下文环境
createSystemContext();
//...
// 创建系统服务管理
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
mDumper.addDumpable(mSystemServiceManager);
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(); // StartServices
}
//...
// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
这个 run()
方法是 system_server
进程启动后执行的主逻辑,负责:
- 初始化系统运行环境
- 启动数百个系统服务(如 ActivityManager、PackageManager、PowerManager 等)
- 建立主线程 Looper 循环,使系统持续运行
还有一个重要的地方,就是 binder 线程池的启动,启动binder 线程池后SystemServer进程就可以与其他进程进行通信了,在之前的安卓源码中,binder 线程池的启动都是放在启动 SystemServer 时创建的,而安卓 12 是在
Zygote
初始化阶段启动!
流程如下:
scss
ZygoteInit.java
↓ nativeZygoteInit() (JNI)
↓
AndroidRuntime.cpp
↓ com_android_internal_os_ZygoteInit_nativeZygoteInit()
↓ gCurRuntime->onZygoteInit() ← 虚函数调用
↓
AppRuntime.cpp (app_main.cpp)
↓ AppRuntime::onZygoteInit()
↓ ProcessState::self()->startThreadPool()
↓
Binder 驱动开始监听 /dev/binder
SystemServiceManager 和 ServiceManager:
在SystemServer 中创建了这两个类,使用 如下:
java
SystemServiceManager.startService()
ServiceManager.addService()
SystemServiceManager 功能是在 SystemServer 进程内部启动一个服务对象,让它运行起来,具备自己的逻辑。
ServiceManager 功能是注册 Binder IPC 接口 ,让其他进程能通过 binder
与该服务交互。
系统服务启动后都会交给 ServiceManager 来管理,另外ServiceManager
是 Android 的系统服务目录,SystemServer
把它创建的服务注册到 ServiceManager
,以便其他进程通过名字找到并通信。管理着 SystemServer
对外暴露的所有服务入口。
最后,SystemServer进程被创建后,主要做了如下工作:
- 创建SystemServiceManager,其用于对系统的服务进行创建、启动和生命周期管理。
- 启动各种系统服务。