SystemServer启动流程代码走读(java层)
1、Main()方法主入口:
SystemServer构造,然后执行run()方法
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}
2、构造方法:
public SystemServer() {
// Check for factory test mode.
mFactoryTestMode = FactoryTest.getMode();
// Record process start information.
// Note SYSPROP_START_COUNT will increment by *2* on a FDE device when it fully boots;
// one for the password screen, second for the actual boot.
mStartCount = SystemProperties.getInt(SYSPROP_START_COUNT, 0) + 1;
mRuntimeStartElapsedTime = SystemClock.elapsedRealtime();
mRuntimeStartUptime = SystemClock.uptimeMillis();
Process.setStartTimes(mRuntimeStartElapsedTime, mRuntimeStartUptime);
// Remember if it's runtime restart(when sys.boot_completed is already set) or reboot
// We don't use "mStartCount > 1" here because it'll be wrong on a FDE device.
// TODO: mRuntimeRestart will *not* be set to true if the proccess crashes before
// sys.boot_completed is set. Fix it.
mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));
}
3、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));
EventLog.writeEvent(EventLogTags.SYSTEM_SERVER_START,
mStartCount, mRuntimeStartUptime, mRuntimeStartElapsedTime);
//如果时区不存在,设置时区为GMT
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");
}
// 如果设置过persist.sys.language属性,则设置
// persist.sys.locale属性去替换,以保持和AndroidRuntime一致
// 该属性仅能被system_server和system apps设置
// AndroidRuntime源码位置:
// frameworks/base/core/jni/AndroidRuntime.cpp
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", "");
}
// The system server should never make non-oneway calls
Binder.setWarnOnBlocking(true);
// The system server should always load safe labels
PackageItemInfo.forceSafeLabels();
// Default to FULL within the system server.
SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;
// Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
SQLiteCompatibilityWalFlags.init(null);
// Here we go!
Slog.i(TAG, "Entered the Android system server!");
final long uptimeMillis = SystemClock.elapsedRealtime();
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
if (!mRuntimeRestart) {
FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
FrameworkStatsLog
.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SYSTEM_SERVER_INIT_START,
uptimeMillis);
}
/// M: BOOTPROF
sMtkSystemServerIns.addBootEvent("Android:SysServerInit_START");
// 变更虚拟机库文件
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
// 清除vm内存上限,由于启动过程需要较多的虚拟机内存空间
// NOTE: 值得注意的点,应用使用的VM内存,也是有上限的,超过设置的上限就会内存溢出,即应用崩溃。
VMRuntime.getRuntime().clearGrowthLimit();
// 有些设备运行依赖指纹,所以在进一步启动之前,确保指纹属性的定义
Build.ensureFingerprintProperty();
// 在system server中,访问环境变量需要指定用户
Environment.setUserRequired(true);
// 在system server中,任何传入的bundle必须避免抛出BadParcelableException异常
// 猜测和内存使用相关
BaseBundle.setShouldDefuse(true);
// 在system server中,打包Exception数据的时候包含stack trace
Parcel.setStackTraceParceling(true);
// 确保binder调用进入system的时候,必须是foreground priority,不能是backaground priority
BinderInternal.disableBackgroundScheduling(true);
// 在system server中,提高binder线程的最大数量
BinderInternal.setMaxThreads(sMaxBinderThreads);
// Prepare the main looper thread (this thread).
// 将当前线程优先级设置为foreground,并且不允许自身线程变成background优先级。NOTE:注意这里的结合使用。
// 然后为自己的线程准备main looper,并设置其日志输出信息的配置
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
// 注册标识,WTF级别错误相关(What the fuck级别的错误,意为基本不可能发生的错误)
SystemServiceRegistry.sEnableServiceNotFoundWtf = true;
// 加载动态库android_servers, 初始化native services
System.loadLibrary("android_servers");
// 允许堆内存分析
initZygoteChildHeapProfiling();
// Debug版本中,孵化一个线程去监控文件句柄泄漏(fd leaks)
if (Build.IS_DEBUGGABLE) {
spawnFdLeakCheckThread();
}
// 检查上一次关机是否失败,它可能会导致直接关机/重启,因此这个方法可能不会return
performPendingShutdown();
// 初始化系统上下文system context
createSystemContext();
// Call per-process mainline module initialization.
// 初始化system server的每一个进程
ActivityThread.initializeMainlineModules();
// dumper service设置,注意是设置,不是启动
ServiceManager.addService("system_server_dumper", mDumper);
mDumper.addDumpable(this);
// 使用之前创建的system context创建system service manager
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
mDumper.addDumpable(mSystemServiceManager);
// 将system service manager添加到LocalServices缓存池中,
// LocalServices的作用就是,确保system server中的services之间的低耦合
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// 为system server进程中的初始化任务,准备并发线程池
SystemServerInitThreadPool tp = SystemServerInitThreadPool.start();
mDumper.addDumpable(tp);
// 如果设置了系统字体懒加载,则预加载system font map,因为WindowManagerService等服务会用到。
if (Typeface.ENABLE_LAZY_TYPEFACE_INITIALIZATION) {
Typeface.loadPreinstalledSystemFontMap();
}
// 如果是debug版本,则开始加载jvmtiAgent,
// JVM TI是JDK提供的一套用于开发JVM监控, 问题定位与性能调优工具的通用编程接口(API),
// 通过JVMTI,我们可以开发各式各样的JVMTI Agent。
// 这个Agent的表现形式是一个以c/c++语言编写的动态共享库。
if (Build.IS_DEBUGGABLE) {
// Property is of the form "library_path=parameters".
String jvmtiAgent = SystemProperties.get("persist.sys.dalvik.jvmtiagent");
if (!jvmtiAgent.isEmpty()) {
int equalIndex = jvmtiAgent.indexOf('=');
String libraryPath = jvmtiAgent.substring(0, equalIndex);
String parameterList =
jvmtiAgent.substring(equalIndex + 1, jvmtiAgent.length());
// Attach the agent.
try {
Debug.attachJvmtiAgent(libraryPath, parameterList, null);
} catch (Exception e) {
Slog.e("System", "*************************************************");
Slog.e("System", "********** Failed to load jvmti plugin: " + jvmtiAgent);
}
}
}
} finally {
t.traceEnd(); // InitBeforeStartServices
}
/// M: Set paramters to mtkSystemserver.
sMtkSystemServerIns.setPrameters(BOOT_TIMINGS_TRACE_LOG, mSystemServiceManager, mSystemContext);
// 在Runtime中设置WTF错误处理Handler
RuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf);
// 接下来就是启动各种服务的过程
try {
t.traceBegin("StartServices");
// bootstrap级别的service
startBootstrapServices(t);
/// M: For mtk systemserver
sMtkSystemServerIns.startMtkBootstrapServices();
// 然后是核心服务
startCoreServices(t);
/// M: for mtk other service.
sMtkSystemServerIns.startMtkCoreServices();
// 剩下的服务,并在其中进行各类服务的systemReady()调用
startOtherServices(t);
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
t.traceEnd(); // StartServices
}
// 严格模式的vm参数初始化?具体意义?性能相关?权限相关?
StrictMode.initVmDefaults(null);
// 如果是user版本,并且非Runtime restart,并且不是第一次开机或者OTA更新
// system server启动如果耗时过长,就记录一个WTF错误
if ("user".equals(Build.TYPE) && !mRuntimeRestart && !isFirstBootOrUpgrade()) {
final long uptimeMillis = SystemClock.elapsedRealtime();
FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SYSTEM_SERVER_READY,
uptimeMillis);
final long maxUptimeMillis = 60 * 1000;
if (uptimeMillis > maxUptimeMillis) {
Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
"SystemServer init took too long. uptimeMillis=" + uptimeMillis);
}
}
///