private static boolean startSystemServer(String abiList, String socketName)
throws MethodAndArgsCaller, RuntimeException {
...
//参数准备
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",
"--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_server",
"--runtime-args",
"com.android.server.SystemServer",
};
ZygoteConnection.Arguments parsedArgs = null;
...
try {
//解析参数生成目标格式
parsedArgs = new ZygoteConnection.Arguments(args);
...
//fork SystemServer进程
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
//若创建的进程为子进程
if (pid == 0) {
if (hasSecondZygote(abiList)) {
//等待第二个进程创建完成
waitForSecondaryZygote(socketName);
}
//完成SystemServer剩余的工作
handleSystemServerProcess(parsedArgs);
}
return true;
}
//第二步
public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
VM_HOOKS.preFork();
//会调用com_android_internal_os_Zygote.cpp中的com_android_internal_os_Zygote_nativeForkSystemServer()
int pid = nativeForkSystemServer(
uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);
if (pid == 0) {
Trace.setTracingEnabled(true);
}
VM_HOOKS.postForkCommon();
return pid;
}
//第三步
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) {
//fork子进程
pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
debug_flags, rlimits,
permittedCapabilities, effectiveCapabilities,
MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
NULL, NULL);
if (pid > 0) {
ALOGI("System server process %d has been created", pid);
//检测Zygote进程是否已经创建
gSystemServerPid = pid;
int status;
if (waitpid(pid, &status, WNOHANG) == pid) {
ALOGE("System server process %d has died. Restarting Zygote!", pid);
//当system_server进程死亡之后重启Zygote进程
RuntimeAbort(env);
}
}
return pid;
}
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();//设置子进程的siginal信号处理函数
...
pid_t pid = fork();//fork子进程
if (pid == 0) {
gMallocLeakZygoteChild = 1;
//进入子进程
DetachDescriptors(env, fdsToClose);
...
if (uid != 0) {
EnableKeepCapabilities(env);
}
....
//对于非system_server进程,则创建进程组,
if (!is_system_server) {
int rc = createProcessGroup(uid, getpid());
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);//设置group
SetRLimits(env, javaRlimits);//设置资源limit
...
rc = setresuid(uid, uid, uid);
SetCapabilities(env, permittedCapabilities, effectiveCapabilities);
//设置调度策略
SetSchedulerPolicy(env);
...
//selinux上下文
rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str);
...
if (se_info_c_str != NULL) {
//设置进程名字为system_server,方便调试
SetThreadName(se_name_c_str);
}
delete se_info;
delete se_name;
UnsetSigChldHandler();//设置子进程的singal处理函数为默认处理函数
//等价于调用zygote.callPostForkChildHooks()
env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
is_system_server ? NULL : instructionSet);
if (env->ExceptionCheck()) {
ALOGE("Error calling post fork hooks.");
RuntimeAbort(env);
}
} else if (pid > 0) {
//进入父进程
}
return pid;
}
//第四步
private static void handleSystemServerProcess(
ZygoteConnection.Arguments parsedArgs)
throws ZygoteInit.MethodAndArgsCaller {
closeServerSocket();//关闭父进程复制而来的socket
if (parsedArgs.niceName != null) {
Process.setArgV0(parsedArgs.niceName);//设置当前进程名为system_server
}
//此处systemServerClasspath环境变量主要有/system/framework/目录下的services.jar,ethernet-service.jar, wifi-service.jar这3个文件
final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
if (systemServerClasspath != null) {
//执行dex优化操作
performSystemServerDexOpt(systemServerClasspath);
}
if (parsedArgs.invokeWith != null) {
String[] args = parsedArgs.remainingArgs;
...
//启动应用进程
WrapperInit.execApplication(parsedArgs.invokeWith,
parsedArgs.niceName, parsedArgs.targetSdkVersion,
VMRuntime.getCurrentInstructionSet(), null, args);
} else {
ClassLoader cl = null;
if (systemServerClasspath != null) {
//创建类加载器并赋予当前线程
cl = new PathClassLoader(systemServerClasspath, ClassLoader.getSystemClassLoader());
Thread.currentThread().setContextClassLoader(cl);
}
//system_server故进入此分支
RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
}
}
//第五步
public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
throws ZygoteInit.MethodAndArgsCaller {
if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from zygote");
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "RuntimeInit");
redirectLogStreams();//重定向log输出
//通用一些初始化
commonInit();
nativeZygoteInit();//zygote初始化
applicationInit(targetSdkVersion, argv, classLoader);//应用初始化
}
//第六步
private static final void commonInit() {
if (DEBUG) Slog.d(TAG, "Entered RuntimeInit!");
//设置默认的未捕捉异常处理方法
Thread.setDefaultUncaughtExceptionHandler(new UncaughtHandler());
//设置时区,中国时区为"Asia/Shanghai"
TimezoneGetter.setInstance(new TimezoneGetter() {
@Override
public String getId() {
return SystemProperties.get("persist.sys.timezone");
}
});
TimeZone.setDefault(null);
//重置log配置
LogManager.getLogManager().reset();
new AndroidConfig();
//设置默认的HTTP User-agent格式,用于 HttpURLConnection。
String userAgent = getDefaultUserAgent();
System.setProperty("http.agent", userAgent);
//设置socket的tag,用于流量统计
NetworkManagementSocketTagger.install();
...
}
//第七步
//nativeZygoteInit()方法在AndroidRuntime.cpp中
static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
//此处的gCurRuntime为AppRuntime,是在AndroidRuntime.cpp中定义的
gCurRuntime->onZygoteInit();
}
virtual void onZygoteInit()
{
//ProcessState::self()是单例模式,主要工作是调用open()打开/dev/binder驱动设备,
//再利用mmap()映射内核的地址空间,将Binder驱动的fd赋值ProcessState对象中的变量mDriverFD,用于交互操作
sp
proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
proc->startThreadPool();//startThreadPool()是创建一个新的binder线程,不断进行talkWithDriver()
}
//第八步
private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
throws ZygoteInit.MethodAndArgsCaller {
//true代表应用程序退出时不调用AppRuntime.onExit(),否则会在退出前调用
nativeSetExitWithoutCleanup(true);
//设置虚拟机的内存利用率参数值为0.75
VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
final Arguments args;
try {
args = new Arguments(argv);//解析参数
} catch (IllegalArgumentException ex) {
Slog.e(TAG, ex.getMessage());
return;
}
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
//调用startClass的static方法main()
invokeStaticMain(args.startClass, args.startArgs, classLoader);
}
private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
throws ZygoteInit.MethodAndArgsCaller {
Class> cl;
...
cl = Class.forName(className, true, classLoader);
...
Method m;
m = cl.getMethod("main", new Class[] { String[].class });
int modifiers = m.getModifiers();
...
//抛出异常,回到zygoteInit的main方法中,这样做好处是能清空栈帧,提高栈帧利用率
throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}
public static void main(String argv[]) {
try {
startSystemServer(abiList, socketName);//启动system_server
....
} catch (MethodAndArgsCaller caller) {
caller.run(); //进入MethodAndArgsCaller 的run方法
} catch (RuntimeException ex) {
closeServerSocket();
throw ex;
}
}
public void run() {
try {
//通过反射机制调用到SystemServer的main方法
mMethod.invoke(null, new Object[] { mArgs });
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
...
}
}
///SystemServer启动流程二******************************************************************************************************************************************************************
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
//若当前系统时间比1970年早,则设置当前系统时间为1970
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
//
if (!SystemProperties.get("persist.sys.language").isEmpty()) {
final String languageTag = Locale.getDefault().toLanguageTag();
SystemProperties.set("persist.sys.locale", languageTag);
SystemProperties.set("persist.sys.language", "");
SystemProperties.set("persist.sys.country", "");
SystemProperties.set("persist.sys.localevar", "");
}
Slog.i(TAG, "Entered the Android system server!");
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis());
//变更虚拟机的默认库文件,对于Android6.0,默认采用的是libart.so
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
if (SamplingProfilerIntegration.isEnabled()) {
SamplingProfilerIntegration.start();
mProfilerSnapshotTimer = new Timer();
mProfilerSnapshotTimer.schedule(new TimerTask() {
@Override
public void run() {
SamplingProfilerIntegration.writeSnapshot("system_server", null);
}
}, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
}
//清除虚拟机内存增长上限,由于启动过程需要较多的虚拟内存空间
VMRuntime.getRuntime().clearGrowthLimit();
//设置内存的可能有效使用率为0.8
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
//针对部分设备依赖于运行时就产生指纹信息,因此需要在开机完成前已经定义
Build.ensureFingerprintProperty();
//在SysteServer在访问环境变量前需要明确指定用户
Environment.setUserRequired(true);
//确保当前系统进程的binder调用,总是运行在前台优先级
BinderInternal.disableBackgroundScheduling(true);
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();//主线程就在当前线程运行
// 加载android_servers.so库,该库包含的源码在frameworks/base/services/目录下
System.loadLibrary("android_servers");
//检测上次关机过程是否失败
performPendingShutdown();
// 初始化系统上下文
createSystemContext();
//创建系统服务管理
mSystemServiceManager = new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// 启动服务
try {
startBootstrapServices();
startCoreServices();
startOtherServices();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
}
// 用于debug版本,将log事件不断循环地输出到dropbox
if (StrictMode.conditionallyEnableDebugLogging()) {
Slog.i(TAG, "Enabled StrictMode for system server main thread.");
}
// 一直循环执行
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
//检测上次关机过程是否失败
private void performPendingShutdown() {
final String shutdownAction = SystemProperties.get(
ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
if (shutdownAction != null && shutdownAction.length() > 0) {
boolean reboot = (shutdownAction.charAt(0) == '1');
final String reason;
if (shutdownAction.length() > 1) {
reason = shutdownAction.substring(1, shutdownAction.length());
} else {
reason = null;
}
//当"sys.shutdown.requested"值不为空,则会重启或者关机
ShutdownThread.rebootOrShutdown(null, reboot, reason);
}
}
//初始化系统上下文
private void createSystemContext() {
//创建system_server进程的上下文信息
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
//设置主题
mSystemContext.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
}
private void startBootstrapServices() {
//阻塞等待与Installers建立socket通道
Installer installer = mSystemServiceManager.startService(Installer.class);
// 启动ActivityManagerService服务
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
//启动PowerManagerService服务
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
//初始化power managerment
mActivityManagerService.initPowerManagement();
//启动LightService
mSystemServiceManager.startService(LightsService.class);
//启动DisplayManagerService服务
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
//Phase100: 在初始化package manager之前,需要默认的显示.
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
//当设备正在加密时,仅运行核心
String cryptState = SystemProperties.get("vold.decrypt");
if (ENCRYPTING_STATE.equals(cryptState)) {
Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
mOnlyCore = true;
} else if (ENCRYPTED_STATE.equals(cryptState)) {
Slog.w(TAG, "Device encrypted - only parsing core apps");
mOnlyCore = true;
}
if (RegionalizationEnvironment.isSupported()) {
Slog.i(TAG, "Regionalization Service");
RegionalizationService regionalizationService = new RegionalizationService();
ServiceManager.addService("regionalization", regionalizationService);
}
// 启动服务PackageManagerService
Slog.i(TAG, "Package Manager");
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
//启动服务UserManagerService
Slog.i(TAG, "User Service");
ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());
// Initialize attribute cache used to cache resources from packages.
AttributeCache.init(mSystemContext);
// 设置AMS
mActivityManagerService.setSystemProcess();
//启动传感器服务
startSensorService();
}
private void startCoreServices() {
// 启动BatteryService,用于统计电池电量,需要LightService
mSystemServiceManager.startService(BatteryService.class);
// 启动UsageStatsService,用于统计应用使用情况
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
mPackageManagerService.getUsageStatsIfNoPackageUsageInfo();
// 启动服务WebViewUpdateService
mSystemServiceManager.startService(WebViewUpdateService.class);
}