Read The Fucking Source Code. —— Linus 站在’巨人’的肩膀上开始自己的旅途。—— 佚名 愉快的周末,从打开💻开始,到骑行归来结束。—— 佚名
文章系列
注: 本系列文章源码基于 Android 11-r21 master 分支
相关文件
- /framework/base/service/java/com/android/server/SystemServer.java
- /framework/base/service/java/com/android/server/SystemServiceManager.java
- /framework/base/service/java/com/android/server/WatchDog.java
- /frameworks/base/core/java/com/android/server/SystemConfig.java
- … etc
执行 System server
经过前两篇的系统文章,已经完成了 init、zygote 进程的创建和初始化,即将启动系统各大服务,各项服务由服务管理者 System server 完成创建和启动,那么赶紧进入瞧瞧去/framework/base/service/java/com/android/server/SystemServer.java
public final class SystemServer implements Dumpable {
private static final String WIFI_SERVICE_CLASS =
"com.android.server.wifi.WifiService";
private static final String WIFI_SCANNING_SERVICE_CLASS =
"com.android.server.wifi.scanner.WifiScanningService";
private static final String ALARM_MANAGER_SERVICE_CLASS =
"com.android.server.alarm.AlarmManagerService";
... etc
private static final int DEFAULT_SYSTEM_THEME =
com.android.internal.R.style.Theme_DeviceDefault_System;
private SystemServiceManager mSystemServiceManager;
private ActivityManagerService mActivityManagerService;
private PackageManagerService mPackageManagerService;
private ContentResolver mContentResolver;
private DisplayManagerService mDisplayManagerService;
private static LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> sPendingWtfs;
private static native void startMemtrackProxyService();
private static native void startHidlServices();
private static native void initZygoteChildHeapProfiling();
public static void main(String[] args) {
new SystemServer().run();
}
}
public SystemServer() {
mFactoryTestMode = FactoryTest.getMode();
mStartCount = SystemProperties.getInt(SYSPROP_START_COUNT, 0) + 1;
mRuntimeStartElapsedTime = SystemClock.elapsedRealtime();
mRuntimeStartUptime = SystemClock.uptimeMillis();
Process.setStartTimes(mRuntimeStartElapsedTime, mRuntimeStartUptime);
mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));
}
private void run() {
SystemProperties.set(SYSPROP_START_COUNT,String.valueOf(mStartCount));
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);
}
VMRuntime.getRuntime().clearGrowthLimit();
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);
createSystemContext();
mSystemServiceManager = new SystemServiceManager(mSystemContext);
SystemServerInitThreadPool tp = SystemServerInitThreadPool.start();
startBootstrapServices(t);
startCoreServices(t);
startOtherServices(t);
StrictMode.initVmDefaults(null);
Looper.loop();
}
启动 Bootstrap 服务
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();
final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
SystemServerInitThreadPool.submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
PlatformCompat platformCompat = new PlatformCompat(mSystemContext);
ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE, platformCompat);
ServiceManager.addService(Context.PLATFORM_COMPAT_NATIVE_SERVICE,
new PlatformCompatNative(platformCompat));
mSystemServiceManager.startService(FileIntegrityService.class);
Installer installer = mSystemServiceManager.startService(Installer.class);
SystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);
mSystemServiceManager.startService(PowerStatsService.class);
startMemtrackProxyService();
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
mDataLoaderManagerService = mSystemServiceManager.startService(
DataLoaderManagerService.class);
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class);
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
domainVerificationService, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF,
mOnlyCore);
mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext));
mSystemServiceManager.startService(SensorService.class);
}
启动服务到这里就结束啦,只是部分列举,并不完整,服务是如何运行的?具体都在做了些什么?等等!!!
这些执行细节希望在之后的系列文章进一步深入(内容实在是太多了😭)
启动 Core 服务
private void startCoreServices(@NonNull TimingsTraceAndSlog t) {
mSystemServiceManager.startService(SystemConfigService.class);
mSystemServiceManager.startService(BatteryService.class);
mSystemServiceManager.startService(UsageStatsService.class);
mSystemServiceManager.startService(CachedDeviceStateService.class);
mSystemServiceManager.startService(ROLLBACK_MANAGER_SERVICE_CLASS);
mSystemServiceManager.startService(NativeTombstoneManagerService.class);
mSystemServiceManager.startService(BugreportManagerService.class);
mSystemServiceManager.startService(GpuService.class);
}
核心服务不是很多,主要是信息记录相关,必不可少、确实很是关键。
启动 Other 服务
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
try {
mSystemServiceManager.startService(ALARM_MANAGER_SERVICE_CLASS);
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_SENSOR_SERVICE);
wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
ServiceManager.addService(Context.WINDOW_SERVICE, wm, false,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
false, DUMP_FLAG_PRIORITY_CRITICAL);
if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
Slog.i(TAG, "No Bluetooth Service (factory test)");
} else if (!context.getPackageManager().hasSystemFeature
(PackageManager.FEATURE_BLUETOOTH)) {
Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");
} else {
mSystemServiceManager.startService(BluetoothService.class);
}
mSystemServiceManager.startService(NetworkWatchlistService.Lifecycle.class);
if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) {
mSystemServiceManager.startService(
MultiClientInputMethodManagerService.Lifecycle.class);
} else {
mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);
}
try {
mSystemServiceManager.startService(ACCESSIBILITY_MANAGER_SERVICE_CLASS);
} catch (Throwable e) {
reportWtf("starting Accessibility Manager", e);
}
if (hasPdb || OemLockService.isHalPresent()) {
mSystemServiceManager.startService(OemLockService.class);
}
try {
statusBar = new StatusBarManagerService(context);
ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
} catch (Throwable e) {
}
startContentCaptureService(context, t);
startAttentionService(context, t);
startRotationResolverService(context, t);
startSystemCaptionsManagerService(context, t);
startTextToSpeechManagerService(context, t);
mSystemServiceManager.startService(SPEECH_RECOGNITION_MANAGER_SERVICE_CLASS);
mSystemServiceManager.startService(SMARTSPACE_MANAGER_SERVICE_CLASS);
try {
networkManagement = NetworkManagementService.create(context);
ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
} catch (Throwable e) {
}
mSystemServiceManager.startService(new FontManagerService.Lifecycle(context, safeMode));
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI)) {
mSystemServiceManager.startServiceFromJar(
WIFI_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
mSystemServiceManager.startServiceFromJar(
WIFI_SCANNING_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
}
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI_RTT)) {
mSystemServiceManager.startServiceFromJar(
WIFI_RTT_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
}
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI_AWARE)) {
mSystemServiceManager.startServiceFromJar(
WIFI_AWARE_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
}
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI_DIRECT)) {
mSystemServiceManager.startServiceFromJar(
WIFI_P2P_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
}
try {
vpnManager = VpnManagerService.create(context);
ServiceManager.addService(Context.VPN_MANAGEMENT_SERVICE, vpnManager);
} catch (Throwable e) {
}
t.traceEnd();
t.traceBegin("StartVcnManagementService");
try {
vcnManagement = VcnManagementService.create(context);
ServiceManager.addService(Context.VCN_MANAGEMENT_SERVICE, vcnManagement);
} catch (Throwable e) {
reportWtf("starting VCN Management Service", e);
}
t.traceEnd();
try {
ServiceManager.addService(Context.SYSTEM_UPDATE_SERVICE,
new SystemUpdateManagerService(context));
} catch (Throwable e) {
}
mSystemServiceManager.startService(NotificationManagerService.class);
SystemNotificationChannels.removeDeprecated(context);
SystemNotificationChannels.createAll(context);
notification = INotificationManager.Stub.asInterface(
ServiceManager.getService(Context.NOTIFICATION_SERVICE));
if (context.getResources().getBoolean(R.bool.config_enableWallpaperService)) {
mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
} else {
}
if (!isArc) {
mSystemServiceManager.startService(AudioService.Lifecycle.class);
} else {
String className = context.getResources()
.getString(R.string.config_deviceSpecificAudioService);
try {
mSystemServiceManager.startService(className + "$Lifecycle");
} catch (Throwable e) {
}
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BROADCAST_RADIO)) {
t.traceBegin("StartBroadcastRadioService");
mSystemServiceManager.startService(BroadcastRadioService.class);
t.traceEnd();
}
try {
mSystemServiceManager.startService(ADB_SERVICE_CLASS);
} catch (Throwable e) {
Slog.e(TAG, "Failure starting AdbService");
}
mSystemServiceManager.startService(LauncherAppsService.class);
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_LOCK_SETTINGS_READY);
mPackageManagerService.systemReady();
mDisplayManagerService.systemReady(safeMode, mOnlyCore);
... etc
mPackageManagerService.waitForAppDataPrepared();
countryDetectorF.systemRunning();
networkTimeUpdaterF.systemRunning();
inputManagerF.systemRunning();
telephonyRegistryF.systemRunning();
mmsServiceF.systemRunning();
... etc
startSystemUi(context, windowManagerF);
}
}
启动 SystemUI 服务
private static void startSystemUi(Context context, WindowManagerService windowManager) {
PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
Intent intent = new Intent();
system UI 服务列表
//通知渠道服务(Android 低版本的通知创建是不需要设置通知渠道,后来高版本引入通知渠道并且必须设置,否则通知显示存在异常)
<item>com.android.systemui.util.NotificationChannels</item>
<item>com.android.systemui.keyguard.KeyguardViewMediator</item>
//应用最近任务列表
<item>com.android.systemui.recents.Recents</item>
//音量
<item>com.android.systemui.volume.VolumeUI</item>
<item>com.android.systemui.stackdivider.Divider</item>
//状态栏
<item>com.android.systemui.statusbar.phone.StatusBar</item>
<item>com.android.systemui.usb.StorageNotification</item>
<item>com.android.systemui.power.PowerUI</item>
<item>com.android.systemui.media.RingtonePlayer</item>
//键盘
<item>com.android.systemui.keyboard.KeyboardUI</item>
<item>com.android.systemui.pip.PipUI</item>
<item>com.android.systemui.shortcut.ShortcutKeyDispatcher</item>
<item>@string/config_systemUIVendorServiceComponent</item>
<item>com.android.systemui.util.leak.GarbageMonitor$Service</item>
<item>com.android.systemui.LatencyTester</item>
<item>com.android.systemui.globalactions.GlobalActionsComponent</item> <item>com.android.systemui.ScreenDecorations</item>
<item>com.android.systemui.biometrics.AuthController</item>
<item>com.android.systemui.SliceBroadcastRelayHandler</item>
<item>com.android.systemui.SizeCompatModeActivityController</item>
<item>com.android.systemui.statusbar.notification.InstantAppNotifier</item>
<item>com.android.systemui.theme.ThemeOverlayController</item>
<item>com.android.systemui.accessibility.WindowMagnification</item>
<item>com.android.systemui.accessibility.SystemActions</item>
<item>com.android.systemui.toast.ToastUI</item>
System Server 大概是启动完成,那么接下来又去哪里运行了呢???或者下一步我们继续看那个点比较合适呢???
之前我们只是粗略浏览,中间忽略了很多,下一步的入口点可能要返回之前的代码重新阅读发现合适的切入点,SystemServer 也已经进入了‘永久的循环’,等待的就是接受外部‘信号’做相应处理、继续分发到具体执行。
那么,我们下周再见😊
附加
如何快速搜索
Android 项目中如何快速搜索某关键字?
AOSP 整个项目是很庞大的,不仅仅是包含 java 代码,就拿当前我下载的 Android 11-r21 分支 来说,我是通过 git 下载在没有指定 single-branch dept=1 参数下,整个过程下载完毕占用大约 430G 存储空间。
一开始我把源码存储在机械硬盘,通过 VSCode 打开机存在械硬盘的中的项目(整个 AOSP),比如搜索某个关键字,那个速度堪比龟速;后来把项目拷贝到笔记本 SSD 固态硬盘,搜索速度确实有了明显的提高,但整个项目搜索还是比较慢,不是十分满意;如果是单独打开某个模块——— framework 模块、framework base 模块等等,搜索速度还可以接受。但如果要找的代码根本不在当前模块,比如你打开 framework base 模块,但实际代码在 framework service 模块,这样是搜索不到结果的,因此还得把搜索范围扩大,引入的模块多了速度终是会变慢。
搜索能够快速找到目标,是不是要借助一个东西————索引,如果有工具把 AOSP 整个项目预先建立索引,然后再打开项目搜索,下次搜索时无需重新创建索引,通过索引搜索不得要起飞。与搜索相关索引确实是个好东西。
【最后】
推荐使用已有的在线网站辅助搜索:基于 opengrok 的 AOSPXRef
以搜索 SystemUIService config_systemUIServiceComponent 为例: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fWaOCdnl-1659507116952)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f6d6877806a144cfb2a73a40aa569c01~tplv-k3u1fbpfcp-watermark.image?)]
【最后的最后】
ASOPXRef 现有的项目是较少的,也就是几个特定的版本,如果能满足自己的需求刚好,要是想看的源码版本不是已存在的建议还是自己通过 opengrok 引擎搭建一个服务。 Oracle opengrok:快速且可用的源代码搜索和交叉引用引擎
参考链接
- WTF:What a Terrible Failure —— Android 系统错误记录的一种
- Memtrack:内存分析 https://zhuanlan.zhihu.com/p/168361476
- Hidl:硬件抽象层,在较低 Android 版本可能还在使用 HAL (hardware abstract layer)https://zhuanlan.zhihu.com/p/28256541
- Android Uri:https://www.cnblogs.com/bhlsheji/p/4246580.html
- Android 错误报告:https://developer.android.com/studio/debug/bug-report ,https://source.android.com/source/read-bug-reports.html
- Android 墓碑:https://source.android.com/devices/tech/debug
|