SystemServer.java的run方法都干了些什么?(2)

private void run() {

TimingsTraceAndSlog t = new TimingsTraceAndSlog();

try {

t.traceBegin("InitBeforeStartServices");

// Record the process start information in sys props.

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);

//

// Default the timezone property to GMT if not set.

//

String timezoneProperty = SystemProperties.get("persist.sys.timezone");

if (timezoneProperty == null || timezoneProperty.isEmpty()) {

Slog.w(TAG, "Timezone not set; setting to GMT.");

SystemProperties.set("persist.sys.timezone", "GMT");

}

// If the system has "persist.sys.language" and friends set, replace them with

// "persist.sys.locale". Note that the default locale at this point is calculated

// using the "-Duser.locale" command line flag. That flag is usually populated by

// AndroidRuntime using the same set of system properties, but only the system_server

// and system apps are allowed to set them.

//

// NOTE: Most changes made here will need an equivalent change to

// 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);

}

// In case the runtime switched since last boot (such as when

// the old runtime was removed in an OTA), set the system

// property so that it is in sync. We can't do this in

// libnativehelper's JniInvocation::Init code where we already

// had to fallback to a different runtime because it is

// running as root and we need to be the system user to set

// the property. http://b/11463182

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);

// Within the system server, when parceling exceptions, include the stack trace

Parcel.setStackTraceParceling(true);

// Ensure binder calls into the system always run at foreground priority.

BinderInternal.disableBackgroundScheduling(true);

// Increase the number of binder threads in system_server

BinderInternal.setMaxThreads(sMaxBinderThreads);

// Prepare the main looper thread (this thread).

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);

SystemServiceRegistry.sEnableServiceNotFoundWtf = true;

// Initialize native services.

System.loadLibrary("android_servers");

// Allow heap / perf profiling.

initZygoteChildHeapProfiling();

// Debug builds - spawn a thread to monitor for fd leaks.

if (Build.IS_DEBUGGABLE) {

spawnFdLeakCheckThread();

}

// Check whether we failed to shut down last time we tried.

// This call may not return.

performPendingShutdown();

// Initialize the system context.

createSystemContext();

// Call per-process mainline module initialization.

ActivityThread.initializeMainlineModules();

// Create the system service manager.

mSystemServiceManager = new SystemServiceManager(mSystemContext);

mSystemServiceManager.setStartInfo(mRuntimeRestart,

mRuntimeStartElapsedTime, mRuntimeStartUptime);

LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

// Prepare the thread pool for init tasks that can be parallelized

SystemServerInitThreadPool.start();

// Attach JVMTI agent if this is a debuggable build and the system property is set.

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

}

// Setup the default WTF handler

RuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf);

// Start services.

try {

t.traceBegin("StartServices");

startBootstrapServices(t);

startCoreServices(t);

startOtherServices(t);

} catch (Throwable ex) {

Slog.e("System", "******************************************");

Slog.e("System", "************ Failure starting system services", ex);

throw ex;

} finally {

t.traceEnd(); // StartServices

}

StrictMode.initVmDefaults(null);

if (!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);

}

}

// Diagnostic to ensure that the system is in a base healthy state. Done here as a common

// non-zygote process.

if (!VMRuntime.hasBootImageSpaces()) {

Slog.wtf(TAG, "Runtime is not running with a boot image!");

}

// Loop forever.

Looper.loop();

throw new RuntimeException("Main thread loop unexpectedly exited");

}

SystemServer.run() 是 Android Framework 中 system_server 进程的"主函数",在 Zygote fork 出 system_server 之后被调用。它负责把 Android 运行所需的所有"系统服务"逐个创建、初始化并发布到 ServiceManager,最终进入 Looper 循环等待 Binder 事务。下面把 300 多行代码按功能阶段拆解说明。

──────────────────

  1. 初始化计时与 trace ────────────────── TimingsTraceAndSlog t = new TimingsTraceAndSlog(); t.traceBegin("InitBeforeStartServices");
  • 开启 systrace 区间,方便性能分析工具抓取。

────────────────── 2. 记录启动信息到系统属性 + event log ────────────────── SystemProperties.set(SYSPROP_START_COUNT, ...); SystemProperties.set(SYSPROP_START_ELAPSED, ...); SystemProperties.set(SYSPROP_START_UPTIME, ...); EventLog.writeEvent(EventLogTags.SYSTEM_SERVER_START, ...);

  • mStartCount:本次开机 system_server 被重启的次数(0 代表第一次)。

  • mRuntimeStartElapsedTime / mRuntimeStartUptime:从开机到此刻的 elapsedRealTime / uptimeMillis。 这些信息后续可被 dumpsys、bootstat、metrics 等抓取。

────────────────── 3. 检查并补全 persist.sys.timezone ────────────────── 如果 persist.sys.timezone 为空,则设为 "GMT"。

────────────────── 4. 将旧式语言属性迁移到 persist.sys.locale ────────────────── persist.sys.language / country / localevar 只在早期版本使用。

若仍残留,则以 Locale.getDefault().toLanguageTag() 生成新格式并存入 persist.sys.locale,然后把旧属性清空。

────────────────── 5. 全局行为开关 ────────────────── Binder.setWarnOnBlocking(true);

  • system_server 禁止进行阻塞式 Binder 调用,否则打印警告。

PackageItemInfo.forceSafeLabels();

  • 强制所有包解析时加载"safe labels",防止解析 apk 时引入不受信任的字符串。

SQLiteGlobal.sDefaultSyncMode = FULL;

  • 系统进程使用 FULL sync,保证数据安全。

SQLiteCompatibilityWalFlags.init(null);

  • 先禁用 WAL-compat flag,等 settings provider 起来后再决定。

────────────────── 6. 系统级环境准备 ────────────────── Slog.i(TAG, "Entered the Android system server!");

  • 打 log 供 logcat 过滤。

SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());

VMRuntime.getRuntime().clearGrowthLimit();

  • 取消 Dalvik/ART 的 heap growth limit,允许 system_server 用更多 RAM。

Build.ensureFingerprintProperty();

  • 确保 ro.build.fingerprint 已生成。

Environment.setUserRequired(true);

  • 以后所有访问 Environment 路径必须指定 user handle,避免 user 0 隐式依赖。

BaseBundle.setShouldDefuse(true); Parcel.setStackTraceParceling(true); BinderInternal.disableBackgroundScheduling(true); BinderInternal.setMaxThreads(sMaxBinderThreads);

  • 防止恶意 Bundle、异常序列化泄露,确保所有 Binder 调用以最高优先级运行,并把 Binder 线程池上限调到 31/63(视版本)。

────────────────── 7. 主线程 Looper 初始化 ────────────────── Looper.prepareMainLooper(); Looper.getMainLooper().setSlowLogThresholdMs(...);

  • system_server 的主线程变为 "ActivityManager" 线程。

────────────────── 8. 加载 native 库 & 调试功能 ────────────────── System.loadLibrary("android_servers");

  • 加载 libandroid_servers.so,内含 SurfaceFlinger、Sensor、Audio 等 native 服务 JNI。

initZygoteChildHeapProfiling();

  • 如果系统属性 ro.config.hw_perf 等开启,则启动 heap profile。

if (Build.IS_DEBUGGABLE) spawnFdLeakCheckThread();

  • debug 版会起子线程每 30 s 扫描 /proc/self/fd,发现泄漏就 dump。

performPendingShutdown();

  • 检查 /data/system/shutdown-request.dat,如果上次关机失败则直接关机或重启。

────────────────── 9. 创建系统 Context 与 ServiceManager ────────────────── createSystemContext();

  • 创建 system Context(package = "android",theme = system),加载 framework-res.apk。

ActivityThread.initializeMainlineModules();

  • 把 Mainline 模块(如 ART 模块、Statsd、Media 组件等)提前初始化。

mSystemServiceManager = new SystemServiceManager(mSystemContext); LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); SystemServerInitThreadPool.start();

  • SystemServiceManager 负责以后 startService 的生命周期;并行线程池用于加速初始化。

────────────────── 10. 可选 JVMTI agent ────────────────── debuggable 版本如果 persist.sys.dalvik.jvmtiagent 指定了 agent,则 attach。

t.traceEnd(); // InitBeforeStartServices

────────────────── 11. 设置默认 WTF handler ────────────────── RuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf);

  • 捕获系统早期 crash,避免直接 kill system_server。

────────────────── 12. 启动三大类服务 ────────────────── t.traceBegin("StartServices"); startBootstrapServices(t); // 基础、必须在早期启动 startCoreServices(t); // 平台核心服务 startOtherServices(t); // 剩余所有服务 t.traceEnd();

(下面列出典型包含的服务,具体版本有差异)

12.1 startBootstrapServices()

  • Installer (增量安装 native 侧)

  • DeviceIdentifiersPolicyService

  • ActivityManagerService (ATM + AMS)

  • PowerManagerService

  • RecoverySystemService

  • LightsService

  • DisplayManagerService

  • PackageManagerService

  • UserManagerService

  • OverlayManagerService

  • SensorPrivacyService

  • (P)SensorService

  • (P)BluetoothService

  • ...

12.2 startCoreServices()

  • BatteryService

  • UsageStatsService

  • WebViewUpdateService

  • BinderCallsStatsService

  • ...

12.3 startOtherServices()

  • AccountManagerService

  • ContentService

  • VibratorService

  • AlarmManagerService

  • InputManagerService

  • WindowManagerService

  • BluetoothService (部分版本移到 bootstrap)

  • TelecomLoaderService

  • ConnectivityService

  • NetworkManagementService

  • NetworkStatsService

  • NetworkPolicyManagerService

  • WifiService

  • WifiScanningService

  • AudioService

  • CameraService

  • TrustManagerService

  • JobSchedulerService

  • ShortcutService

  • NotificationManagerService

  • DevicePolicyManagerService

  • StatusBarManagerService

  • ClipboardService

  • NetworkTimeUpdateService

  • CommonTimeManagementService

  • InputMethodManagerService

  • TextServicesManagerService

  • ...(总计 100+)

每个服务通过 SystemServiceManager.startService() 或 ServiceManager.addService() 注册。 细节见 SystemServer.java 的各 start*Services() 方法,此处略。

────────────────── 13. StrictMode 默认策略 ────────────────── StrictMode.initVmDefaults(null);

  • system_server 自己也要受 StrictMode 检查,防止系统代码违规。

────────────────── 14. 记录系统就绪时间 & 诊断 ────────────────── if (!mRuntimeRestart && !isFirstBootOrUpgrade()) { FrameworkStatsLog.write(... SYSTEM_SERVER_READY ...); if (uptimeMillis > 60 s) Slog.wtf ... }

  • 如果非重启且非 OTA,则把 "system_server 从 init 到 ready" 耗时发送给 statsd。

  • 超过 60 s 打 WTF(系统启动异常慢)。

if (!VMRuntime.hasBootImageSpaces()) Slog.wtf ...

  • 如果当前 ART 没有 boot image,则系统性能会严重下降,打 WTF。

────────────────── 15. 进入主循环 ────────────────── Looper.loop();

  • system_server 主线程开始处理 Binder、Handler 消息队列,永不返回。

  • 如果 loop() 意外退出,抛 RuntimeException,SystemServer 会触发重启 UI 或直接重启系统。

────────────────── 小结 ────────────────── run() 的工作可以概括为:

  1. 记录启动信息

  2. 设置系统属性、时区、locale、SQLite、Binder、环境等全局状态

  3. 创建 system context 和 SystemServiceManager

  4. 并行/顺序地启动 100+ 系统服务

  5. 进入 Looper,把线程变成 Binder 服务端,永远处理事务

这些步骤完成后,Android Framework 层才算真正"跑起来",应用进程才能通过 Binder 调用 AMS、WMS、PKMS 等系统服务。