AndroidSystemServer进程源码分析上
⼀ System Server
System Server是Zygote启动的第⼀个进程,它的核⼼功能是启动和管理Android系统的各类服务。
1.0 startSystemServer
private static boolean startSystemServer(String abiList, String socketName) // abiList为arm64-v8a,socketName为zygote
throws MethodAndArgsCaller, RuntimeException {
long capabilities = posixCapabilitiesAsBits( // Linux的Capabilities安全机制,可参考include/uapi/linux/capability.hadapted
OsConstants.CAP_BLOCK_SUSPEND, // 允许阻⽌系统挂起
OsConstants.CAP_KILL, // 允许对不属于⾃⼰的进程发送信号
OsConstants.CAP_NET_ADMIN, // 允许执⾏⽹络管理任务
OsConstants.CAP_NET_BIND_SERVICE, // 允许绑定到⼩于1024的端⼝
OsConstants.CAP_NET_BROADCAST, // 允许⽹络⼴播和多播访问
OsConstants.CAP_NET_RAW, // 允许使⽤原始套接字
OsConstants.CAP_SYS_MODULE, // 允许插⼊和删除内核模块
OsConstants.CAP_SYS_NICE, // 允许提升优先级及设置其他进程的优先级
OsConstants.CAP_SYS_RESOURCE, // 忽略资源限制
OsConstants.CAP_SYS_TIME, // 允许改变系统时钟
OsConstants.CAP_SYS_TTY_CONFIG // 允许配置TTY设备
);
/* Hardcoded command line to start the system rver */
String args[] = { // 设置参数
"--tuid=1000",
"--tgid=1000",
"--tgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1032,3001,3002,3003,3006,3007,3009,3010", "--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_rver", // 进程名是system_rver
"--runtime-args",
"com.android.rver.SystemServer",
};
ZygoteConnection.Arguments pardArgs = null;
int pid;
try {
pardArgs = new ZygoteConnection.Arguments(args); // 将参数转化为Arguments格式
ZygoteConnection.applyDebuggerSystemProperty(pardArgs);
ZygoteConnection.applyInvokeWithSystemProperty(pardArgs);
/* Request to fork the system rver process */
pid = Zygote.forkSystemServer( // // fork system_rver进程
pardArgs.uid, pardArgs.gid,
pardArgs.gids,
pardArgs.debugFlags,
null,
pardArgs.permittedCapabilities,
pardArgs.effectiveCapabilities);
cnn听力下载
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
if (hasSecondZygote(abiList)) { // 判断是否存在第⼆个zygote需要启动,由于64位系统为了兼容32位应⽤程序,将同时启动zygote64和zygote,所以这⾥为true
waitForSecondaryZygote(socketName); // 等待zygote_condary启动完成
}
handleSystemServerProcess(pardArgs); // 完成system_rver进程剩余的⼯作
}
return true;
}
⼆ forkSystemServer
2.0 forkSystemServer
public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
VM_HOOKS.preFork();
int pid = nativeForkSystemServer( // 调⽤native⽅法fork system_rver进程
uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);
// Enable tracing as soon as we enter the system_rver.
if (pid == 0) {
Trace.tTracingEnabled(true); // 在system_rver进程中重新使能Systrace追踪cnki翻译
}
VM_HOOKS.postForkCommon();
return pid;
}
public void preFork() {
Daemons.stop(); // 停⽌HeapTaskDaemon、ReferenceQueueDaemon、FinalizerDaemon、FinalizerWatchdogDaemon等四个Daemon⼦线程
waitUntilAllThreadsStopped(); // 等待所有⼦线程结束
token = nativePreFork(); // 完成⼀些运⾏时fork前期⼯作
}
public void postForkCommon() {
Daemons.start(); // 启动HeapTaskDaemon、ReferenceQueueDaemon、FinalizerDaemon、FinalizerWatchdogDaemon等四个Daemon⼦线程
}
2.1 com_android_internal_os_Zygote_nativeForkSystemServer
nativeForkSystemServer对应JNI函数是com_android_internal_os_Zygote_nativeForkSystemServer
static jint com_android_internal_os_Zygote_nativeForkSystemServer(
JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
jlong effectiveCapabilities) {
pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
debug_flags, rlimits,
permittedCapabilities, effectiveCapabilities,
MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
NULL, NULL); // fork⼦进程
if (pid > 0) { // fork返回⼤于0,说明在⽗进程(zygote64)中
// The zygote process checks whether the child process has died or not.
ALOGI("System rver process %d has been created", pid);
// but it went unnoticed becau we haven't published its pid yet. So
// we recheck here just to make sure that all is well.
int status;
if (waitpid(pid, &status, WNOHANG) == pid) { // 等待⼦进程退出,WNOHANG表⽰⾮阻塞 // 这⾥是处理system_rver刚创建就crash 的情况
ALOGE("System rver process %d has died. Restarting Zygote!", pid);
RuntimeAbort(env, __LINE__, "System rver process has died. Restarting Zygote!"); // 当system_rver进程死亡后,需要重启zygote进程
}
}
return pid;
}
2.2 ForkAndSpecializeCommon
static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
jint debug_flags, jobjectArray javaRlimits,
jlong permittedCapabilities, jlong effectiveCapabilities,
jint mount_external,
jstring java__info, jstring java__name,
bool is_system_rver, jintArray fdsToClo,
jstring instructionSet, jstring dataDir) {
SetSigChldHandler(); // 设置SIGCHLD信号处理函数 // ⼦进程的SIGCHLD信号处理函数会在后⾯改回系统默认函数
#ifdef ENABLE_SCHED_BOOST
SetForkLoad(true);
#endif
pid_t pid = fork(); // fork⼦进程
委托翻译
if (pid == 0) { // 进⼊⼦进程
// The child process.
gMallocLeakZygoteChild = 1;
// Clean up any descriptors which must be clod immediately
DetachDescriptors(env, fdsToClo); // 关闭并清除⽂件描述符 // 由于fdsToClo为null,所以没有关闭任何⽂件描述符
// Keep capabilities across UID change, unless we're staying root.
if (uid != 0) {
EnableKeepCapabilities(env); // ⾮root⽤户,禁⽌动态改变进程的权限
}principle是什么意思
DropCapabilitiesBoundingSet(env); // 取消进程的已有的Capabilities权限
bool u_native_bridge = !is_system_rver && (instructionSet != NULL)
&& android::NativeBridgeAvailable();
if (u_native_bridge) {
穿普拉达的女王ScopedUtfChars isa_string(env, instructionSet);
u_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
}
if (u_native_bridge && dataDir == NULL) {
// dataDir should never be null if we need to u a native bridge.
// In general, dataDir will never be null for normal applications. It can only happen in
// special cas (for isolated process which are not associated with any app). The are
u_native_bridge = fal;
ALOGW("Native bridge will not be ud becau dataDir == NULL.");
}
if (!MountEmulatedStorage(uid, mount_external, u_native_bridge)) { // mount命名空间
classic是什么意思
ALOGW("Failed to mount emulated storage: %s", strerror(errno));
if (errno == ENOTCONN || errno == EROFS) {
toefl官网/
/ When device is actively encrypting, we get ENOTCONN here
// since FUSE was mounted before the framework restarted.
// When encrypted device is booting, we get EROFS since
// FUSE hasn't been created yet by init.
// In either ca, continue without external storage.
} el {
RuntimeAbort(env, __LINE__, "Cannot continue without emulated storage");
}
}
if (!is_system_rver) {
int rc = createProcessGroup(uid, getpid()); // 对于⾮system_rver⼦进程,则创建进程组
if (rc != 0) {
if (rc == -EROFS) {
ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?"); } el {
ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc));
}
}
}
SetGids(env, javaGids); // 设置组代码
SetRLimits(env, javaRlimits); // 设置资源limit // javaRlimits等于null,不限制
if (u_native_bridge) {
ScopedUtfChars isa_string(env, instructionSet);
ScopedUtfChars data_dir(env, dataDir);
android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
}
int rc = tresgid(gid, gid, gid); // 分别设置真实的,有效的和保存过的组标识号
if (rc == -1) {
ALOGE("tresgid(%d) failed: %s", gid, strerror(errno));
RuntimeAbort(env, __LINE__, "tresgid failed");
}
rc = tresuid(uid, uid, uid); // 分别设置真实的,有效的和保存过的⽤户标识号
if (rc == -1) {
ALOGE("tresuid(%d) failed: %s", uid, strerror(errno));
RuntimeAbort(env, __LINE__, "tresuid failed");
}
if (NeedsNoRandomizeWorkaround()) {
// Work around ARM kernel ASLR lossage (b/5817320).
int old_personality = personality(0xffffffff);
int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
if (new_personality == -1) {
ALOGW("personality(%d) failed: %s", new_personality, strerror(errno));
}
SetCapabilities(env, permittedCapabilities, effectiveCapabilities); // 配置新的Capabilities权限
SetSchedulerPolicy(env); // 设置调度策略
const char* _info_c_str = NULL;
ScopedUtfChars* _info = NULL;
if (java__info != NULL) {
_info = new ScopedUtfChars(env, java__info);
_info_c_str = _info->c_str();dusk
if (_info_c_str == NULL) {
RuntimeAbort(env, __LINE__, "_info_c_str == NULL");
}
}
const char* _name_c_str = NULL;
ScopedUtfChars* _name = NULL;
if (java__name != NULL) {
_name = new ScopedUtfChars(env, java__name);
_name_c_str = _name->c_str();
if (_name_c_str == NULL) {
RuntimeAbort(env, __LINE__, "_name_c_str == NULL");
}
}
rc = linux_android_tcontext(uid, is_system_rver, _info_c_str, _name_c_str); // 设置SELinux的domain上下⽂
if (rc == -1) {
ALOGE("linux_android_tcontext(%d, %d, \"%s\", \"%s\") failed", uid,
is_system_rver, _info_c_str, _name_c_str);
RuntimeAbort(env, __LINE__, "linux_android_tcontext failed");
}
// Make it easier to debug audit logs by tting the main thread's name to the
// nice name rather than "app_process".
if (_info_c_str == NULL && is_system_rver) {
_name_c_str = "system_rver";
}
if (_info_c_str != NULL) {
SetThreadName(_name_c_str);
}
delete _info;
delete _name;
UntSigChldHandler(); // 将⼦进程system_rver的SIGCHLD信号的处理函数修改回系统默认函数
env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
is_system_rver, instructionSet); // 调⽤zygote.callPostForkChildHooks()⽅法 // 完成⼀些运⾏时的后期⼯作 if (env->ExceptionCheck()) {
RuntimeAbort(env, __LINE__, "Error calling post fork hooks.");
}
polybag
} el if (pid > 0) { // 进⼊⽗进程,即zygote64进程
// the parent process
#ifdef ENABLE_SCHED_BOOST
// unt scheduler knob
SetForkLoad(fal);