赞
踩
上次说到,从Zygote.forkSystemServer()一直到SystemServer.main()。这篇博客,将从SystemServer的main方法开始说起。没看过SystemServer(一)的可以先去看一下:Android FrameWork之SystemServer(一)
首先,SystemServer.java的路径如下:/frameworks/base/services/java/com/android/server/SystemServer.java。我们看一下其main()方法:
- /**
- * The main entry point from zygote.
- */
- public static void main(String[] args) {
- new SystemServer().run();
- }
非常简短的方法,创建一个SystemServerd对象,然后调用其run()方法。
run()方法是一个很长的方法,其实也还好,注释占了很大一部分篇幅,源码如下:
- private void run() {
- try {
- traceBeginAndSlog("InitBeforeStartServices");
- // If a device's clock is before 1970 (before 0), a lot of
- // APIs crash dealing with negative numbers, notably
- // java.io.File#setLastModified, so instead we fake it and
- // hope that time from cell towers or NTP fixes it shortly.
- if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
- Slog.w(TAG, "System clock is before 1970; setting to 1970.");
- SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
- }
-
- //
- // 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.setForceSafeLabels(true);
- // Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
- SQLiteCompatibilityWalFlags.init(null);
-
- // Here we go!
- Slog.i(TAG, "Entered the Android system server!");
- int uptimeMillis = (int) SystemClock.elapsedRealtime();
- EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
- if (!mRuntimeRestart) {
- MetricsLogger.histogram(null, "boot_system_server_init", 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 | xq oqi'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();
-
- // The system server has to run all of the time, so it needs to be
- // as efficient as possible with its memory usage.
- VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
-
- // 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);
-
- // Initialize native services.
- System.loadLibrary("android_servers");
-
- // Check whether we failed to shut down last time we tried.
- // This call may not return.
- performPendingShutdown();
-
- // Initialize the system context.
- createSystemContext();
-
- // 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.get();
- } finally {
- traceEnd(); // InitBeforeStartServices
- }
-
- // Start services.
- try {
- traceBeginAndSlog("StartServices");
- startBootstrapServices();
- startCoreServices();
- startOtherServices();
- SystemServerInitThreadPool.shutdown();
- } catch (Throwable ex) {
- Slog.e("System", "******************************************");
- Slog.e("System", "************ Failure starting system services", ex);
- throw ex;
- } finally {
- traceEnd();
- }
-
- StrictMode.initVmDefaults(null);
-
- if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
- int uptimeMillis = (int) SystemClock.elapsedRealtime();
- MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
- final int MAX_UPTIME_MILLIS = 60 * 1000;
- if (uptimeMillis > MAX_UPTIME_MILLIS) {
- Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
- "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
- }
- }
-
- // Loop forever.
- Looper.loop();
- throw new RuntimeException("Main thread loop unexpectedly exited");
- }
run()方法主要做了哪些工作?让我们一起跟着源码和注释分析一下:
(1)如果系统时间早于1970年,则设置系统时间为1970年
- if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
- Slog.w(TAG, "System clock is before 1970; setting to 1970.");
- SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
- }
(2)如果时区没有设置,设置时区为GMT(格林尼治标准时间)
- if (timezoneProperty == null || timezoneProperty.isEmpty()) {
- Slog.w(TAG, "Timezone not set; setting to GMT.");
- SystemProperties.set("persist.sys.timezone", "GMT");
- }
(3)设置语言,国家,地区等(只有system server或者系统app才能修改)
- 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", "");
- }
(4)变更库文件,因为默认使用的是libart.so
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
(5)清除内存增长上限,为启动过程提供更多的内存空间
VMRuntime.getRuntime().clearGrowthLimit();
(6)设置内存可能的利用率为0.8
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
(7)在开机完成前定义指纹信息
Build.ensureFingerprintProperty();
(8)设置Binder的优先级和最大线程数
- BinderInternal.disableBackgroundScheduling(true);
-
- BinderInternal.setMaxThreads(sMaxBinderThreads);
(9)准备主线程Looper
- // 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);
(10)初始化系统上下文
createSystemContext();
(11)创建System Service Manager
- mSystemServiceManager = new SystemServiceManager(mSystemContext);
- mSystemServiceManager.setStartInfo(mRuntimeRestart,
- mRuntimeStartElapsedTime, mRuntimeStartUptime);
- LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
(12)启动各种系统服务
- traceBeginAndSlog("StartServices");
- startBootstrapServices();
- startCoreServices();
- startOtherServices();
- SystemServerInitThreadPool.shutdown();
(13)循环执行
- // Loop forever.
- Looper.loop();
做的主要工作是启动一些服务,例如我们常说的:ActivityManagerService, PowerManagerService,DisplayManagerService, PackageManagerService等。
- /**
- * Starts the small tangle of critical services that are needed to get
- * the system off the ground. These services have complex mutual dependencies
- * which is why we initialize them all in one place here. Unless your service
- * is also entwined in these dependencies, it should be initialized in one of
- * the other functions.
- */
- private void startBootstrapServices() {
- Slog.i(TAG, "Reading configuration...");
- final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
- traceBeginAndSlog(TAG_SYSTEM_CONFIG);
- SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
- traceEnd();
-
- // Wait for installd to finish starting up so that it has a chance to
- // create critical directories such as /data/user with the appropriate
- // permissions. We need this to complete before we initialize other services.
- traceBeginAndSlog("StartInstaller");
- Installer installer = mSystemServiceManager.startService(Installer.class);
- traceEnd();
-
- // In some cases after launching an app we need to access device identifiers,
- // therefore register the device identifier policy before the activity manager.
- traceBeginAndSlog("DeviceIdentifiersPolicyService");
- mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
- traceEnd();
-
- // Activity manager runs the show.
- traceBeginAndSlog("StartActivityManager");
- mActivityManagerService = mSystemServiceManager.startService(
- ActivityManagerService.Lifecycle.class).getService();
- mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
- mActivityManagerService.setInstaller(installer);
- traceEnd();
-
- // Power manager needs to be started early because other services need it.
- // Native daemons may be watching for it to be registered so it must be ready
- // to handle incoming binder calls immediately (including being able to verify
- // the permissions for those calls).
- traceBeginAndSlog("StartPowerManager");
- mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
- traceEnd();
-
- // Now that the power manager has been started, let the activity manager
- // initialize power management features.
- traceBeginAndSlog("InitPowerManagement");
- mActivityManagerService.initPowerManagement();
- traceEnd();
-
- // Bring up recovery system in case a rescue party needs a reboot
- traceBeginAndSlog("StartRecoverySystemService");
- mSystemServiceManager.startService(RecoverySystemService.class);
- traceEnd();
-
- // Now that we have the bare essentials of the OS up and running, take
- // note that we just booted, which might send out a rescue party if
- // we're stuck in a runtime restart loop.
- RescueParty.noteBoot(mSystemContext);
-
- // Manages LEDs and display backlight so we need it to bring up the display.
- traceBeginAndSlog("StartLightsService");
- mSystemServiceManager.startService(LightsService.class);
- traceEnd();
-
- traceBeginAndSlog("StartSidekickService");
- // Package manager isn't started yet; need to use SysProp not hardware feature
- if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
- mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
- }
- traceEnd();
-
- // Display manager is needed to provide display metrics before package manager
- // starts up.
- traceBeginAndSlog("StartDisplayManager");
- mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
- traceEnd();
-
- // We need the default display before we can initialize the package manager.
- traceBeginAndSlog("WaitForDisplay");
- mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
- traceEnd();
-
- // Only run "core" apps if we're encrypting the device.
- String cryptState = SystemProperties.get("vold.decrypt");
- 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;
- }
-
- // Start the package manager.
- if (!mRuntimeRestart) {
- MetricsLogger.histogram(null, "boot_package_manager_init_start",
- (int) SystemClock.elapsedRealtime());
- }
- traceBeginAndSlog("StartPackageManagerService");
- mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
- mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
- mFirstBoot = mPackageManagerService.isFirstBoot();
- mPackageManager = mSystemContext.getPackageManager();
- traceEnd();
- if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
- MetricsLogger.histogram(null, "boot_package_manager_init_ready",
- (int) SystemClock.elapsedRealtime());
- }
- // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
- // A/B artifacts after boot, before anything else might touch/need them.
- // Note: this isn't needed during decryption (we don't have /data anyways).
- if (!mOnlyCore) {
- boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
- false);
- if (!disableOtaDexopt) {
- traceBeginAndSlog("StartOtaDexOptService");
- try {
- OtaDexoptService.main(mSystemContext, mPackageManagerService);
- } catch (Throwable e) {
- reportWtf("starting OtaDexOptService", e);
- } finally {
- traceEnd();
- }
- }
- }
-
- traceBeginAndSlog("StartUserManagerService");
- mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
- traceEnd();
-
- // Initialize attribute cache used to cache resources from packages.
- traceBeginAndSlog("InitAttributerCache");
- AttributeCache.init(mSystemContext);
- traceEnd();
-
- // Set up the Application instance for the system process and get started.
- traceBeginAndSlog("SetSystemProcess");
- mActivityManagerService.setSystemProcess();
- traceEnd();
-
- // DisplayManagerService needs to setup android.display scheduling related policies
- // since setSystemProcess() would have overridden policies due to setProcessGroup
- mDisplayManagerService.setupSchedulerPolicies();
-
- // Manages Overlay packages
- traceBeginAndSlog("StartOverlayManagerService");
- mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));
- traceEnd();
-
- // The sensor service needs access to package manager service, app ops
- // service, and permissions service, therefore we start it after them.
- // Start sensor service in a separate thread. Completion should be checked
- // before using it.
- 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);
- }
启动一些核心的服务:BatteryService,UsageStatsService,WebViewUpdateService。
- /**
- * Starts some essential services that are not tangled up in the bootstrap process.
- */
- private void startCoreServices() {
- traceBeginAndSlog("StartBatteryService");
- // Tracks the battery level. Requires LightService.
- mSystemServiceManager.startService(BatteryService.class);
- traceEnd();
-
- // Tracks application usage stats.
- traceBeginAndSlog("StartUsageService");
- mSystemServiceManager.startService(UsageStatsService.class);
- mActivityManagerService.setUsageStatsManager(
- LocalServices.getService(UsageStatsManagerInternal.class));
- traceEnd();
-
- // Tracks whether the updatable WebView is in a ready state and watches for update installs.
- if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
- traceBeginAndSlog("StartWebViewUpdateService");
- mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
- traceEnd();
- }
-
- // Tracks cpu time spent in binder calls
- traceBeginAndSlog("StartBinderCallsStatsService");
- BinderCallsStatsService.start();
- traceEnd();
- }
SystemServer还会启动一些其他的服务,代码太多,不再一一去看。
最后,总结一下。System Server是zygote进程fork的第一个进程,是android 基本服务的提供者,FrameWork关键的系统服务全由此创建而来。可以说,整个android系统的业务都是围绕system server而展开。一旦SystemServer挂了,整个手机系统也就挂了。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。