Android SystemServer进程启动流程
Zygote是所有应用的鼻祖。SystemServer和其他所有Dalivik虚拟机进程都是由Zygote fork而来。Zygote fork的第一个进程就是SystemServer,其在手机中的进程名为 system_server。
Android系统启动篇
4,《Android SystemServer进程启动流程》
Android系统开发准备篇
3,《Android Framework代码IDE加载和调试》
Android系统开发实践篇
4,《android单独编译framework模块并push》
Android系统开发核心知识储备篇
1,《Android编译系统-envsetup和lunch代码篇》
6,《Android中Activity、View和Window关系详解》
11,《android中AMS进程通知Zygote进程fork新进程的通信方式》
Android核心功能详解篇
2,《Android 手势导航(从下往上滑动进入多任务页面)》
3,《android手势分析(应用界面左往右边滑动退出应用)》
———————————————————————————————————————————
目录
一,基础介绍
Zygote是所有应用的鼻祖。SystemServer和其他所有Dalivik虚拟机进程都是由Zygote fork而来。Zygote fork的第一个进程就是SystemServer,其在手机中的进程名为 system_server。
system_server 进程承载着整个framework的核心服务,例如用来创建ActivityManagerService、PowerManagerService、DisplayManagerService、PackageManagerService、WindowManagerService、LauncherAppsService等核心系统服务
启动流程如下:
1,Zygote启动后fork的第一个进程为SystemServer,在手机中的进程别名为"system_server",主要用来启动系统中的服务
2,Zygote fork后,进入SystemServer的main()
3,SystemServer在启动过程中,先初始化一些系统变量,加载类库,创建Context对象,创建SystemServiceManager对象等候再启动服务
4,启动的服务分为 引导服务(Boot Service)、核心服务(Core Service)和其他服务(Other Service)三大类
5,SystemServer在启动服务前,会尝试与Zygote建立Socket通信,通信成功后才去启动服务
启动的服务都单独运行在SystemServer的各自线程中,同属于SystemServer进程
二,代码分析
2.1 入口
Zygote进程,通过fork()函数,最终孵化出system_server的进程,通过反射的方法启动
SystemServer.java的main()方法
位置:/frameworks/base/services/java/com/android/server/SystemServer.java
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}
2.2 run()流程
在run()主要是做了一些初始化工作,现在我们来看看初始化的:
1,初始化必要的SystemServer环境参数,如系统时间,默认时区和load一些Library等等,
2,初始化Looper,在主线程中使用的looper就是在SystemServer进行初始化,
3,初始化Context,只有初始化一个Context才能启动Service的操作。
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"));
}
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");
//如果时区为空,设置时区为GMT
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!
//清除vm内存增长限制,由于启动过程需要更多的虚拟机内存空间
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
//设置system_server进程中binder线程的最大数量为31
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.
//加载android_servers.so库,初始化native service
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
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
//将mSystemServiceManager添加到本地服务的成员sLocalServiceObjects
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");
}
2.3 createSystemContext
private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain();
//设置系统context
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
位置:/frameworks/base/core/java/android/app/ActivityThread.java
public ContextImpl getSystemContext() {
synchronized (this) {
if (mSystemContext == null) {
mSystemContext = ContextImpl.createSystemContext(this);
}
return mSystemContext;
}
}
三,启动核心服务
3.1 startBootstrapServices
用于启动系统Boot级服务,有ActivityManagerService, PowerManagerService, LightsService, DisplayManagerService, PackageManagerService, UserManagerService, sensor服务.
private void startBootstrapServices() {
traceBeginAndSlog("StartWatchdog");
//启动watchdog
//尽早启动watchdog,如果在早起启动时发生死锁,我们可以让system_server
//崩溃,从而进行详细分析
final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();
traceEnd();
...
//添加PLATFORM_COMPAT_SERVICE,Platform compat服务被ActivityManagerService、PackageManagerService
//以及将来可能出现的其他服务使用。
traceBeginAndSlog("PlatformCompat");
ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE,
new PlatformCompat(mSystemContext));
traceEnd();
//阻塞等待installd完成启动,以便有机会创建具有适当权限的关键目录,如/data/user。
//我们需要在初始化其他服务之前完成此任务。
traceBeginAndSlog("StartInstaller");
Installer installer = mSystemServiceManager.startService(Installer.class);
traceEnd();
...
//启动服务ActivityManagerService,并为其设置mSystemServiceManager和installer
traceBeginAndSlog("StartActivityManager");
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();
traceEnd();
//启动服务PowerManagerService
//Power manager需要尽早启动,因为其他服务需要它。
//本机守护进程可能正在监视它的注册,
//因此它必须准备好立即处理传入的绑定器调用(包括能够验证这些调用的权限)
。
traceBeginAndSlog("StartPowerManager");
mPowerManagerService = mSystemServiceManager.startService(
PowerManagerService.class);
traceEnd();
...
//初始化power management
traceBeginAndSlog("InitPowerManagement");
mActivityManagerService.initPowerManagement();
traceEnd();
//启动recovery system,以防需要重新启动
traceBeginAndSlog("StartRecoverySystemService");
mSystemServiceManager.startService(RecoverySystemService.class);
traceEnd();
...
//启动服务LightsService
//管理led和显示背光,所以我们需要它来打开显示
traceBeginAndSlog("StartLightsService");
mSystemServiceManager.startService(LightsService.class);
traceEnd();
...
//启动服务DisplayManagerService
//显示管理器需要在包管理器之前提供显示指标
traceBeginAndSlog("StartDisplayManager");
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
traceEnd();
// Boot Phases: Phase100: 在初始化package manager之前,需要默认的显示.
traceBeginAndSlog("WaitForDisplay");
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
traceEnd();
//当设备正在加密时,仅运行核心
String cryptState = VoldProperties.decrypt().orElse("");
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;
}
...
//启动服务PackageManagerService
traceBeginAndSlog("StartPackageManagerService");
try {
Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
} finally {
Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
}
...
//启动服务UserManagerService,新建目录/data/user/
traceBeginAndSlog("StartUserManagerService");
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
traceEnd();
// Set up the Application instance for the system process and get started.
//为系统进程设置应用程序实例并开始。
//设置AMS
traceBeginAndSlog("SetSystemProcess");
mActivityManagerService.setSystemProcess();
traceEnd();
//使用一个ActivityManager实例完成watchdog设置并监听重启,
//只有在ActivityManagerService作为一个系统进程正确启动后才能这样做
traceBeginAndSlog("InitWatchdog");
watchdog.init(mSystemContext, mActivityManagerService);
traceEnd();
//传感器服务需要访问包管理器服务、app ops服务和权限服务,
//因此我们在它们之后启动它。
//在单独的线程中启动传感器服务。在使用它之前应该检查完成情况。
mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
TimingsTraceLog traceLog = new TimingsTraceLog(
SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.
TRACE_TAG_SYSTEM_SERVER);
traceLog.traceBegin(START_SENSOR_SERVICE);
startSensorService(); //启动传感器服务
traceLog.traceEnd();
}, START_SENSOR_SERVICE);
}
3.2 startCoreServices
启动核心服务BatteryService,UsageStatsService,WebViewUpdateService、BugreportManagerService、GpuService等.
private void startCoreServices() {
//启动服务BatteryService,用于统计电池电量,需要LightService.
mSystemServiceManager.startService(BatteryService.class);
//启动服务UsageStatsService,用于统计应用使用情况
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
//启动服务WebViewUpdateService
//跟踪可更新的WebView是否处于就绪状态,并监视更新安装
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
}
//启动CachedDeviceStateService,跟踪和缓存设备状态
mSystemServiceManager.startService(CachedDeviceStateService.class);
//启动BinderCallsStatsService, 跟踪在绑定器调用中花费的cpu时间
traceBeginAndSlog("StartBinderCallsStatsService");
mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);
traceEnd();
//启动LooperStatsService,跟踪处理程序中处理消息所花费的时间。
traceBeginAndSlog("StartLooperStatsService");
mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);
traceEnd();
//启动RollbackManagerService,管理apk回滚
mSystemServiceManager.startService(RollbackManagerService.class);
//启动BugreportManagerService,捕获bugreports的服务
mSystemServiceManager.startService(BugreportManagerService.class);
//启动GpuService,为GPU和GPU驱动程序提供服务。
mSystemServiceManager.startService(GpuService.class);
}
3.3 startOtherServices
启动其他的服务,开始处理一大堆尚未重构和整理的东西,这里的服务比较多,
private void startOtherServices() {
...
//启动TelecomLoaderService,通话相关核心服务
mSystemServiceManager.startService(TelecomLoaderService.class);
//启动TelephonyRegistry
telephonyRegistry = new TelephonyRegistry(context);
ServiceManager.addService("telephony.registry", telephonyRegistry);
...
//启动AlarmManagerService,时钟管理
mSystemServiceManager.startService(new AlarmManagerService(context));
...
//启动InputManagerService
inputManager = new InputManagerService(context);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
...
inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback());
inputManager.start();
...
//Phase480:在接收到此启动阶段后,服务可以获得锁设置数据
mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
//Phase500:在接收到这个启动阶段之后,服务可以安全地调用核心系统服务,
//如PowerManager或PackageManager。
mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
mActivityManagerService.systemReady(() -> {
//Phase550:在接收到此引导阶段后,服务可以广播意图。
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY);
//Phase600:在接收到这个启动阶段后,服务可以启动/绑定到第三方应用程序。
//此时,应用程序将能够对服务进行绑定调用。
mSystemServiceManager.startBootPhase(
SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
}
}
更多推荐
所有评论(0)