本文基于AOSP Android12的源码分析Android系统的启动流程。
由于这部分内容各版本之间差异不大,同样适用于Android12之前的版本。
1. 概述
整体流程为:BootRom > BootLoader > Kernel > init > Zygote > System Server
2. Boot Rom
此步骤称为开机和系统启动。
意味着每当我们按下电源按钮时,BootROM代码就会从预先固定在ROM中的预定位置开始执行,Boot ROM将BootLoader加载到RAM中并开始执行。
3. BootLoader
引导加载程序是一个低级代码,包含指示设备如何启动和查找系统内核的指令。
BootLoader是制造商放置锁和限制的地方,一般解锁才能刷机就是解锁的BootLoader。
引导加载程序是在任何操作系统开始运行之前执行的代码,BooLoader分两个阶段执行:
- 第一阶段,它检测到外部RAM并加载一个在第二阶段有帮助的程序。
- 第二阶段,引导程序会设置需要运行内核的网络,内存等。
4. Kernel
内核启动后,它将启动
- 设置缓存
- 受保护的内存
- 调度
- 加载驱动程序
- 启动内核守护程序
- 安装根文件系统
- 初始化输入/输出
- 启动中断
- 初始化进程表
内核是我们设备中的硬件接口的易于替换的软件最低级别。
当内核首先完成系统设置时,它会在系统文件中寻找init进程并启动
5. init
init 进程是第一个进程,或者我们可以说它是所有进程的父进程或者父父进程。
init 进程有两个职责:
- 挂载/sys,/dev或/proc之类的目录
- 运行/init.rc脚本。init.rc负责系统的初始化设置
init 进程会设置所有本级服务,这类似于常规的Linux系统引导。
在 init.rc 文件中有如下几行import的rc文件]
import /init.environ.rc
import /system/etc/init/hw/init.usb.rc
import /init.${ro.hardware}.rc
import /vendor/etc/init/hw/init.${ro.hardware}.rc
import /system/etc/init/hw/init.usb.configfs.rc
import /system/etc/init/hw/init.${ro.zygote}.rc
最后一行即为Zygote的启动配置
启动Zygote分为32位和64位,分别对应下面两个rc文件。
system/core/rootdir/init.zygote32.rcsystem/core/rootdir/init.zygote64.rc
service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
class main
priority -20
user root
group root readproc reserved_disk
socket zygote stream 660 root system
socket usap_pool_primary stream 660 root system
onrestart exec_background - system system -- /system/bin/vdc volume abort_fuse
onrestart write /sys/power/state on
onrestart restart audioserver
onrestart restart cameraserver
onrestart restart media
onrestart restart netd
onrestart restart wificond
writepid /dev/cpuset/foreground/tasks
critical window=${zygote.critical_window.minute:-off} target=zygote-fatal
rc配置文件的格式为:service <service_name> <bin_path> <args>
可以发现启动的可执行文件为app_process64 ,存放在/system/bin目录下。
5.1 app_process
源码路径:frameworks/base/cmds/app_process/app_main.cpp
app_process 调用的命令格式如下
app_process [java-options] cmd-dir start-class-name [options]
参数一: app_process可执行文件本身路径
参数二: Java虚拟机参数
参数三: app_process可执行程序所在父目录路径,目前未使用
参数三往后:为内部参数,有如下四种使用方法
--zygote : 以Zygote模式启动
--start-system-server: 启动SystemServer
--application : 以独立应用程序模式启动(非Zygote模式)
--nice-name:设置新启动的进程名称
参考init.zygote64.rc配置
/system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
5.1.1 main
int main(int argc, char* const argv[])
{
// ...
// AppRuntime继承自AndroidRuntime
AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
// 忽略第一个参数,命令程序本身
argc--;
argv++;
// ...
int i;
// ...
// 解析运行时参数
bool zygote = false;
bool startSystemServer = false;
bool application = false;
String8 niceName;
String8 className;
++i; // 跳过不使用的parent dir
while (i < argc) {
const char* arg = argv[i++];
if (strcmp(arg, "--zygote") == 0) {
zygote = true;
niceName = ZYGOTE_NICE_NAME; // zygote 或者 zygote64
} else if (strcmp(arg, "--start-system-server") == 0) {
startSystemServer = true;
} else if (strcmp(arg, "--application") == 0) {
application = true;
} else if (strncmp(arg, "--nice-name=", 12) == 0) {
niceName.setTo(arg + 12);
} else if (strncmp(arg, "--", 2) != 0) {
className.setTo(arg);
break;
} else {
--i;
break;
}
}
Vector<String8> args; // 保存参数列表
if (!className.isEmpty()) {
// 以application模式启动
args.add(application ? String8("application") : String8("tool"));
runtime.setClassNameAndArgs(className, argc - i, argv + i);
// ...
} else {
// 以zygote模式启动
maybeCreateDalvikCache(); // 创建虚Dalvik虚拟机缓存目录
if (startSystemServer) {
args.add(String8("start-system-server"));
}
// 获取abi list
char prop[PROP_VALUE_MAX];
if (property_get(ABI_LIST_PROPERTY, prop, NULL) == 0) {
LOG_ALWAYS_FATAL("app_process: Unable to determine ABI list from property %s.",
ABI_LIST_PROPERTY);
return 11;
}
String8 abiFlag("--abi-list=");
abiFlag.append(prop);
args.add(abiFlag);
// 在zygote模式中,保存剩于的所有参数供zygote使用
for (; i < argc; ++i) {
args.add(String8(argv[i]));
}
}
if (!niceName.isEmpty()) { // 设置进程名称
runtime.setArgv0(niceName.string(), true /* setProcName */);
}
if (zygote) {
// 根据init.zygote64.rc配置文件可知,zygote为true,执行该条件
runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
} else if (className) {
runtime.start("com.android.internal.os.RuntimeInit", args, zygote);
} else {
fprintf(stderr, "Error: no class name or --zygote supplied.\n");
app_usage();
LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
}
}
5.1.2 小结
通过源码分析我们得知app_process主要是解析参数,并确定具体的启动模式(zygote/application),最后由AndroidRuntime负责启动Java虚拟机并调用入口函数执行。
6. Zygote
源码路径:frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
Zygote是一个VM进程,它在系统启动时由init进程解析init.rc文件通过app_process启动。
当app_process启动zygote时,它首先创建Dalvik VM,然后调用ZygoteInit的main方法。
public static void main(String[] argv) {
ZygoteServer zygoteServer = null;
// 标记当前正在启动Zygote,确保线程创建将导致异常
ZygoteHooks.startZygoteNoThreadCreation();
// 使Zygote进入它自己的进程组
try {
Os.setpgid(0, 0);
} catch (ErrnoException ex) {
throw new RuntimeException("Failed to setpgid(0,0)", ex);
}
Runnable caller;
try {
// 存储现在启动相关信息,便于后续使用
final long startTime = SystemClock.elapsedRealtime(); // 记录启动时间
final boolean isRuntimeRestarted = "1".equals(SystemProperties.get("sys.boot_completed"));// 是否重启
String bootTimeTag = Process.is64Bit() ? "Zygote64Timing" : "Zygote32Timing"; // Log TAG
TimingsTraceLog bootTimingsTraceLog = new TimingsTraceLog(bootTimeTag,
Trace.TRACE_TAG_DALVIK); // trace记录
bootTimingsTraceLog.traceBegin("ZygoteInit");
// 启用DDMS,设置MimeMap
RuntimeInit.preForkInit();
boolean startSystemServer = false; // 是否需要启动SystemServer
String zygoteSocketName = "zygote"; // 套接字名称
String abiList = null; // abi列表
boolean enableLazyPreload = false; // 是否启用懒加载资源
for (int i = 1; i < argv.length; i++) { // 参数解析
if ("start-system-server".equals(argv[i])) {
startSystemServer = true;
} else if ("--enable-lazy-preload".equals(argv[i])) {
enableLazyPreload = true;
} else if (argv[i].startsWith(ABI_LIST_ARG)) {
abiList = argv[i].substring(ABI_LIST_ARG.length());
} else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
zygoteSocketName = argv[i].substring(SOCKET_NAME_ARG.length());
} else {
throw new RuntimeException("Unknown command line argument: " + argv[i]);
}
}
// PRIMARY_SOCKET_NAME = “zygote”
// 标记是否是主要的Zygote
final boolean isPrimaryZygote = zygoteSocketName.equals(Zygote.PRIMARY_SOCKET_NAME);
if (!isRuntimeRestarted) {
if (isPrimaryZygote) {
FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__ZYGOTE_INIT_START,
startTime);
} else if (zygoteSocketName.equals(Zygote.SECONDARY_SOCKET_NAME)) {
FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SECONDARY_ZYGOTE_INIT_START,
startTime);
}
}
// abiList为空,则抛出异常
if (abiList == null) {
throw new RuntimeException("No ABI list supplied.");
}
// 在某些配置中,我们避免急切地预加载资源和类。
// 在这种情况下,我们将在第一次分叉之前预加载内容。
if (!enableLazyPreload) {
// ...
preload(bootTimingsTraceLog); // 预加载资源 [6.1小节]
// ...
}
gcAndFinalize();// 启动后进行初始的GC清理
// ...
// 调用Native初始化状态
Zygote.initNativeState(isPrimaryZygote);
// 与上方startZygoteNoThreadCreation配对
ZygoteHooks.stopZygoteNoThreadCreation();
// 构建ZygoteServer [6.2 小节]
zygoteServer = new ZygoteServer(isPrimaryZygote);
if (startSystemServer) { // 启动SystemServer [7小节]
Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
// r为null表示在zygote进程执行,r不为null表示在system_server进程执行
if (r != null) {
r.run();
return;
}
}
// Zygote进程进入永久循环 [6.2 小节]
caller = zygoteServer.runSelectLoop(abiList);
} catch (Throwable ex) {
Log.e(TAG, "System zygote died with fatal exception", ex);
throw ex;
} finally {
if (zygoteServer != null) { // ZygoteServer服务结束,关闭断开Socket
zygoteServer.closeServerSocket();
}
}
// We're in the child process and have exited the select loop. Proceed to execute the
// command.
if (caller != null) {
caller.run();
}
}
6.1 preload
源码路径:frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
static void preload(TimingsTraceLog bootTimingsTraceLog) {
// 忽略log trace代码,便于分析
beginPreload(); // 调用ZygoteHooks初始化ICU缓存,反射JaCoCo中的class
preloadClasses(); // 加载和初始化常用的类
cacheNonBootClasspathClassLoaders(); // 缓存hidi相关的ClassLoader
preloadResources(); // 加载常用资源,使它们可以跨进程共享
nativePreloadAppProcessHALs(); // 调用native函数来初始化的HAL层逻辑
maybePreloadGraphicsDriver(); // 调用native函数来初始化图形驱动程序
preloadSharedLibraries(); // 加载共享库(android,compiler_rt,jnigraphics)
preloadTextResources(); // 初始化文本字体资源
WebViewFactory.prepareWebViewInZygote();// 初始化WebView需要进程内存共享的空间(64位:1GB,32位:130MB)
endPreload(); // 预加载结束,同时会调用ZygoteHooks进程克隆标准文件描述符(in,out,err)
warmUpJcaProviders(); // 注册AndroidKeyStoreProvider,并且通知Security的providers
sPreloadComplete = true;
}
6.2 ZygoteServer
源码路径:frameworks/base/core/java/com/android/internal/os/ZygoteServer.java
6.2.1 ZygoteServer 构造函数
// ZygoteServer构造函数
ZygoteServer(boolean isPrimaryZygote) {
mUsapPoolEventFD = Zygote.getUsapPoolEventFD(); // Usap文件描述符
if (isPrimaryZygote) { // 创建zygote和usap_pool_primary的Socket连接
mZygoteSocket = Zygote.createManagedSocketFromInitSocket(Zygote.PRIMARY_SOCKET_NAME);
mUsapPoolSocket =
Zygote.createManagedSocketFromInitSocket(
Zygote.USAP_POOL_PRIMARY_SOCKET_NAME);
} else { // 创建zygote_secondary和usap_pool_secondary的Socket连接
mZygoteSocket = Zygote.createManagedSocketFromInitSocket(Zygote.SECONDARY_SOCKET_NAME);
mUsapPoolSocket =
Zygote.createManagedSocketFromInitSocket(
Zygote.USAP_POOL_SECONDARY_SOCKET_NAME);
}
// 最终建立的Socket的名字会被加上 ANDROID_SOCKET_ 前缀
mUsapPoolSupported = true;
fetchUsapPoolPolicyProps(); // 获取Usap相关配置
}
6.2.2 ZygoteServer.runSelectLoop
Runnable runSelectLoop(String abiList) {
ArrayList<FileDescriptor> socketFDs = new ArrayList<>();
ArrayList<ZygoteConnection> peers = new ArrayList<>();
socketFDs.add(mZygoteSocket.getFileDescriptor());
peers.add(null);
mUsapPoolRefillTriggerTimestamp = INVALID_TIMESTAMP;
while (true) {
fetchUsapPoolPolicyPropsWithMinInterval(); // 获取UsapPool相关配置
mUsapPoolRefillAction = UsapPoolRefillAction.NONE;
int[] usapPipeFDs = null;
StructPollfd[] pollFDs;
if (mUsapPoolEnabled) { // 该值默认为false,在此不做过多介绍,后续单独介绍UsapPool内容
usapPipeFDs = Zygote.getUsapPipeFDs();
pollFDs = new StructPollfd[socketFDs.size() + 1 + usapPipeFDs.length];
} else {
pollFDs = new StructPollfd[socketFDs.size()];
}
int pollIndex = 0;
for (FileDescriptor socketFD : socketFDs) {
pollFDs[pollIndex] = new StructPollfd();
pollFDs[pollIndex].fd = socketFD;
pollFDs[pollIndex].events = (short) POLLIN;
++pollIndex;
}
final int usapPoolEventFDIndex = pollIndex; // 该值为SocketFD个数
// ... 忽略UsapPool
int pollTimeoutMs;
if (mUsapPoolRefillTriggerTimestamp == INVALID_TIMESTAMP) {
pollTimeoutMs = -1;
} else {
long elapsedTimeMs = System.currentTimeMillis() - mUsapPoolRefillTriggerTimestamp;
if (elapsedTimeMs >= mUsapPoolRefillDelayMs) {
pollTimeoutMs = 0;
mUsapPoolRefillTriggerTimestamp = INVALID_TIMESTAMP;
mUsapPoolRefillAction = UsapPoolRefillAction.DELAYED;
} else if (elapsedTimeMs <= 0) {
pollTimeoutMs = mUsapPoolRefillDelayMs;
} else {
pollTimeoutMs = (int) (mUsapPoolRefillDelayMs - elapsedTimeMs);
}
}
int pollReturnValue;
try {
pollReturnValue = Os.poll(pollFDs, pollTimeoutMs);
} catch (ErrnoException ex) {
throw new RuntimeException("poll failed", ex);
}
if (pollReturnValue == 0) {
mUsapPoolRefillTriggerTimestamp = INVALID_TIMESTAMP;
mUsapPoolRefillAction = UsapPoolRefillAction.DELAYED;
} else {
boolean usapPoolFDRead = false;
while (--pollIndex >= 0) {
// 读取的状态不是客户端连接或者数据请求时,进入下一次循环
if ((pollFDs[pollIndex].revents & POLLIN) == 0) {
continue;
}
if (pollIndex == 0) { //表示跟客户端Socket 连接上了
ZygoteConnection newPeer = acceptCommandPeer(abiList); // 产生一个ZygoteConnection连接
peers.add(newPeer); // 保存到集合中
socketFDs.add(newPeer.getFileDescriptor()); // FD也保存到集中中
} else if (pollIndex < usapPoolEventFDIndex) {
// ZygoteServer接收到客户端请求
try {
ZygoteConnection connection = peers.get(pollIndex);
boolean multipleForksOK = !isUsapPoolEnabled()
&& ZygoteHooks.isIndefiniteThreadSuspensionSafe();
// 处理此次请求任务 [6.3 小节]
final Runnable command =
connection.processCommand(this, multipleForksOK);
if (mIsForkChild) {
// 在子进程中,如果没有命令来执行,抛出异常
if (command == null) {
throw new IllegalStateException("command == null");
}
return command;
} else {
// 在Server进程中,我们不应该有命令需要执行
if (command != null) {
throw new IllegalStateException("command != null");
}
// 关闭Socket
if (connection.isClosedByPeer()) {
connection.closeSocket();
peers.remove(pollIndex);
socketFDs.remove(pollIndex);
}
}
} catch (Exception e) { // 处理异常情况
if (!mIsForkChild) {
Slog.e(TAG, "Exception executing zygote command: ", e);
// 关闭连接
ZygoteConnection conn = peers.remove(pollIndex);
conn.closeSocket();
socketFDs.remove(pollIndex);
} else {
Log.e(TAG, "Caught post-fork exception in child process.", e);
throw e;
}
} finally {
// 恢复默认值
mIsForkChild = false;
}
} else {
//... 忽略USAP poll
}
} // while
//... 忽略USAP poll
}
//... 忽略USAP poll
}
}
6.3 ZygoteConnection
源码路径:frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java
Runnable processCommand(ZygoteServer zygoteServer, boolean multipleOK) {
ZygoteArguments parsedArgs;
try (ZygoteCommandBuffer argBuffer = new ZygoteCommandBuffer(mSocket)) {
while (true) {
try {
// 读取并解析Client发出的参数列表
parsedArgs = ZygoteArguments.getInstance(argBuffer);
// Keep argBuffer around, since we need it to fork.
} catch (IOException ex) {
throw new IllegalStateException("IOException on command socket", ex);
}
// ...
int pid;
// ...
if (parsedArgs.mInvokeWith != null || parsedArgs.mStartChildZygote
|| !multipleOK || peer.getUid() != Process.SYSTEM_UID) {
// fork完后返回pid,具体fork过程是在native中的nativeForkAndSpecialize函数
pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid,
parsedArgs.mGids, parsedArgs.mRuntimeFlags, rlimits,
parsedArgs.mMountExternal, parsedArgs.mSeInfo, parsedArgs.mNiceName,
fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
parsedArgs.mInstructionSet, parsedArgs.mAppDataDir,
parsedArgs.mIsTopApp, parsedArgs.mPkgDataInfoList,
parsedArgs.mAllowlistedDataInfoList, parsedArgs.mBindMountAppDataDirs,
parsedArgs.mBindMountAppStorageDirs);
try {
if (pid == 0) {
// 标记在子进程,一般情况是ATMS发出请求,此时已经建立了App进程。
zygoteServer.setForkChild();
zygoteServer.closeServerSocket();
IoUtils.closeQuietly(serverPipeFd);
serverPipeFd = null;
// 在子进程中处理,最终会调用RuntimeInit去查找ActivityThread的静态main函数
// 这也是Android应用程序入口的函数
return handleChildProc(parsedArgs, childPipeFd,
parsedArgs.mStartChildZygote);
} else {
// 在Zygote进程中,也是所有应用进程的父进程
IoUtils.closeQuietly(childPipeFd);
childPipeFd = null;
// 主要用来发送pid给ATMS
handleParentProc(pid, serverPipeFd);
return null;
}
} finally {
// 释放资源
IoUtils.closeQuietly(childPipeFd);
IoUtils.closeQuietly(serverPipeFd);
}
} else {
// ...
}
}
}
// ...
throw new AssertionError("Shouldn't get here");
}
6.4 小结
- 预加载系统资源(classes、resouces、hal...)。
- 根据参数决定是否需要启动SystemServer。
- 最终启动ZygoteServer,接收并处理来自Client(ATMS的fork)的请求,Client和Server是通过LocalSocket建立连接。
7. SystemServer
源码路径:frameworks/base/services/java/com/android/server/SystemServer.java
Zygote预加载所有必要的Java类和资源后,它将启动SystemServer。
system_server是Android系统的核心。
public static void main(String[] args) {
new SystemServer().run();
}
7.1 run
private void run() {
TimingsTraceAndSlog t = new TimingsTraceAndSlog();
try {
t.traceBegin("InitBeforeStartServices");
// 在系统属性中记录进程相关启动信息
SystemProperties.set(SYSPROP_START_COUNT, String.valueOf(mStartCount));
SystemProperties.set(SYSPROP_START_ELAPSED, String.valueOf(mRuntimeStartElapsedTime));
SystemProperties.set(SYSPROP_START_UPTIME, String.valueOf(mRuntimeStartUptime));
// ...
String timezoneProperty = SystemProperties.get("persist.sys.timezone"); // 时区
if (!isValidTimeZoneId(timezoneProperty)) {
Slog.w(TAG, "persist.sys.timezone is not valid (" + timezoneProperty
+ "); setting to GMT.");
SystemProperties.set("persist.sys.timezone", "GMT");
}
// 语言相关属性
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", "");
}
// 省略部分代码
// Here we go!
Slog.i(TAG, "Entered the Android system server!");
final long uptimeMillis = SystemClock.elapsedRealtime(); // 启动时间
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
// Mmmmmm... more memory!
VMRuntime.getRuntime().clearGrowthLimit();
// Some devices rely on runtime fingerprint generation, so make sure
// we've defined it before booting further.
Build.ensureFingerprintProperty();
// Within the system server, it is an error to access Environment paths without
// explicitly specifying a user.
Environment.setUserRequired(true);
// Within the system server, any incoming Bundles should be defused
// to avoid throwing BadParcelableException.
BaseBundle.setShouldDefuse(true);
// 在System server中,当发生parce异常,倒入相关堆栈信息
Parcel.setStackTraceParceling(true);
// 确保对系统的 Binder 调用始终以前台优先级运行
BinderInternal.disableBackgroundScheduling(true);
// 增加 system_server 中的 binder 线程数
BinderInternal.setMaxThreads(sMaxBinderThreads);
// 设置线程优先级
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();// 准备main looper thread ,
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
SystemServiceRegistry.sEnableServiceNotFoundWtf = true;
// 初始化native services
System.loadLibrary("android_servers");
// 允许堆性能分析
initZygoteChildHeapProfiling();
// 开启Debug模式后,生成一个线程来监听文件描述符泄露
if (Build.IS_DEBUGGABLE) {
spawnFdLeakCheckThread();
}
// 检测我们上次尝试是否为能关闭,此调用可能不会返回
performPendingShutdown();
// 初始化系统上下文,包括ActivityThread
createSystemContext();
// 调用每个进程的主线模块初始化。
ActivityThread.initializeMainlineModules();
// 设置Dump service
ServiceManager.addService("system_server_dumper", mDumper);
mDumper.addDumpable(this);
// 创建system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
mDumper.addDumpable(mSystemServiceManager);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// 为可并行的init任务准备线程池
SystemServerInitThreadPool tp = SystemServerInitThreadPool.start();
mDumper.addDumpable(tp);
// 为system server加载系统预装的系统字体
if (Typeface.ENABLE_LAZY_TYPEFACE_INITIALIZATION) {
Typeface.loadPreinstalledSystemFontMap();
}
// ...忽略JVM Debug相关
} finally {
t.traceEnd(); // InitBeforeStartServices
}
// Setup the default WTF handler
RuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf);
// Start services.
try {
t.traceBegin("StartServices");
startBootstrapServices(t); // 启动Bootstrap相关服务 [7.2 小节]
startCoreServices(t); // 启动核心服务 [7.3 小节]
startOtherServices(t); // 启动非核心服务 [7.4 小节]
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
t.traceEnd(); // StartServices
}
StrictMode.initVmDefaults(null);
// .. 忽略log打印相关
// 进入永远循环
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
7.2 startBootstrapServices
启动系统启动所需的一小部分关键服务,这些服务具有复杂的相互依赖关系,所以会在此将他们全部初始化。
具体服务如下:
FileIntegrityService、Installer、DeviceIdentifiersPolicyService、UriGrantsManagerService、PowerStatsService、IStatsService、MemtrackProxyService、ActivityTaskManagerService、ActivityManagerService、DataLoaderManagerService、IncrementalService、PowerManagerService、ThermalManagerService、HintManagerService、RecoverySystemService、LightsService、SidekickService、DisplayManagerService、DomainVerificationService、UserManagerService、OverlayManagerService、SensorPrivacyService、SensorService
7.3 startCoreServices
启动一些在startBootstrapServices中没有依赖的一部分服务,具体服务如下:
SystemConfigService、BatteryService、UsageStatsService、CachedDeviceStateService、BinderCallsStatsService、LooperStatsService、RollbackManagerService、NativeTombstoneManagerService、BugreportManagerService、GpuService
7.4 startOtherServices
启动一些在startBootstrapServices和startCoreServices没有启动的服务,由于服务过多,在此只展示一些我们熟悉的服务,所有服务请通过阅读源码查看。
WindowManagerService、InputManagerService、VibratorManagerService、AlarmManagerService、BluetoothService、StorageManagerService、UiModeManagerService、StatusBarManagerService、VpnManagerService、NotificationManagerService、LocationManagerService、ConnectivityManager
最终也会启动SystemUI的Service。
7.5 小结
SystemServer主要负责一下几部分内容:
- 启动相关的信息的存储。
- 设置Binder thread相关的配置。
- 构建ActivityThread以及系统上下文。
- 通过SystemServiceManager去启动系统中的各种Service。
- 使Main Looper进入循环,等待消息处理任务。