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.h
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 server */
String args[] = { // 设置参数
"--setuid=1000",
"--setgid=1000",
"--setgroups=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_server", // 进程名是system_server
"--runtime-args",
"com.android.server.SystemServer",
};
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
parsedArgs = new ZygoteConnection.Arguments(args); // 将参数转化为Arguments格式
ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
/* Request to fork the system server process */
pid = Zygote.forkSystemServer( // // fork system_server进程
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
if (hasSecondZygote(abiList)) { // 判断是否存在第⼆个zygote需要启动,由于64位系统为了兼容32位应⽤程序,将同时启动zygote64和zygote,所以这⾥为true
waitForSecondaryZygote(socketName); // 等待zygote_secondary启动完成
}
handleSystemServerProcess(parsedArgs); // 完成system_server进程剩余的⼯作
}
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_server进程
uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);
// Enable tracing as soon as we enter the system_server.
if (pid == 0) {
Trace.setTracingEnabled(true); // 在system_server进程中重新使能Systrace追踪
}
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 server process %d has been created", pid);
// but it went unnoticed because 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_server刚创建就crash 的情况
ALOGE("System server process %d has died. Restarting Zygote!", pid);
RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!"); // 当system_server进程死亡后,需要重启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_se_info, jstring java_se_name,
bool is_system_server, jintArray fdsToClose,
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 closed immediately
DetachDescriptors(env, fdsToClose); // 关闭并清除⽂件描述符 // 由于fdsToClose为null,所以没有关闭任何⽂件描述符
// Keep capabilities across UID change, unless we're staying root.
if (uid != 0) {
EnableKeepCapabilities(env); // ⾮root⽤户,禁⽌动态改变进程的权限
}
DropCapabilitiesBoundingSet(env); // 取消进程的已有的Capabilities权限
bool use_native_bridge = !is_system_server && (instructionSet != NULL)
&& android::NativeBridgeAvailable();
if (use_native_bridge) {
ScopedUtfChars isa_string(env, instructionSet);
use_native_bridge = android::NeedsNativeBridge(isa_string.c_str());
}
if (use_native_bridge && dataDir == NULL) {
// dataDir should never be null if we need to use a native bridge.
// In general, dataDir will never be null for normal applications. It can only happen in
// special cases (for isolated processes which are not associated with any app). These are
use_native_bridge = false;
ALOGW("Native bridge will not be used because dataDir == NULL.");
}
if (!MountEmulatedStorage(uid, mount_external, use_native_bridge)) { // mount命名空间
ALOGW("Failed to mount emulated storage: %s", strerror(errno));
if (errno == ENOTCONN || errno == EROFS) {
/
/ 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 case, continue without external storage.
} else {
RuntimeAbort(env, __LINE__, "Cannot continue without emulated storage");
}
}
if (!is_system_server) {
int rc = createProcessGroup(uid, getpid()); // 对于⾮system_server⼦进程,则创建进程组
createprocessa
if (rc != 0) {
if (rc == -EROFS) {
ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?"); } else {
ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc));
}
}
}
SetGids(env, javaGids); // 设置组代码
SetRLimits(env, javaRlimits); // 设置资源limit // javaRlimits等于null,不限制
if (use_native_bridge) {
ScopedUtfChars isa_string(env, instructionSet);
ScopedUtfChars data_dir(env, dataDir);
android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str());
}
int rc = setresgid(gid, gid, gid); // 分别设置真实的,有效的和保存过的组标识号
if (rc == -1) {
ALOGE("setresgid(%d) failed: %s", gid, strerror(errno));
RuntimeAbort(env, __LINE__, "setresgid failed");
}
rc = setresuid(uid, uid, uid); // 分别设置真实的,有效的和保存过的⽤户标识号
if (rc == -1) {
ALOGE("setresuid(%d) failed: %s", uid, strerror(errno));
RuntimeAbort(env, __LINE__, "setresuid 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* se_info_c_str = NULL;
ScopedUtfChars* se_info = NULL;
if (java_se_info != NULL) {
se_info = new ScopedUtfChars(env, java_se_info);
se_info_c_str = se_info->c_str();
if (se_info_c_str == NULL) {
RuntimeAbort(env, __LINE__, "se_info_c_str == NULL");
}
}
const char* se_name_c_str = NULL;
ScopedUtfChars* se_name = NULL;
if (java_se_name != NULL) {
se_name = new ScopedUtfChars(env, java_se_name);
se_name_c_str = se_name->c_str();
if (se_name_c_str == NULL) {
RuntimeAbort(env, __LINE__, "se_name_c_str == NULL");
}
}
rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str); // 设置SELinux的domain上下⽂
if (rc == -1) {
ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid,
is_system_server, se_info_c_str, se_name_c_str);
RuntimeAbort(env, __LINE__, "selinux_android_setcontext failed");
}
// Make it easier to debug audit logs by setting the main thread's name to the
// nice name rather than "app_process".
if (se_info_c_str == NULL && is_system_server) {
se_name_c_str = "system_server";
}
if (se_info_c_str != NULL) {
SetThreadName(se_name_c_str);
}
delete se_info;
delete se_name;
UnsetSigChldHandler(); // 将⼦进程system_server的SIGCHLD信号的处理函数修改回系统默认函数
env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
is_system_server, instructionSet); // 调⽤zygote.callPostForkChildHooks()⽅法 // 完成⼀些运⾏时的后期⼯作 if (env->ExceptionCheck()) {
RuntimeAbort(env, __LINE__, "Error calling post fork hooks.");
}
} else if (pid > 0) { // 进⼊⽗进程,即zygote64进程
// the parent process
#ifdef ENABLE_SCHED_BOOST
// unset scheduler knob
SetForkLoad(false);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论