1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server;
18 
19 import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
20 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_CRITICAL;
21 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_HIGH;
22 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_NORMAL;
23 import static android.os.IServiceManager.DUMP_FLAG_PROTO;
24 import static android.view.Display.DEFAULT_DISPLAY;
25 
26 import android.annotation.NonNull;
27 import android.annotation.StringRes;
28 import android.app.ActivityThread;
29 import android.app.AppCompatCallbacks;
30 import android.app.INotificationManager;
31 import android.app.usage.UsageStatsManagerInternal;
32 import android.content.ComponentName;
33 import android.content.ContentResolver;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.pm.PackageItemInfo;
37 import android.content.pm.PackageManager;
38 import android.content.res.Configuration;
39 import android.content.res.Resources.Theme;
40 import android.database.sqlite.SQLiteCompatibilityWalFlags;
41 import android.database.sqlite.SQLiteGlobal;
42 import android.hardware.display.DisplayManagerInternal;
43 import android.net.ConnectivityModuleConnector;
44 import android.net.NetworkStackClient;
45 import android.os.BaseBundle;
46 import android.os.Binder;
47 import android.os.Build;
48 import android.os.Debug;
49 import android.os.Environment;
50 import android.os.FactoryTest;
51 import android.os.FileUtils;
52 import android.os.IIncidentManager;
53 import android.os.Looper;
54 import android.os.Message;
55 import android.os.Parcel;
56 import android.os.PowerManager;
57 import android.os.Process;
58 import android.os.ServiceManager;
59 import android.os.StrictMode;
60 import android.os.SystemClock;
61 import android.os.SystemProperties;
62 import android.os.Trace;
63 import android.os.UserHandle;
64 import android.os.storage.IStorageManager;
65 import android.provider.DeviceConfig;
66 import android.provider.Settings;
67 import android.sysprop.VoldProperties;
68 import android.text.TextUtils;
69 import android.util.DisplayMetrics;
70 import android.util.EventLog;
71 import android.util.Slog;
72 import android.util.TimingsTraceLog;
73 import android.view.WindowManager;
74 import android.view.contentcapture.ContentCaptureManager;
75 import android.view.inputmethod.InputMethodSystemProperty;
76 
77 import com.android.i18n.timezone.ZoneInfoDb;
78 import com.android.internal.R;
79 import com.android.internal.logging.MetricsLogger;
80 import com.android.internal.notification.SystemNotificationChannels;
81 import com.android.internal.os.BinderInternal;
82 import com.android.internal.util.ConcurrentUtils;
83 import com.android.internal.util.EmergencyAffordanceManager;
84 import com.android.internal.widget.ILockSettings;
85 import com.android.server.am.ActivityManagerService;
86 import com.android.server.appbinding.AppBindingService;
87 import com.android.server.attention.AttentionManagerService;
88 import com.android.server.audio.AudioService;
89 import com.android.server.biometrics.BiometricService;
90 import com.android.server.biometrics.face.FaceService;
91 import com.android.server.biometrics.fingerprint.FingerprintService;
92 import com.android.server.biometrics.iris.IrisService;
93 import com.android.server.broadcastradio.BroadcastRadioService;
94 import com.android.server.camera.CameraServiceProxy;
95 import com.android.server.clipboard.ClipboardService;
96 import com.android.server.compat.PlatformCompat;
97 import com.android.server.compat.PlatformCompatNative;
98 import com.android.server.connectivity.IpConnectivityMetrics;
99 import com.android.server.contentcapture.ContentCaptureManagerInternal;
100 import com.android.server.coverage.CoverageService;
101 import com.android.server.devicepolicy.DevicePolicyManagerService;
102 import com.android.server.display.DisplayManagerService;
103 import com.android.server.display.color.ColorDisplayService;
104 import com.android.server.dreams.DreamManagerService;
105 import com.android.server.emergency.EmergencyAffordanceService;
106 import com.android.server.gpu.GpuService;
107 import com.android.server.hdmi.HdmiControlService;
108 import com.android.server.incident.IncidentCompanionService;
109 import com.android.server.input.InputManagerService;
110 import com.android.server.inputmethod.InputMethodManagerService;
111 import com.android.server.inputmethod.MultiClientInputMethodManagerService;
112 import com.android.server.job.JobSchedulerService;
113 import com.android.server.lights.LightsService;
114 import com.android.server.media.MediaResourceMonitorService;
115 import com.android.server.media.MediaRouterService;
116 import com.android.server.media.MediaSessionService;
117 import com.android.server.media.projection.MediaProjectionManagerService;
118 import com.android.server.net.NetworkPolicyManagerService;
119 import com.android.server.net.NetworkStatsService;
120 import com.android.server.net.watchlist.NetworkWatchlistService;
121 import com.android.server.notification.NotificationManagerService;
122 import com.android.server.oemlock.OemLockService;
123 import com.android.server.om.OverlayManagerService;
124 import com.android.server.os.BugreportManagerService;
125 import com.android.server.os.DeviceIdentifiersPolicyService;
126 import com.android.server.os.SchedulingPolicyService;
127 import com.android.server.pm.BackgroundDexOptService;
128 import com.android.server.pm.CrossProfileAppsService;
129 import com.android.server.pm.DynamicCodeLoggingService;
130 import com.android.server.pm.Installer;
131 import com.android.server.pm.LauncherAppsService;
132 import com.android.server.pm.OtaDexoptService;
133 import com.android.server.pm.PackageManagerService;
134 import com.android.server.pm.ShortcutService;
135 import com.android.server.pm.UserManagerService;
136 import com.android.server.policy.PermissionPolicyService;
137 import com.android.server.policy.PhoneWindowManager;
138 import com.android.server.policy.role.LegacyRoleResolutionPolicy;
139 import com.android.server.power.PowerManagerService;
140 import com.android.server.power.ShutdownThread;
141 import com.android.server.power.ThermalManagerService;
142 import com.android.server.recoverysystem.RecoverySystemService;
143 import com.android.server.restrictions.RestrictionsManagerService;
144 import com.android.server.role.RoleManagerService;
145 import com.android.server.rollback.RollbackManagerService;
146 import com.android.server.security.KeyAttestationApplicationIdProviderService;
147 import com.android.server.security.KeyChainSystemService;
148 import com.android.server.signedconfig.SignedConfigService;
149 import com.android.server.soundtrigger.SoundTriggerService;
150 import com.android.server.stats.StatsCompanionService;
151 import com.android.server.statusbar.StatusBarManagerService;
152 import com.android.server.storage.DeviceStorageMonitorService;
153 import com.android.server.telecom.TelecomLoaderService;
154 import com.android.server.testharness.TestHarnessModeService;
155 import com.android.server.textclassifier.TextClassificationManagerService;
156 import com.android.server.textservices.TextServicesManagerService;
157 import com.android.server.trust.TrustManagerService;
158 import com.android.server.tv.TvInputManagerService;
159 import com.android.server.tv.TvRemoteService;
160 import com.android.server.twilight.TwilightService;
161 import com.android.server.uri.UriGrantsManagerService;
162 import com.android.server.usage.UsageStatsService;
163 import com.android.server.vr.VrManagerService;
164 import com.android.server.webkit.WebViewUpdateService;
165 import com.android.server.wm.ActivityTaskManagerService;
166 import com.android.server.wm.WindowManagerGlobalLock;
167 import com.android.server.wm.WindowManagerService;
168 
169 import dalvik.system.VMRuntime;
170 
171 import java.io.File;
172 import java.io.IOException;
173 import java.util.Locale;
174 import java.util.Timer;
175 import java.util.concurrent.CountDownLatch;
176 import java.util.concurrent.Future;
177 
178 public final class SystemServer {
179 
180     private static final String TAG = "SystemServer";
181 
182     // Tag for timing measurement of main thread.
183     private static final String SYSTEM_SERVER_TIMING_TAG = "SystemServerTiming";
184     // Tag for timing measurement of non-main asynchronous operations.
185     private static final String SYSTEM_SERVER_TIMING_ASYNC_TAG = SYSTEM_SERVER_TIMING_TAG + "Async";
186 
187     private static final TimingsTraceLog BOOT_TIMINGS_TRACE_LOG
188             = new TimingsTraceLog(SYSTEM_SERVER_TIMING_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
189 
190     private static final String ENCRYPTING_STATE = "trigger_restart_min_framework";
191     private static final String ENCRYPTED_STATE = "1";
192 
193     private static final long SLOW_DISPATCH_THRESHOLD_MS = 100;
194     private static final long SLOW_DELIVERY_THRESHOLD_MS = 200;
195 
196     /*
197      * Implementation class names. TODO: Move them to a codegen class or load
198      * them from the build system somehow.
199      */
200     private static final String BACKUP_MANAGER_SERVICE_CLASS =
201             "com.android.server.backup.BackupManagerService$Lifecycle";
202     private static final String APPWIDGET_SERVICE_CLASS =
203             "com.android.server.appwidget.AppWidgetService";
204     private static final String VOICE_RECOGNITION_MANAGER_SERVICE_CLASS =
205             "com.android.server.voiceinteraction.VoiceInteractionManagerService";
206     private static final String PRINT_MANAGER_SERVICE_CLASS =
207             "com.android.server.print.PrintManagerService";
208     private static final String COMPANION_DEVICE_MANAGER_SERVICE_CLASS =
209             "com.android.server.companion.CompanionDeviceManagerService";
210     private static final String USB_SERVICE_CLASS =
211             "com.android.server.usb.UsbService$Lifecycle";
212     private static final String MIDI_SERVICE_CLASS =
213             "com.android.server.midi.MidiService$Lifecycle";
214     private static final String WIFI_SERVICE_CLASS =
215             "com.android.server.wifi.WifiService";
216     private static final String WIFI_AWARE_SERVICE_CLASS =
217             "com.android.server.wifi.aware.WifiAwareService";
218     private static final String WIFI_P2P_SERVICE_CLASS =
219             "com.android.server.wifi.p2p.WifiP2pService";
220     private static final String LOWPAN_SERVICE_CLASS =
221             "com.android.server.lowpan.LowpanService";
222     private static final String ETHERNET_SERVICE_CLASS =
223             "com.android.server.ethernet.EthernetService";
224     private static final String JOB_SCHEDULER_SERVICE_CLASS =
225             "com.android.server.job.JobSchedulerService";
226     private static final String LOCK_SETTINGS_SERVICE_CLASS =
227             "com.android.server.locksettings.LockSettingsService$Lifecycle";
228     private static final String STORAGE_MANAGER_SERVICE_CLASS =
229             "com.android.server.StorageManagerService$Lifecycle";
230     private static final String STORAGE_STATS_SERVICE_CLASS =
231             "com.android.server.usage.StorageStatsService$Lifecycle";
232     private static final String SEARCH_MANAGER_SERVICE_CLASS =
233             "com.android.server.search.SearchManagerService$Lifecycle";
234     private static final String THERMAL_OBSERVER_CLASS =
235             "com.google.android.clockwork.ThermalObserver";
236     private static final String WEAR_CONNECTIVITY_SERVICE_CLASS =
237             "com.android.clockwork.connectivity.WearConnectivityService";
238     private static final String WEAR_POWER_SERVICE_CLASS =
239             "com.android.clockwork.power.WearPowerService";
240     private static final String WEAR_SIDEKICK_SERVICE_CLASS =
241             "com.google.android.clockwork.sidekick.SidekickService";
242     private static final String WEAR_DISPLAY_SERVICE_CLASS =
243             "com.google.android.clockwork.display.WearDisplayService";
244     private static final String WEAR_LEFTY_SERVICE_CLASS =
245             "com.google.android.clockwork.lefty.WearLeftyService";
246     private static final String WEAR_TIME_SERVICE_CLASS =
247             "com.google.android.clockwork.time.WearTimeService";
248     private static final String WEAR_GLOBAL_ACTIONS_SERVICE_CLASS =
249             "com.android.clockwork.globalactions.GlobalActionsService";
250     private static final String ACCOUNT_SERVICE_CLASS =
251             "com.android.server.accounts.AccountManagerService$Lifecycle";
252     private static final String CONTENT_SERVICE_CLASS =
253             "com.android.server.content.ContentService$Lifecycle";
254     private static final String WALLPAPER_SERVICE_CLASS =
255             "com.android.server.wallpaper.WallpaperManagerService$Lifecycle";
256     private static final String AUTO_FILL_MANAGER_SERVICE_CLASS =
257             "com.android.server.autofill.AutofillManagerService";
258     private static final String CONTENT_CAPTURE_MANAGER_SERVICE_CLASS =
259             "com.android.server.contentcapture.ContentCaptureManagerService";
260     private static final String SYSTEM_CAPTIONS_MANAGER_SERVICE_CLASS =
261             "com.android.server.systemcaptions.SystemCaptionsManagerService";
262     private static final String TIME_ZONE_RULES_MANAGER_SERVICE_CLASS =
263             "com.android.server.timezone.RulesManagerService$Lifecycle";
264     private static final String IOT_SERVICE_CLASS =
265             "com.android.things.server.IoTSystemService";
266     private static final String SLICE_MANAGER_SERVICE_CLASS =
267             "com.android.server.slice.SliceManagerService$Lifecycle";
268     private static final String CAR_SERVICE_HELPER_SERVICE_CLASS =
269             "com.android.internal.car.CarServiceHelperService";
270     private static final String TIME_DETECTOR_SERVICE_CLASS =
271             "com.android.server.timedetector.TimeDetectorService$Lifecycle";
272     private static final String TIME_ZONE_DETECTOR_SERVICE_CLASS =
273             "com.android.server.timezonedetector.TimeZoneDetectorService$Lifecycle";
274     private static final String ACCESSIBILITY_MANAGER_SERVICE_CLASS =
275             "com.android.server.accessibility.AccessibilityManagerService$Lifecycle";
276     private static final String ADB_SERVICE_CLASS =
277             "com.android.server.adb.AdbService$Lifecycle";
278     private static final String APP_PREDICTION_MANAGER_SERVICE_CLASS =
279             "com.android.server.appprediction.AppPredictionManagerService";
280     private static final String CONTENT_SUGGESTIONS_SERVICE_CLASS =
281             "com.android.server.contentsuggestions.ContentSuggestionsManagerService";
282 
283     private static final String TETHERING_CONNECTOR_CLASS = "android.net.ITetheringConnector";
284 
285     private static final String PERSISTENT_DATA_BLOCK_PROP = "ro.frp.pst";
286 
287     private static final String UNCRYPT_PACKAGE_FILE = "/cache/recovery/uncrypt_file";
288     private static final String BLOCK_MAP_FILE = "/cache/recovery/block.map";
289 
290     private static final String GSI_RUNNING_PROP = "ro.gsid.image_running";
291 
292     // maximum number of binder threads used for system_server
293     // will be higher than the system default
294     private static final int sMaxBinderThreads = 31;
295 
296     /**
297      * Default theme used by the system context. This is used to style system-provided dialogs, such
298      * as the Power Off dialog, and other visual content.
299      */
300     private static final int DEFAULT_SYSTEM_THEME =
301             com.android.internal.R.style.Theme_DeviceDefault_System;
302 
303     private final int mFactoryTestMode;
304     private Timer mProfilerSnapshotTimer;
305 
306     private Context mSystemContext;
307     private SystemServiceManager mSystemServiceManager;
308 
309     // TODO: remove all of these references by improving dependency resolution and boot phases
310     private PowerManagerService mPowerManagerService;
311     private ActivityManagerService mActivityManagerService;
312     private WindowManagerGlobalLock mWindowManagerGlobalLock;
313     private WebViewUpdateService mWebViewUpdateService;
314     private DisplayManagerService mDisplayManagerService;
315     private PackageManagerService mPackageManagerService;
316     private PackageManager mPackageManager;
317     private ContentResolver mContentResolver;
318     private EntropyMixer mEntropyMixer;
319 
320     private boolean mOnlyCore;
321     private boolean mFirstBoot;
322     private final int mStartCount;
323     private final boolean mRuntimeRestart;
324     private final long mRuntimeStartElapsedTime;
325     private final long mRuntimeStartUptime;
326 
327     private static final String START_SENSOR_SERVICE = "StartSensorService";
328     private static final String START_HIDL_SERVICES = "StartHidlServices";
329 
330     private static final String SYSPROP_START_COUNT = "sys.system_server.start_count";
331     private static final String SYSPROP_START_ELAPSED = "sys.system_server.start_elapsed";
332     private static final String SYSPROP_START_UPTIME = "sys.system_server.start_uptime";
333 
334     private Future<?> mSensorServiceStart;
335     private Future<?> mZygotePreload;
336 
337     /**
338      * Start the sensor service. This is a blocking call and can take time.
339      */
startSensorService()340     private static native void startSensorService();
341 
342     /**
343      * Start all HIDL services that are run inside the system server. This may take some time.
344      */
startHidlServices()345     private static native void startHidlServices();
346 
347     /**
348      * Mark this process' heap as profileable. Only for debug builds.
349      */
initZygoteChildHeapProfiling()350     private static native void initZygoteChildHeapProfiling();
351 
352 
353     /**
354      * Spawn a thread that monitors for fd leaks.
355      */
spawnFdLeakCheckThread()356     private static native void spawnFdLeakCheckThread();
357 
358     /**
359      * The main entry point from zygote.
360      */
main(String[] args)361     public static void main(String[] args) {
362         new SystemServer().run();
363     }
364 
SystemServer()365     public SystemServer() {
366         // Check for factory test mode.
367         mFactoryTestMode = FactoryTest.getMode();
368 
369         // Record process start information.
370         // Note SYSPROP_START_COUNT will increment by *2* on a FDE device when it fully boots;
371         // one for the password screen, second for the actual boot.
372         mStartCount = SystemProperties.getInt(SYSPROP_START_COUNT, 0) + 1;
373         mRuntimeStartElapsedTime = SystemClock.elapsedRealtime();
374         mRuntimeStartUptime = SystemClock.uptimeMillis();
375 
376         // Remember if it's runtime restart(when sys.boot_completed is already set) or reboot
377         // We don't use "mStartCount > 1" here because it'll be wrong on a FDE device.
378         // TODO: mRuntimeRestart will *not* be set to true if the proccess crashes before
379         // sys.boot_completed is set. Fix it.
380         mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));
381     }
382 
run()383     private void run() {
384         try {
385             traceBeginAndSlog("InitBeforeStartServices");
386 
387             // Record the process start information in sys props.
388             SystemProperties.set(SYSPROP_START_COUNT, String.valueOf(mStartCount));
389             SystemProperties.set(SYSPROP_START_ELAPSED, String.valueOf(mRuntimeStartElapsedTime));
390             SystemProperties.set(SYSPROP_START_UPTIME, String.valueOf(mRuntimeStartUptime));
391 
392             EventLog.writeEvent(EventLogTags.SYSTEM_SERVER_START,
393                     mStartCount, mRuntimeStartUptime, mRuntimeStartElapsedTime);
394 
395             //
396             // Default the timezone property to GMT if not set.
397             //
398             String timezoneProperty = SystemProperties.get("persist.sys.timezone");
399             if (!isValidTimeZoneId(timezoneProperty)) {
400                 Slog.w(TAG, "persist.sys.timezone is not valid (" + timezoneProperty
401                         + "); setting to GMT.");
402                 SystemProperties.set("persist.sys.timezone", "GMT");
403             }
404 
405             // If the system has "persist.sys.language" and friends set, replace them with
406             // "persist.sys.locale". Note that the default locale at this point is calculated
407             // using the "-Duser.locale" command line flag. That flag is usually populated by
408             // AndroidRuntime using the same set of system properties, but only the system_server
409             // and system apps are allowed to set them.
410             //
411             // NOTE: Most changes made here will need an equivalent change to
412             // core/jni/AndroidRuntime.cpp
413             if (!SystemProperties.get("persist.sys.language").isEmpty()) {
414                 final String languageTag = Locale.getDefault().toLanguageTag();
415 
416                 SystemProperties.set("persist.sys.locale", languageTag);
417                 SystemProperties.set("persist.sys.language", "");
418                 SystemProperties.set("persist.sys.country", "");
419                 SystemProperties.set("persist.sys.localevar", "");
420             }
421 
422             // The system server should never make non-oneway calls
423             Binder.setWarnOnBlocking(true);
424             // The system server should always load safe labels
425             PackageItemInfo.forceSafeLabels();
426 
427             // Default to FULL within the system server.
428             SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;
429 
430             // Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
431             SQLiteCompatibilityWalFlags.init(null);
432 
433             // Here we go!
434             Slog.i(TAG, "Entered the Android system server!");
435             int uptimeMillis = (int) SystemClock.elapsedRealtime();
436             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
437             if (!mRuntimeRestart) {
438                 MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
439             }
440 
441             // In case the runtime switched since last boot (such as when
442             // the old runtime was removed in an OTA), set the system
443             // property so that it is in sync. We can | xq oqi't do this in
444             // libnativehelper's JniInvocation::Init code where we already
445             // had to fallback to a different runtime because it is
446             // running as root and we need to be the system user to set
447             // the property. http://b/11463182
448             SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
449 
450             // Mmmmmm... more memory!
451             VMRuntime.getRuntime().clearGrowthLimit();
452 
453             // Some devices rely on runtime fingerprint generation, so make sure
454             // we've defined it before booting further.
455             Build.ensureFingerprintProperty();
456 
457             // Within the system server, it is an error to access Environment paths without
458             // explicitly specifying a user.
459             Environment.setUserRequired(true);
460 
461             // Within the system server, any incoming Bundles should be defused
462             // to avoid throwing BadParcelableException.
463             BaseBundle.setShouldDefuse(true);
464 
465             // Within the system server, when parceling exceptions, include the stack trace
466             Parcel.setStackTraceParceling(true);
467 
468             // Ensure binder calls into the system always run at foreground priority.
469             BinderInternal.disableBackgroundScheduling(true);
470 
471             // Increase the number of binder threads in system_server
472             BinderInternal.setMaxThreads(sMaxBinderThreads);
473 
474             // Prepare the main looper thread (this thread).
475             android.os.Process.setThreadPriority(
476                     android.os.Process.THREAD_PRIORITY_FOREGROUND);
477             android.os.Process.setCanSelfBackground(false);
478             Looper.prepareMainLooper();
479             Looper.getMainLooper().setSlowLogThresholdMs(
480                     SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
481 
482             // Initialize native services.
483             System.loadLibrary("android_servers");
484 
485             // Debug builds - allow heap profiling.
486             if (Build.IS_DEBUGGABLE) {
487                 initZygoteChildHeapProfiling();
488             }
489 
490             // Debug builds - spawn a thread to monitor for fd leaks.
491             if (Build.IS_DEBUGGABLE) {
492                 spawnFdLeakCheckThread();
493             }
494 
495             // Check whether we failed to shut down last time we tried.
496             // This call may not return.
497             performPendingShutdown();
498 
499             // Initialize the system context.
500             createSystemContext();
501 
502             // Create the system service manager.
503             mSystemServiceManager = new SystemServiceManager(mSystemContext);
504             mSystemServiceManager.setStartInfo(mRuntimeRestart,
505                     mRuntimeStartElapsedTime, mRuntimeStartUptime);
506             LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
507             // Prepare the thread pool for init tasks that can be parallelized
508             SystemServerInitThreadPool.get();
509             // Attach JVMTI agent if this is a debuggable build and the system property is set.
510             if (Build.IS_DEBUGGABLE) {
511                 // Property is of the form "library_path=parameters".
512                 String jvmtiAgent = SystemProperties.get("persist.sys.dalvik.jvmtiagent");
513                 if (!jvmtiAgent.isEmpty()) {
514                     int equalIndex = jvmtiAgent.indexOf('=');
515                     String libraryPath = jvmtiAgent.substring(0, equalIndex);
516                     String parameterList =
517                             jvmtiAgent.substring(equalIndex + 1, jvmtiAgent.length());
518                     // Attach the agent.
519                     try {
520                         Debug.attachJvmtiAgent(libraryPath, parameterList, null);
521                     } catch (Exception e) {
522                         Slog.e("System", "*************************************************");
523                         Slog.e("System", "********** Failed to load jvmti plugin: " + jvmtiAgent);
524                     }
525                 }
526             }
527         } finally {
528             traceEnd();  // InitBeforeStartServices
529         }
530 
531         // Start services.
532         try {
533             traceBeginAndSlog("StartServices");
534             startBootstrapServices();
535             startCoreServices();
536             startOtherServices();
537             SystemServerInitThreadPool.shutdown();
538         } catch (Throwable ex) {
539             Slog.e("System", "******************************************");
540             Slog.e("System", "************ Failure starting system services", ex);
541             throw ex;
542         } finally {
543             traceEnd();
544         }
545 
546         StrictMode.initVmDefaults(null);
547 
548         if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
549             int uptimeMillis = (int) SystemClock.elapsedRealtime();
550             MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
551             final int MAX_UPTIME_MILLIS = 60 * 1000;
552             if (uptimeMillis > MAX_UPTIME_MILLIS) {
553                 Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
554                         "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
555             }
556         }
557 
558         // Loop forever.
559         Looper.loop();
560         throw new RuntimeException("Main thread loop unexpectedly exited");
561     }
562 
isValidTimeZoneId(String timezoneProperty)563     private static boolean isValidTimeZoneId(String timezoneProperty) {
564         return timezoneProperty != null
565                 && !timezoneProperty.isEmpty()
566                 && ZoneInfoDb.getInstance().hasTimeZone(timezoneProperty);
567     }
568 
isFirstBootOrUpgrade()569     private boolean isFirstBootOrUpgrade() {
570         return mPackageManagerService.isFirstBoot() || mPackageManagerService.isDeviceUpgrading();
571     }
572 
reportWtf(String msg, Throwable e)573     private void reportWtf(String msg, Throwable e) {
574         Slog.w(TAG, "***********************************************");
575         Slog.wtf(TAG, "BOOT FAILURE " + msg, e);
576     }
577 
performPendingShutdown()578     private void performPendingShutdown() {
579         final String shutdownAction = SystemProperties.get(
580                 ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
581         if (shutdownAction != null && shutdownAction.length() > 0) {
582             boolean reboot = (shutdownAction.charAt(0) == '1');
583 
584             final String reason;
585             if (shutdownAction.length() > 1) {
586                 reason = shutdownAction.substring(1, shutdownAction.length());
587             } else {
588                 reason = null;
589             }
590 
591             // If it's a pending reboot into recovery to apply an update,
592             // always make sure uncrypt gets executed properly when needed.
593             // If '/cache/recovery/block.map' hasn't been created, stop the
594             // reboot which will fail for sure, and get a chance to capture a
595             // bugreport when that's still feasible. (Bug: 26444951)
596             if (reason != null && reason.startsWith(PowerManager.REBOOT_RECOVERY_UPDATE)) {
597                 File packageFile = new File(UNCRYPT_PACKAGE_FILE);
598                 if (packageFile.exists()) {
599                     String filename = null;
600                     try {
601                         filename = FileUtils.readTextFile(packageFile, 0, null);
602                     } catch (IOException e) {
603                         Slog.e(TAG, "Error reading uncrypt package file", e);
604                     }
605 
606                     if (filename != null && filename.startsWith("/data")) {
607                         if (!new File(BLOCK_MAP_FILE).exists()) {
608                             Slog.e(TAG, "Can't find block map file, uncrypt failed or " +
609                                     "unexpected runtime restart?");
610                             return;
611                         }
612                     }
613                 }
614             }
615             Runnable runnable = new Runnable() {
616                 @Override
617                 public void run() {
618                     synchronized (this) {
619                         ShutdownThread.rebootOrShutdown(null, reboot, reason);
620                     }
621                 }
622             };
623 
624             // ShutdownThread must run on a looper capable of displaying the UI.
625             Message msg = Message.obtain(UiThread.getHandler(), runnable);
626             msg.setAsynchronous(true);
627             UiThread.getHandler().sendMessage(msg);
628 
629         }
630     }
631 
createSystemContext()632     private void createSystemContext() {
633         ActivityThread activityThread = ActivityThread.systemMain();
634         mSystemContext = activityThread.getSystemContext();
635         mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
636 
637         final Context systemUiContext = activityThread.getSystemUiContext();
638         systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
639     }
640 
641     /**
642      * Starts the small tangle of critical services that are needed to get the system off the
643      * ground.  These services have complex mutual dependencies which is why we initialize them all
644      * in one place here.  Unless your service is also entwined in these dependencies, it should be
645      * initialized in one of the other functions.
646      */
startBootstrapServices()647     private void startBootstrapServices() {
648         // Start the watchdog as early as possible so we can crash the system server
649         // if we deadlock during early boot
650         traceBeginAndSlog("StartWatchdog");
651         final Watchdog watchdog = Watchdog.getInstance();
652         watchdog.start();
653         traceEnd();
654 
655         Slog.i(TAG, "Reading configuration...");
656         final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
657         traceBeginAndSlog(TAG_SYSTEM_CONFIG);
658         SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
659         traceEnd();
660 
661         // Platform compat service is used by ActivityManagerService, PackageManagerService, and
662         // possibly others in the future. b/135010838.
663         traceBeginAndSlog("PlatformCompat");
664         PlatformCompat platformCompat = new PlatformCompat(mSystemContext);
665         ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE, platformCompat);
666         ServiceManager.addService(Context.PLATFORM_COMPAT_NATIVE_SERVICE,
667                 new PlatformCompatNative(platformCompat));
668         AppCompatCallbacks.install(new long[0]);
669         traceEnd();
670 
671         // Wait for installd to finish starting up so that it has a chance to
672         // create critical directories such as /data/user with the appropriate
673         // permissions.  We need this to complete before we initialize other services.
674         traceBeginAndSlog("StartInstaller");
675         Installer installer = mSystemServiceManager.startService(Installer.class);
676         traceEnd();
677 
678         // In some cases after launching an app we need to access device identifiers,
679         // therefore register the device identifier policy before the activity manager.
680         traceBeginAndSlog("DeviceIdentifiersPolicyService");
681         mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
682         traceEnd();
683 
684         // Uri Grants Manager.
685         traceBeginAndSlog("UriGrantsManagerService");
686         mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);
687         traceEnd();
688 
689         // Activity manager runs the show.
690         traceBeginAndSlog("StartActivityManager");
691         // TODO: Might need to move after migration to WM.
692         ActivityTaskManagerService atm = mSystemServiceManager.startService(
693                 ActivityTaskManagerService.Lifecycle.class).getService();
694         mActivityManagerService = ActivityManagerService.Lifecycle.startService(
695                 mSystemServiceManager, atm);
696         mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
697         mActivityManagerService.setInstaller(installer);
698         mWindowManagerGlobalLock = atm.getGlobalLock();
699         traceEnd();
700 
701         // Power manager needs to be started early because other services need it.
702         // Native daemons may be watching for it to be registered so it must be ready
703         // to handle incoming binder calls immediately (including being able to verify
704         // the permissions for those calls).
705         traceBeginAndSlog("StartPowerManager");
706         mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
707         traceEnd();
708 
709         traceBeginAndSlog("StartThermalManager");
710         mSystemServiceManager.startService(ThermalManagerService.class);
711         traceEnd();
712 
713         // Now that the power manager has been started, let the activity manager
714         // initialize power management features.
715         traceBeginAndSlog("InitPowerManagement");
716         mActivityManagerService.initPowerManagement();
717         traceEnd();
718 
719         // Bring up recovery system in case a rescue party needs a reboot
720         traceBeginAndSlog("StartRecoverySystemService");
721         mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class);
722         traceEnd();
723 
724         // Now that we have the bare essentials of the OS up and running, take
725         // note that we just booted, which might send out a rescue party if
726         // we're stuck in a runtime restart loop.
727         RescueParty.noteBoot(mSystemContext);
728 
729         // Manages LEDs and display backlight so we need it to bring up the display.
730         traceBeginAndSlog("StartLightsService");
731         mSystemServiceManager.startService(LightsService.class);
732         traceEnd();
733 
734         traceBeginAndSlog("StartSidekickService");
735         // Package manager isn't started yet; need to use SysProp not hardware feature
736         if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
737             mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
738         }
739         traceEnd();
740 
741         // Display manager is needed to provide display metrics before package manager
742         // starts up.
743         traceBeginAndSlog("StartDisplayManager");
744         mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
745         traceEnd();
746 
747         // We need the default display before we can initialize the package manager.
748         traceBeginAndSlog("WaitForDisplay");
749         mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
750         traceEnd();
751 
752         // Only run "core" apps if we're encrypting the device.
753         String cryptState = VoldProperties.decrypt().orElse("");
754         if (ENCRYPTING_STATE.equals(cryptState)) {
755             Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
756             mOnlyCore = true;
757         } else if (ENCRYPTED_STATE.equals(cryptState)) {
758             Slog.w(TAG, "Device encrypted - only parsing core apps");
759             mOnlyCore = true;
760         }
761 
762         // Start the package manager.
763         if (!mRuntimeRestart) {
764             MetricsLogger.histogram(null, "boot_package_manager_init_start",
765                     (int) SystemClock.elapsedRealtime());
766         }
767         traceBeginAndSlog("StartPackageManagerService");
768         try {
769             Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
770             mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
771                     mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
772         } finally {
773             Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
774         }
775         mFirstBoot = mPackageManagerService.isFirstBoot();
776         mPackageManager = mSystemContext.getPackageManager();
777         traceEnd();
778         if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
779             MetricsLogger.histogram(null, "boot_package_manager_init_ready",
780                     (int) SystemClock.elapsedRealtime());
781         }
782         // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
783         // A/B artifacts after boot, before anything else might touch/need them.
784         // Note: this isn't needed during decryption (we don't have /data anyways).
785         if (!mOnlyCore) {
786             boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
787                     false);
788             if (!disableOtaDexopt) {
789                 traceBeginAndSlog("StartOtaDexOptService");
790                 try {
791                     Watchdog.getInstance().pauseWatchingCurrentThread("moveab");
792                     OtaDexoptService.main(mSystemContext, mPackageManagerService);
793                 } catch (Throwable e) {
794                     reportWtf("starting OtaDexOptService", e);
795                 } finally {
796                     Watchdog.getInstance().resumeWatchingCurrentThread("moveab");
797                     traceEnd();
798                 }
799             }
800         }
801 
802         traceBeginAndSlog("StartUserManagerService");
803         mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
804         traceEnd();
805 
806         // Initialize attribute cache used to cache resources from packages.
807         traceBeginAndSlog("InitAttributerCache");
808         AttributeCache.init(mSystemContext);
809         traceEnd();
810 
811         // Set up the Application instance for the system process and get started.
812         traceBeginAndSlog("SetSystemProcess");
813         mActivityManagerService.setSystemProcess();
814         traceEnd();
815 
816         // Complete the watchdog setup with an ActivityManager instance and listen for reboots
817         // Do this only after the ActivityManagerService is properly started as a system process
818         traceBeginAndSlog("InitWatchdog");
819         watchdog.init(mSystemContext, mActivityManagerService);
820         traceEnd();
821 
822         // DisplayManagerService needs to setup android.display scheduling related policies
823         // since setSystemProcess() would have overridden policies due to setProcessGroup
824         mDisplayManagerService.setupSchedulerPolicies();
825 
826         // Manages Overlay packages
827         traceBeginAndSlog("StartOverlayManagerService");
828         mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));
829         traceEnd();
830 
831         traceBeginAndSlog("StartSensorPrivacyService");
832         mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext));
833         traceEnd();
834 
835         if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {
836             // DisplayManager needs the overlay immediately.
837             mActivityManagerService.updateSystemUiContext();
838             LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();
839         }
840 
841         // The sensor service needs access to package manager service, app ops
842         // service, and permissions service, therefore we start it after them.
843         // Start sensor service in a separate thread. Completion should be checked
844         // before using it.
845         mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
846             TimingsTraceLog traceLog = new TimingsTraceLog(
847                     SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
848             traceLog.traceBegin(START_SENSOR_SERVICE);
849             startSensorService();
850             traceLog.traceEnd();
851         }, START_SENSOR_SERVICE);
852     }
853 
854     /**
855      * Starts some essential services that are not tangled up in the bootstrap process.
856      */
startCoreServices()857     private void startCoreServices() {
858         traceBeginAndSlog("StartBatteryService");
859         // Tracks the battery level.  Requires LightService.
860         mSystemServiceManager.startService(BatteryService.class);
861         traceEnd();
862 
863         // Tracks application usage stats.
864         traceBeginAndSlog("StartUsageService");
865         mSystemServiceManager.startService(UsageStatsService.class);
866         mActivityManagerService.setUsageStatsManager(
867                 LocalServices.getService(UsageStatsManagerInternal.class));
868         traceEnd();
869 
870         // Tracks whether the updatable WebView is in a ready state and watches for update installs.
871         if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
872             traceBeginAndSlog("StartWebViewUpdateService");
873             mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
874             traceEnd();
875         }
876 
877         // Tracks and caches the device state.
878         traceBeginAndSlog("StartCachedDeviceStateService");
879         mSystemServiceManager.startService(CachedDeviceStateService.class);
880         traceEnd();
881 
882         // Tracks cpu time spent in binder calls
883         traceBeginAndSlog("StartBinderCallsStatsService");
884         mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);
885         traceEnd();
886 
887         // Tracks time spent in handling messages in handlers.
888         traceBeginAndSlog("StartLooperStatsService");
889         mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);
890         traceEnd();
891 
892         // Manages apk rollbacks.
893         traceBeginAndSlog("StartRollbackManagerService");
894         mSystemServiceManager.startService(RollbackManagerService.class);
895         traceEnd();
896 
897         // Service to capture bugreports.
898         traceBeginAndSlog("StartBugreportManagerService");
899         mSystemServiceManager.startService(BugreportManagerService.class);
900         traceEnd();
901 
902         // Serivce for GPU and GPU driver.
903         traceBeginAndSlog("GpuService");
904         mSystemServiceManager.startService(GpuService.class);
905         traceEnd();
906     }
907 
908     /**
909      * Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized.
910      */
startOtherServices()911     private void startOtherServices() {
912         final Context context = mSystemContext;
913         VibratorService vibrator = null;
914         DynamicSystemService dynamicSystem = null;
915         IStorageManager storageManager = null;
916         NetworkManagementService networkManagement = null;
917         IpSecService ipSecService = null;
918         NetworkStatsService networkStats = null;
919         NetworkPolicyManagerService networkPolicy = null;
920         ConnectivityService connectivity = null;
921         NsdService serviceDiscovery = null;
922         WindowManagerService wm = null;
923         SerialService serial = null;
924         NetworkTimeUpdateService networkTimeUpdater = null;
925         InputManagerService inputManager = null;
926         TelephonyRegistry telephonyRegistry = null;
927         ConsumerIrService consumerIr = null;
928         MmsServiceBroker mmsService = null;
929         HardwarePropertiesManagerService hardwarePropertiesService = null;
930 
931         boolean disableSystemTextClassifier = SystemProperties.getBoolean(
932                 "config.disable_systemtextclassifier", false);
933 
934         boolean disableNetworkTime = SystemProperties.getBoolean("config.disable_networktime",
935                 false);
936         boolean disableCameraService = SystemProperties.getBoolean("config.disable_cameraservice",
937                 false);
938         boolean enableLeftyService = SystemProperties.getBoolean("config.enable_lefty", false);
939 
940         boolean isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1");
941 
942         boolean isWatch = context.getPackageManager().hasSystemFeature(
943                 PackageManager.FEATURE_WATCH);
944 
945         boolean isArc = context.getPackageManager().hasSystemFeature(
946                 "org.chromium.arc");
947 
948         boolean enableVrService = context.getPackageManager().hasSystemFeature(
949                 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE);
950 
951         // For debugging RescueParty
952         if (Build.IS_DEBUGGABLE && SystemProperties.getBoolean("debug.crash_system", false)) {
953             throw new RuntimeException();
954         }
955 
956         try {
957             final String SECONDARY_ZYGOTE_PRELOAD = "SecondaryZygotePreload";
958             // We start the preload ~1s before the webview factory preparation, to
959             // ensure that it completes before the 32 bit relro process is forked
960             // from the zygote. In the event that it takes too long, the webview
961             // RELRO process will block, but it will do so without holding any locks.
962             mZygotePreload = SystemServerInitThreadPool.get().submit(() -> {
963                 try {
964                     Slog.i(TAG, SECONDARY_ZYGOTE_PRELOAD);
965                     TimingsTraceLog traceLog = new TimingsTraceLog(
966                             SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
967                     traceLog.traceBegin(SECONDARY_ZYGOTE_PRELOAD);
968                     if (!Process.ZYGOTE_PROCESS.preloadDefault(Build.SUPPORTED_32_BIT_ABIS[0])) {
969                         Slog.e(TAG, "Unable to preload default resources");
970                     }
971                     traceLog.traceEnd();
972                 } catch (Exception ex) {
973                     Slog.e(TAG, "Exception preloading default resources", ex);
974                 }
975             }, SECONDARY_ZYGOTE_PRELOAD);
976 
977             traceBeginAndSlog("StartKeyAttestationApplicationIdProviderService");
978             ServiceManager.addService("sec_key_att_app_id_provider",
979                     new KeyAttestationApplicationIdProviderService(context));
980             traceEnd();
981 
982             traceBeginAndSlog("StartKeyChainSystemService");
983             mSystemServiceManager.startService(KeyChainSystemService.class);
984             traceEnd();
985 
986             traceBeginAndSlog("StartSchedulingPolicyService");
987             ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
988             traceEnd();
989 
990             traceBeginAndSlog("StartTelecomLoaderService");
991             mSystemServiceManager.startService(TelecomLoaderService.class);
992             traceEnd();
993 
994             traceBeginAndSlog("StartTelephonyRegistry");
995             telephonyRegistry = new TelephonyRegistry(
996                     context, new TelephonyRegistry.ConfigurationProvider());
997             ServiceManager.addService("telephony.registry", telephonyRegistry);
998             traceEnd();
999 
1000             traceBeginAndSlog("StartEntropyMixer");
1001             mEntropyMixer = new EntropyMixer(context);
1002             traceEnd();
1003 
1004             mContentResolver = context.getContentResolver();
1005 
1006             // The AccountManager must come before the ContentService
1007             traceBeginAndSlog("StartAccountManagerService");
1008             mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
1009             traceEnd();
1010 
1011             traceBeginAndSlog("StartContentService");
1012             mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);
1013             traceEnd();
1014 
1015             traceBeginAndSlog("InstallSystemProviders");
1016             mActivityManagerService.installSystemProviders();
1017             // Now that SettingsProvider is ready, reactivate SQLiteCompatibilityWalFlags
1018             SQLiteCompatibilityWalFlags.reset();
1019             traceEnd();
1020 
1021             // Records errors and logs, for example wtf()
1022             // Currently this service indirectly depends on SettingsProvider so do this after
1023             // InstallSystemProviders.
1024             traceBeginAndSlog("StartDropBoxManager");
1025             mSystemServiceManager.startService(DropBoxManagerService.class);
1026             traceEnd();
1027 
1028             traceBeginAndSlog("StartVibratorService");
1029             vibrator = new VibratorService(context);
1030             ServiceManager.addService("vibrator", vibrator);
1031             traceEnd();
1032 
1033             traceBeginAndSlog("StartDynamicSystemService");
1034             dynamicSystem = new DynamicSystemService(context);
1035             ServiceManager.addService("dynamic_system", dynamicSystem);
1036             traceEnd();
1037 
1038             if (!isWatch) {
1039                 traceBeginAndSlog("StartConsumerIrService");
1040                 consumerIr = new ConsumerIrService(context);
1041                 ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);
1042                 traceEnd();
1043             }
1044 
1045             traceBeginAndSlog("StartAlarmManagerService");
1046             mSystemServiceManager.startService(new AlarmManagerService(context));
1047             traceEnd();
1048 
1049             traceBeginAndSlog("StartInputManagerService");
1050             inputManager = new InputManagerService(context);
1051             traceEnd();
1052 
1053             traceBeginAndSlog("StartWindowManagerService");
1054             // WMS needs sensor service ready
1055             ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
1056             mSensorServiceStart = null;
1057             wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
1058                     new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
1059             ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
1060                     DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
1061             ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
1062                     /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
1063             traceEnd();
1064 
1065             traceBeginAndSlog("SetWindowManagerService");
1066             mActivityManagerService.setWindowManager(wm);
1067             traceEnd();
1068 
1069             traceBeginAndSlog("WindowManagerServiceOnInitReady");
1070             wm.onInitReady();
1071             traceEnd();
1072 
1073             // Start receiving calls from HIDL services. Start in in a separate thread
1074             // because it need to connect to SensorManager. This have to start
1075             // after START_SENSOR_SERVICE is done.
1076             SystemServerInitThreadPool.get().submit(() -> {
1077                 TimingsTraceLog traceLog = new TimingsTraceLog(
1078                         SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
1079                 traceLog.traceBegin(START_HIDL_SERVICES);
1080                 startHidlServices();
1081                 traceLog.traceEnd();
1082             }, START_HIDL_SERVICES);
1083 
1084             if (!isWatch && enableVrService) {
1085                 traceBeginAndSlog("StartVrManagerService");
1086                 mSystemServiceManager.startService(VrManagerService.class);
1087                 traceEnd();
1088             }
1089 
1090             traceBeginAndSlog("StartInputManager");
1091             inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback());
1092             inputManager.start();
1093             traceEnd();
1094 
1095             // TODO: Use service dependencies instead.
1096             traceBeginAndSlog("DisplayManagerWindowManagerAndInputReady");
1097             mDisplayManagerService.windowManagerAndInputReady();
1098             traceEnd();
1099 
1100             if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
1101                 Slog.i(TAG, "No Bluetooth Service (factory test)");
1102             } else if (!context.getPackageManager().hasSystemFeature
1103                     (PackageManager.FEATURE_BLUETOOTH)) {
1104                 Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");
1105             } else {
1106                 traceBeginAndSlog("StartBluetoothService");
1107                 mSystemServiceManager.startService(BluetoothService.class);
1108                 traceEnd();
1109             }
1110 
1111             traceBeginAndSlog("IpConnectivityMetrics");
1112             mSystemServiceManager.startService(IpConnectivityMetrics.class);
1113             traceEnd();
1114 
1115             traceBeginAndSlog("NetworkWatchlistService");
1116             mSystemServiceManager.startService(NetworkWatchlistService.Lifecycle.class);
1117             traceEnd();
1118 
1119             traceBeginAndSlog("PinnerService");
1120             mSystemServiceManager.startService(PinnerService.class);
1121             traceEnd();
1122 
1123             traceBeginAndSlog("SignedConfigService");
1124             SignedConfigService.registerUpdateReceiver(mSystemContext);
1125             traceEnd();
1126 
1127         } catch (RuntimeException e) {
1128             Slog.e("System", "******************************************");
1129             Slog.e("System", "************ Failure starting core service", e);
1130         }
1131 
1132         // Before things start rolling, be sure we have decided whether
1133         // we are in safe mode.
1134         final boolean safeMode = wm.detectSafeMode();
1135         if (safeMode) {
1136             // If yes, immediately turn on the global setting for airplane mode.
1137             // Note that this does not send broadcasts at this stage because
1138             // subsystems are not yet up. We will send broadcasts later to ensure
1139             // all listeners have the chance to react with special handling.
1140             Settings.Global.putInt(context.getContentResolver(),
1141                     Settings.Global.AIRPLANE_MODE_ON, 1);
1142         }
1143 
1144         StatusBarManagerService statusBar = null;
1145         INotificationManager notification = null;
1146         LocationManagerService location = null;
1147         CountryDetectorService countryDetector = null;
1148         ILockSettings lockSettings = null;
1149         MediaRouterService mediaRouter = null;
1150 
1151         // Bring up services needed for UI.
1152         if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
1153             traceBeginAndSlog("StartInputMethodManagerLifecycle");
1154             if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) {
1155                 mSystemServiceManager.startService(
1156                         MultiClientInputMethodManagerService.Lifecycle.class);
1157             } else {
1158                 mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);
1159             }
1160             traceEnd();
1161 
1162             traceBeginAndSlog("StartAccessibilityManagerService");
1163             try {
1164                 mSystemServiceManager.startService(ACCESSIBILITY_MANAGER_SERVICE_CLASS);
1165             } catch (Throwable e) {
1166                 reportWtf("starting Accessibility Manager", e);
1167             }
1168             traceEnd();
1169         }
1170 
1171         traceBeginAndSlog("MakeDisplayReady");
1172         try {
1173             wm.displayReady();
1174         } catch (Throwable e) {
1175             reportWtf("making display ready", e);
1176         }
1177         traceEnd();
1178 
1179         if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
1180             if (!"0".equals(SystemProperties.get("system_init.startmountservice"))) {
1181                 traceBeginAndSlog("StartStorageManagerService");
1182                 try {
1183                     /*
1184                      * NotificationManagerService is dependant on StorageManagerService,
1185                      * (for media / usb notifications) so we must start StorageManagerService first.
1186                      */
1187                     mSystemServiceManager.startService(STORAGE_MANAGER_SERVICE_CLASS);
1188                     storageManager = IStorageManager.Stub.asInterface(
1189                             ServiceManager.getService("mount"));
1190                 } catch (Throwable e) {
1191                     reportWtf("starting StorageManagerService", e);
1192                 }
1193                 traceEnd();
1194 
1195                 traceBeginAndSlog("StartStorageStatsService");
1196                 try {
1197                     mSystemServiceManager.startService(STORAGE_STATS_SERVICE_CLASS);
1198                 } catch (Throwable e) {
1199                     reportWtf("starting StorageStatsService", e);
1200                 }
1201                 traceEnd();
1202             }
1203         }
1204 
1205         // We start this here so that we update our configuration to set watch or television
1206         // as appropriate.
1207         traceBeginAndSlog("StartUiModeManager");
1208         mSystemServiceManager.startService(UiModeManagerService.class);
1209         traceEnd();
1210 
1211         if (!mOnlyCore) {
1212             traceBeginAndSlog("UpdatePackagesIfNeeded");
1213             try {
1214                 Watchdog.getInstance().pauseWatchingCurrentThread("dexopt");
1215                 mPackageManagerService.updatePackagesIfNeeded();
1216             } catch (Throwable e) {
1217                 reportWtf("update packages", e);
1218             } finally {
1219                 Watchdog.getInstance().resumeWatchingCurrentThread("dexopt");
1220             }
1221             traceEnd();
1222         }
1223 
1224         traceBeginAndSlog("PerformFstrimIfNeeded");
1225         try {
1226             mPackageManagerService.performFstrimIfNeeded();
1227         } catch (Throwable e) {
1228             reportWtf("performing fstrim", e);
1229         }
1230         traceEnd();
1231 
1232         if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
1233             traceBeginAndSlog("StartLockSettingsService");
1234             try {
1235                 mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);
1236                 lockSettings = ILockSettings.Stub.asInterface(
1237                         ServiceManager.getService("lock_settings"));
1238             } catch (Throwable e) {
1239                 reportWtf("starting LockSettingsService service", e);
1240             }
1241             traceEnd();
1242 
1243             final boolean hasPdb = !SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("");
1244             final boolean hasGsi = SystemProperties.getInt(GSI_RUNNING_PROP, 0) > 0;
1245             if (hasPdb && !hasGsi) {
1246                 traceBeginAndSlog("StartPersistentDataBlock");
1247                 mSystemServiceManager.startService(PersistentDataBlockService.class);
1248                 traceEnd();
1249             }
1250 
1251             traceBeginAndSlog("StartTestHarnessMode");
1252             mSystemServiceManager.startService(TestHarnessModeService.class);
1253             traceEnd();
1254 
1255             if (hasPdb || OemLockService.isHalPresent()) {
1256                 // Implementation depends on pdb or the OemLock HAL
1257                 traceBeginAndSlog("StartOemLockService");
1258                 mSystemServiceManager.startService(OemLockService.class);
1259                 traceEnd();
1260             }
1261 
1262             traceBeginAndSlog("StartDeviceIdleController");
1263             mSystemServiceManager.startService(DeviceIdleController.class);
1264             traceEnd();
1265 
1266             // Always start the Device Policy Manager, so that the API is compatible with
1267             // API8.
1268             traceBeginAndSlog("StartDevicePolicyManager");
1269             mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class);
1270             traceEnd();
1271 
1272             if (!isWatch) {
1273                 traceBeginAndSlog("StartStatusBarManagerService");
1274                 try {
1275                     statusBar = new StatusBarManagerService(context, wm);
1276                     ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
1277                 } catch (Throwable e) {
1278                     reportWtf("starting StatusBarManagerService", e);
1279                 }
1280                 traceEnd();
1281             }
1282 
1283             startContentCaptureService(context);
1284             startAttentionService(context);
1285 
1286             startSystemCaptionsManagerService(context);
1287 
1288             // App prediction manager service
1289             if (deviceHasConfigString(context, R.string.config_defaultAppPredictionService)) {
1290                 traceBeginAndSlog("StartAppPredictionService");
1291                 mSystemServiceManager.startService(APP_PREDICTION_MANAGER_SERVICE_CLASS);
1292                 traceEnd();
1293             } else {
1294                 Slog.d(TAG, "AppPredictionService not defined by OEM");
1295             }
1296 
1297             // Content suggestions manager service
1298             if (deviceHasConfigString(context, R.string.config_defaultContentSuggestionsService)) {
1299                 traceBeginAndSlog("StartContentSuggestionsService");
1300                 mSystemServiceManager.startService(CONTENT_SUGGESTIONS_SERVICE_CLASS);
1301                 traceEnd();
1302             } else {
1303                 Slog.d(TAG, "ContentSuggestionsService not defined by OEM");
1304             }
1305 
1306             traceBeginAndSlog("InitConnectivityModuleConnector");
1307             try {
1308                 ConnectivityModuleConnector.getInstance().init(context);
1309             } catch (Throwable e) {
1310                 reportWtf("initializing ConnectivityModuleConnector", e);
1311             }
1312             traceEnd();
1313 
1314             traceBeginAndSlog("InitNetworkStackClient");
1315             try {
1316                 NetworkStackClient.getInstance().init();
1317             } catch (Throwable e) {
1318                 reportWtf("initializing NetworkStackClient", e);
1319             }
1320             traceEnd();
1321 
1322             traceBeginAndSlog("StartNetworkManagementService");
1323             try {
1324                 networkManagement = NetworkManagementService.create(context);
1325                 ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
1326             } catch (Throwable e) {
1327                 reportWtf("starting NetworkManagement Service", e);
1328             }
1329             traceEnd();
1330 
1331 
1332             traceBeginAndSlog("StartIpSecService");
1333             try {
1334                 ipSecService = IpSecService.create(context, networkManagement);
1335                 ServiceManager.addService(Context.IPSEC_SERVICE, ipSecService);
1336             } catch (Throwable e) {
1337                 reportWtf("starting IpSec Service", e);
1338             }
1339             traceEnd();
1340 
1341             traceBeginAndSlog("StartTextServicesManager");
1342             mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);
1343             traceEnd();
1344 
1345             if (!disableSystemTextClassifier) {
1346                 traceBeginAndSlog("StartTextClassificationManagerService");
1347                 mSystemServiceManager
1348                         .startService(TextClassificationManagerService.Lifecycle.class);
1349                 traceEnd();
1350             }
1351 
1352             traceBeginAndSlog("StartNetworkScoreService");
1353             mSystemServiceManager.startService(NetworkScoreService.Lifecycle.class);
1354             traceEnd();
1355 
1356             traceBeginAndSlog("StartNetworkStatsService");
1357             try {
1358                 networkStats = NetworkStatsService.create(context, networkManagement);
1359                 ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);
1360             } catch (Throwable e) {
1361                 reportWtf("starting NetworkStats Service", e);
1362             }
1363             traceEnd();
1364 
1365             traceBeginAndSlog("StartNetworkPolicyManagerService");
1366             try {
1367                 networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService,
1368                         networkManagement);
1369                 ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
1370             } catch (Throwable e) {
1371                 reportWtf("starting NetworkPolicy Service", e);
1372             }
1373             traceEnd();
1374 
1375             if (context.getPackageManager().hasSystemFeature(
1376                     PackageManager.FEATURE_WIFI)) {
1377                 // Wifi Service must be started first for wifi-related services.
1378                 traceBeginAndSlog("StartWifi");
1379                 mSystemServiceManager.startService(WIFI_SERVICE_CLASS);
1380                 traceEnd();
1381                 traceBeginAndSlog("StartWifiScanning");
1382                 mSystemServiceManager.startService(
1383                         "com.android.server.wifi.scanner.WifiScanningService");
1384                 traceEnd();
1385             }
1386 
1387             if (context.getPackageManager().hasSystemFeature(
1388                     PackageManager.FEATURE_WIFI_RTT)) {
1389                 traceBeginAndSlog("StartRttService");
1390                 mSystemServiceManager.startService(
1391                         "com.android.server.wifi.rtt.RttService");
1392                 traceEnd();
1393             }
1394 
1395             if (context.getPackageManager().hasSystemFeature(
1396                     PackageManager.FEATURE_WIFI_AWARE)) {
1397                 traceBeginAndSlog("StartWifiAware");
1398                 mSystemServiceManager.startService(WIFI_AWARE_SERVICE_CLASS);
1399                 traceEnd();
1400             }
1401 
1402             if (context.getPackageManager().hasSystemFeature(
1403                     PackageManager.FEATURE_WIFI_DIRECT)) {
1404                 traceBeginAndSlog("StartWifiP2P");
1405                 mSystemServiceManager.startService(WIFI_P2P_SERVICE_CLASS);
1406                 traceEnd();
1407             }
1408 
1409             if (context.getPackageManager().hasSystemFeature(
1410                     PackageManager.FEATURE_LOWPAN)) {
1411                 traceBeginAndSlog("StartLowpan");
1412                 mSystemServiceManager.startService(LOWPAN_SERVICE_CLASS);
1413                 traceEnd();
1414             }
1415 
1416             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) ||
1417                     mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) {
1418                 traceBeginAndSlog("StartEthernet");
1419                 mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS);
1420                 traceEnd();
1421             }
1422 
1423             traceBeginAndSlog("StartConnectivityService");
1424             try {
1425                 connectivity = new ConnectivityService(
1426                         context, networkManagement, networkStats, networkPolicy);
1427                 ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity,
1428                         /* allowIsolated= */ false,
1429                         DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL);
1430                 networkPolicy.bindConnectivityManager(connectivity);
1431             } catch (Throwable e) {
1432                 reportWtf("starting Connectivity Service", e);
1433             }
1434             traceEnd();
1435 
1436             traceBeginAndSlog("StartNsdService");
1437             try {
1438                 serviceDiscovery = NsdService.create(context);
1439                 ServiceManager.addService(
1440                         Context.NSD_SERVICE, serviceDiscovery);
1441             } catch (Throwable e) {
1442                 reportWtf("starting Service Discovery Service", e);
1443             }
1444             traceEnd();
1445 
1446             traceBeginAndSlog("StartSystemUpdateManagerService");
1447             try {
1448                 ServiceManager.addService(Context.SYSTEM_UPDATE_SERVICE,
1449                         new SystemUpdateManagerService(context));
1450             } catch (Throwable e) {
1451                 reportWtf("starting SystemUpdateManagerService", e);
1452             }
1453             traceEnd();
1454 
1455             traceBeginAndSlog("StartUpdateLockService");
1456             try {
1457                 ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
1458                         new UpdateLockService(context));
1459             } catch (Throwable e) {
1460                 reportWtf("starting UpdateLockService", e);
1461             }
1462             traceEnd();
1463 
1464             traceBeginAndSlog("StartNotificationManager");
1465             mSystemServiceManager.startService(NotificationManagerService.class);
1466             SystemNotificationChannels.removeDeprecated(context);
1467             SystemNotificationChannels.createAll(context);
1468             notification = INotificationManager.Stub.asInterface(
1469                     ServiceManager.getService(Context.NOTIFICATION_SERVICE));
1470             traceEnd();
1471 
1472             traceBeginAndSlog("StartDeviceMonitor");
1473             mSystemServiceManager.startService(DeviceStorageMonitorService.class);
1474             traceEnd();
1475 
1476             traceBeginAndSlog("StartLocationManagerService");
1477             try {
1478                 location = new LocationManagerService(context);
1479                 ServiceManager.addService(Context.LOCATION_SERVICE, location);
1480             } catch (Throwable e) {
1481                 reportWtf("starting Location Manager", e);
1482             }
1483             traceEnd();
1484 
1485             traceBeginAndSlog("StartCountryDetectorService");
1486             try {
1487                 countryDetector = new CountryDetectorService(context);
1488                 ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
1489             } catch (Throwable e) {
1490                 reportWtf("starting Country Detector", e);
1491             }
1492             traceEnd();
1493 
1494             traceBeginAndSlog("StartTimeDetectorService");
1495             try {
1496                 mSystemServiceManager.startService(TIME_DETECTOR_SERVICE_CLASS);
1497             } catch (Throwable e) {
1498                 reportWtf("starting StartTimeDetectorService service", e);
1499             }
1500             traceEnd();
1501 
1502             traceBeginAndSlog("StartTimeZoneDetectorService");
1503             try {
1504                 mSystemServiceManager.startService(TIME_ZONE_DETECTOR_SERVICE_CLASS);
1505             } catch (Throwable e) {
1506                 reportWtf("starting StartTimeZoneDetectorService service", e);
1507             }
1508             traceEnd();
1509 
1510             if (!isWatch) {
1511                 traceBeginAndSlog("StartSearchManagerService");
1512                 try {
1513                     mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS);
1514                 } catch (Throwable e) {
1515                     reportWtf("starting Search Service", e);
1516                 }
1517                 traceEnd();
1518             }
1519 
1520             if (context.getResources().getBoolean(R.bool.config_enableWallpaperService)) {
1521                 traceBeginAndSlog("StartWallpaperManagerService");
1522                 mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
1523                 traceEnd();
1524             } else {
1525                 Slog.i(TAG, "Wallpaper service disabled by config");
1526             }
1527 
1528             traceBeginAndSlog("StartAudioService");
1529             if (!isArc) {
1530                 mSystemServiceManager.startService(AudioService.Lifecycle.class);
1531             } else {
1532                 String className = context.getResources()
1533                         .getString(R.string.config_deviceSpecificAudioService);
1534                 try {
1535                     mSystemServiceManager.startService(className + "$Lifecycle");
1536                 } catch (Throwable e) {
1537                     reportWtf("starting " + className, e);
1538                 }
1539             }
1540             traceEnd();
1541 
1542             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BROADCAST_RADIO)) {
1543                 traceBeginAndSlog("StartBroadcastRadioService");
1544                 mSystemServiceManager.startService(BroadcastRadioService.class);
1545                 traceEnd();
1546             }
1547 
1548             traceBeginAndSlog("StartDockObserver");
1549             mSystemServiceManager.startService(DockObserver.class);
1550             traceEnd();
1551 
1552             if (isWatch) {
1553                 traceBeginAndSlog("StartThermalObserver");
1554                 mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS);
1555                 traceEnd();
1556             }
1557 
1558             traceBeginAndSlog("StartWiredAccessoryManager");
1559             try {
1560                 // Listen for wired headset changes
1561                 inputManager.setWiredAccessoryCallbacks(
1562                         new WiredAccessoryManager(context, inputManager));
1563             } catch (Throwable e) {
1564                 reportWtf("starting WiredAccessoryManager", e);
1565             }
1566             traceEnd();
1567 
1568             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) {
1569                 // Start MIDI Manager service
1570                 traceBeginAndSlog("StartMidiManager");
1571                 mSystemServiceManager.startService(MIDI_SERVICE_CLASS);
1572                 traceEnd();
1573             }
1574 
1575             // Start ADB Debugging Service
1576             traceBeginAndSlog("StartAdbService");
1577             try {
1578                 mSystemServiceManager.startService(ADB_SERVICE_CLASS);
1579             } catch (Throwable e) {
1580                 Slog.e(TAG, "Failure starting AdbService");
1581             }
1582             traceEnd();
1583 
1584             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)
1585                     || mPackageManager.hasSystemFeature(
1586                     PackageManager.FEATURE_USB_ACCESSORY)
1587                     || isEmulator) {
1588                 // Manage USB host and device support
1589                 traceBeginAndSlog("StartUsbService");
1590                 mSystemServiceManager.startService(USB_SERVICE_CLASS);
1591                 traceEnd();
1592             }
1593 
1594             if (!isWatch) {
1595                 traceBeginAndSlog("StartSerialService");
1596                 try {
1597                     // Serial port support
1598                     serial = new SerialService(context);
1599                     ServiceManager.addService(Context.SERIAL_SERVICE, serial);
1600                 } catch (Throwable e) {
1601                     Slog.e(TAG, "Failure starting SerialService", e);
1602                 }
1603                 traceEnd();
1604             }
1605 
1606             traceBeginAndSlog("StartHardwarePropertiesManagerService");
1607             try {
1608                 hardwarePropertiesService = new HardwarePropertiesManagerService(context);
1609                 ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE,
1610                         hardwarePropertiesService);
1611             } catch (Throwable e) {
1612                 Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e);
1613             }
1614             traceEnd();
1615 
1616             traceBeginAndSlog("StartTwilightService");
1617             mSystemServiceManager.startService(TwilightService.class);
1618             traceEnd();
1619 
1620             traceBeginAndSlog("StartColorDisplay");
1621             mSystemServiceManager.startService(ColorDisplayService.class);
1622             traceEnd();
1623 
1624             traceBeginAndSlog("StartJobScheduler");
1625             mSystemServiceManager.startService(JobSchedulerService.class);
1626             traceEnd();
1627 
1628             traceBeginAndSlog("StartSoundTrigger");
1629             mSystemServiceManager.startService(SoundTriggerService.class);
1630             traceEnd();
1631 
1632             traceBeginAndSlog("StartTrustManager");
1633             mSystemServiceManager.startService(TrustManagerService.class);
1634             traceEnd();
1635 
1636             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) {
1637                 traceBeginAndSlog("StartBackupManager");
1638                 mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS);
1639                 traceEnd();
1640             }
1641 
1642             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)
1643                     || context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {
1644                 traceBeginAndSlog("StartAppWidgetService");
1645                 mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS);
1646                 traceEnd();
1647             }
1648 
1649             // Grants default permissions and defines roles
1650             traceBeginAndSlog("StartRoleManagerService");
1651             mSystemServiceManager.startService(new RoleManagerService(
1652                     mSystemContext, new LegacyRoleResolutionPolicy(mSystemContext)));
1653             traceEnd();
1654 
1655             // We need to always start this service, regardless of whether the
1656             // FEATURE_VOICE_RECOGNIZERS feature is set, because it needs to take care
1657             // of initializing various settings.  It will internally modify its behavior
1658             // based on that feature.
1659             traceBeginAndSlog("StartVoiceRecognitionManager");
1660             mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS);
1661             traceEnd();
1662 
1663             if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) {
1664                 traceBeginAndSlog("StartGestureLauncher");
1665                 mSystemServiceManager.startService(GestureLauncherService.class);
1666                 traceEnd();
1667             }
1668             traceBeginAndSlog("StartSensorNotification");
1669             mSystemServiceManager.startService(SensorNotificationService.class);
1670             traceEnd();
1671 
1672             traceBeginAndSlog("StartContextHubSystemService");
1673             mSystemServiceManager.startService(ContextHubSystemService.class);
1674             traceEnd();
1675 
1676             traceBeginAndSlog("StartDiskStatsService");
1677             try {
1678                 ServiceManager.addService("diskstats", new DiskStatsService(context));
1679             } catch (Throwable e) {
1680                 reportWtf("starting DiskStats Service", e);
1681             }
1682             traceEnd();
1683 
1684             traceBeginAndSlog("RuntimeService");
1685             try {
1686                 ServiceManager.addService("runtime", new RuntimeService(context));
1687             } catch (Throwable e) {
1688                 reportWtf("starting RuntimeService", e);
1689             }
1690             traceEnd();
1691 
1692             // timezone.RulesManagerService will prevent a device starting up if the chain of trust
1693             // required for safe time zone updates might be broken. RuleManagerService cannot do
1694             // this check when mOnlyCore == true, so we don't enable the service in this case.
1695             // This service requires that JobSchedulerService is already started when it starts.
1696             final boolean startRulesManagerService =
1697                     !mOnlyCore && context.getResources().getBoolean(
1698                             R.bool.config_enableUpdateableTimeZoneRules);
1699             if (startRulesManagerService) {
1700                 traceBeginAndSlog("StartTimeZoneRulesManagerService");
1701                 mSystemServiceManager.startService(TIME_ZONE_RULES_MANAGER_SERVICE_CLASS);
1702                 traceEnd();
1703             }
1704 
1705             if (!isWatch && !disableNetworkTime) {
1706                 traceBeginAndSlog("StartNetworkTimeUpdateService");
1707                 try {
1708                     networkTimeUpdater = new NetworkTimeUpdateService(context);
1709                     ServiceManager.addService("network_time_update_service", networkTimeUpdater);
1710                 } catch (Throwable e) {
1711                     reportWtf("starting NetworkTimeUpdate service", e);
1712                 }
1713                 traceEnd();
1714             }
1715 
1716             traceBeginAndSlog("CertBlacklister");
1717             try {
1718                 CertBlacklister blacklister = new CertBlacklister(context);
1719             } catch (Throwable e) {
1720                 reportWtf("starting CertBlacklister", e);
1721             }
1722             traceEnd();
1723 
1724             if (EmergencyAffordanceManager.ENABLED) {
1725                 // EmergencyMode service
1726                 traceBeginAndSlog("StartEmergencyAffordanceService");
1727                 mSystemServiceManager.startService(EmergencyAffordanceService.class);
1728                 traceEnd();
1729             }
1730 
1731             // Dreams (interactive idle-time views, a/k/a screen savers, and doze mode)
1732             traceBeginAndSlog("StartDreamManager");
1733             mSystemServiceManager.startService(DreamManagerService.class);
1734             traceEnd();
1735 
1736             traceBeginAndSlog("AddGraphicsStatsService");
1737             ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE,
1738                     new GraphicsStatsService(context));
1739             traceEnd();
1740 
1741             if (CoverageService.ENABLED) {
1742                 traceBeginAndSlog("AddCoverageService");
1743                 ServiceManager.addService(CoverageService.COVERAGE_SERVICE, new CoverageService());
1744                 traceEnd();
1745             }
1746 
1747             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) {
1748                 traceBeginAndSlog("StartPrintManager");
1749                 mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS);
1750                 traceEnd();
1751             }
1752 
1753             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_COMPANION_DEVICE_SETUP)) {
1754                 traceBeginAndSlog("StartCompanionDeviceManager");
1755                 mSystemServiceManager.startService(COMPANION_DEVICE_MANAGER_SERVICE_CLASS);
1756                 traceEnd();
1757             }
1758 
1759             traceBeginAndSlog("StartRestrictionManager");
1760             mSystemServiceManager.startService(RestrictionsManagerService.class);
1761             traceEnd();
1762 
1763             traceBeginAndSlog("StartMediaSessionService");
1764             mSystemServiceManager.startService(MediaSessionService.class);
1765             traceEnd();
1766 
1767             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) {
1768                 traceBeginAndSlog("StartHdmiControlService");
1769                 mSystemServiceManager.startService(HdmiControlService.class);
1770                 traceEnd();
1771             }
1772 
1773             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)
1774                     || mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
1775                 traceBeginAndSlog("StartTvInputManager");
1776                 mSystemServiceManager.startService(TvInputManagerService.class);
1777                 traceEnd();
1778             }
1779 
1780             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
1781                 traceBeginAndSlog("StartMediaResourceMonitor");
1782                 mSystemServiceManager.startService(MediaResourceMonitorService.class);
1783                 traceEnd();
1784             }
1785 
1786             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
1787                 traceBeginAndSlog("StartTvRemoteService");
1788                 mSystemServiceManager.startService(TvRemoteService.class);
1789                 traceEnd();
1790             }
1791 
1792             traceBeginAndSlog("StartMediaRouterService");
1793             try {
1794                 mediaRouter = new MediaRouterService(context);
1795                 ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);
1796             } catch (Throwable e) {
1797                 reportWtf("starting MediaRouterService", e);
1798             }
1799             traceEnd();
1800 
1801             final boolean hasFeatureFace
1802                     = mPackageManager.hasSystemFeature(PackageManager.FEATURE_FACE);
1803             final boolean hasFeatureIris
1804                     = mPackageManager.hasSystemFeature(PackageManager.FEATURE_IRIS);
1805             final boolean hasFeatureFingerprint
1806                     = mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);
1807 
1808             if (hasFeatureFace) {
1809                 traceBeginAndSlog("StartFaceSensor");
1810                 mSystemServiceManager.startService(FaceService.class);
1811                 traceEnd();
1812             }
1813 
1814             if (hasFeatureIris) {
1815                 traceBeginAndSlog("StartIrisSensor");
1816                 mSystemServiceManager.startService(IrisService.class);
1817                 traceEnd();
1818             }
1819 
1820             if (hasFeatureFingerprint) {
1821                 traceBeginAndSlog("StartFingerprintSensor");
1822                 mSystemServiceManager.startService(FingerprintService.class);
1823                 traceEnd();
1824             }
1825 
1826             if (hasFeatureFace || hasFeatureIris || hasFeatureFingerprint) {
1827                 // Start this service after all biometric services.
1828                 traceBeginAndSlog("StartBiometricService");
1829                 mSystemServiceManager.startService(BiometricService.class);
1830                 traceEnd();
1831             }
1832 
1833             traceBeginAndSlog("StartBackgroundDexOptService");
1834             try {
1835                 BackgroundDexOptService.schedule(context);
1836             } catch (Throwable e) {
1837                 reportWtf("starting StartBackgroundDexOptService", e);
1838             }
1839             traceEnd();
1840 
1841             if (!isWatch) {
1842                 // We don't run this on watches as there are no plans to use the data logged
1843                 // on watch devices.
1844                 traceBeginAndSlog("StartDynamicCodeLoggingService");
1845                 try {
1846                     DynamicCodeLoggingService.schedule(context);
1847                 } catch (Throwable e) {
1848                     reportWtf("starting DynamicCodeLoggingService", e);
1849                 }
1850                 traceEnd();
1851             }
1852 
1853             if (!isWatch) {
1854                 traceBeginAndSlog("StartPruneInstantAppsJobService");
1855                 try {
1856                     PruneInstantAppsJobService.schedule(context);
1857                 } catch (Throwable e) {
1858                     reportWtf("StartPruneInstantAppsJobService", e);
1859                 }
1860                 traceEnd();
1861             }
1862 
1863             // LauncherAppsService uses ShortcutService.
1864             traceBeginAndSlog("StartShortcutServiceLifecycle");
1865             mSystemServiceManager.startService(ShortcutService.Lifecycle.class);
1866             traceEnd();
1867 
1868             traceBeginAndSlog("StartLauncherAppsService");
1869             mSystemServiceManager.startService(LauncherAppsService.class);
1870             traceEnd();
1871 
1872             traceBeginAndSlog("StartCrossProfileAppsService");
1873             mSystemServiceManager.startService(CrossProfileAppsService.class);
1874             traceEnd();
1875         }
1876 
1877         if (!isWatch) {
1878             traceBeginAndSlog("StartMediaProjectionManager");
1879             mSystemServiceManager.startService(MediaProjectionManagerService.class);
1880             traceEnd();
1881         }
1882 
1883         if (isWatch) {
1884             // Must be started before services that depend it, e.g. WearConnectivityService
1885             traceBeginAndSlog("StartWearPowerService");
1886             mSystemServiceManager.startService(WEAR_POWER_SERVICE_CLASS);
1887             traceEnd();
1888 
1889             traceBeginAndSlog("StartWearConnectivityService");
1890             mSystemServiceManager.startService(WEAR_CONNECTIVITY_SERVICE_CLASS);
1891             traceEnd();
1892 
1893             traceBeginAndSlog("StartWearDisplayService");
1894             mSystemServiceManager.startService(WEAR_DISPLAY_SERVICE_CLASS);
1895             traceEnd();
1896 
1897             traceBeginAndSlog("StartWearTimeService");
1898             mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS);
1899             traceEnd();
1900 
1901             if (enableLeftyService) {
1902                 traceBeginAndSlog("StartWearLeftyService");
1903                 mSystemServiceManager.startService(WEAR_LEFTY_SERVICE_CLASS);
1904                 traceEnd();
1905             }
1906 
1907             traceBeginAndSlog("StartWearGlobalActionsService");
1908             mSystemServiceManager.startService(WEAR_GLOBAL_ACTIONS_SERVICE_CLASS);
1909             traceEnd();
1910         }
1911 
1912         if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_SLICES_DISABLED)) {
1913             traceBeginAndSlog("StartSliceManagerService");
1914             mSystemServiceManager.startService(SLICE_MANAGER_SERVICE_CLASS);
1915             traceEnd();
1916         }
1917 
1918         if (!disableCameraService) {
1919             traceBeginAndSlog("StartCameraServiceProxy");
1920             mSystemServiceManager.startService(CameraServiceProxy.class);
1921             traceEnd();
1922         }
1923 
1924         if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_EMBEDDED)) {
1925             traceBeginAndSlog("StartIoTSystemService");
1926             mSystemServiceManager.startService(IOT_SERVICE_CLASS);
1927             traceEnd();
1928         }
1929 
1930         // Statsd helper
1931         traceBeginAndSlog("StartStatsCompanionService");
1932         mSystemServiceManager.startService(StatsCompanionService.Lifecycle.class);
1933         traceEnd();
1934 
1935         // Incidentd and dumpstated helper
1936         traceBeginAndSlog("StartIncidentCompanionService");
1937         mSystemServiceManager.startService(IncidentCompanionService.class);
1938         traceEnd();
1939 
1940         if (safeMode) {
1941             mActivityManagerService.enterSafeMode();
1942         }
1943 
1944         // MMS service broker
1945         traceBeginAndSlog("StartMmsService");
1946         mmsService = mSystemServiceManager.startService(MmsServiceBroker.class);
1947         traceEnd();
1948 
1949         if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOFILL)) {
1950             traceBeginAndSlog("StartAutoFillService");
1951             mSystemServiceManager.startService(AUTO_FILL_MANAGER_SERVICE_CLASS);
1952             traceEnd();
1953         }
1954 
1955         // NOTE: ClipboardService depends on ContentCapture and Autofill
1956         traceBeginAndSlog("StartClipboardService");
1957         mSystemServiceManager.startService(ClipboardService.class);
1958         traceEnd();
1959 
1960         traceBeginAndSlog("AppServiceManager");
1961         mSystemServiceManager.startService(AppBindingService.Lifecycle.class);
1962         traceEnd();
1963 
1964         // It is now time to start up the app processes...
1965 
1966         traceBeginAndSlog("MakeVibratorServiceReady");
1967         try {
1968             vibrator.systemReady();
1969         } catch (Throwable e) {
1970             reportWtf("making Vibrator Service ready", e);
1971         }
1972         traceEnd();
1973 
1974         traceBeginAndSlog("MakeLockSettingsServiceReady");
1975         if (lockSettings != null) {
1976             try {
1977                 lockSettings.systemReady();
1978             } catch (Throwable e) {
1979                 reportWtf("making Lock Settings Service ready", e);
1980             }
1981         }
1982         traceEnd();
1983 
1984         // Needed by DevicePolicyManager for initialization
1985         traceBeginAndSlog("StartBootPhaseLockSettingsReady");
1986         mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
1987         traceEnd();
1988 
1989         traceBeginAndSlog("StartBootPhaseSystemServicesReady");
1990         mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
1991         traceEnd();
1992 
1993         traceBeginAndSlog("MakeWindowManagerServiceReady");
1994         try {
1995             wm.systemReady();
1996         } catch (Throwable e) {
1997             reportWtf("making Window Manager Service ready", e);
1998         }
1999         traceEnd();
2000 
2001         if (safeMode) {
2002             mActivityManagerService.showSafeModeOverlay();
2003         }
2004 
2005         // Update the configuration for this context by hand, because we're going
2006         // to start using it before the config change done in wm.systemReady() will
2007         // propagate to it.
2008         final Configuration config = wm.computeNewConfiguration(DEFAULT_DISPLAY);
2009         DisplayMetrics metrics = new DisplayMetrics();
2010         WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
2011         w.getDefaultDisplay().getMetrics(metrics);
2012         context.getResources().updateConfiguration(config, metrics);
2013 
2014         // The system context's theme may be configuration-dependent.
2015         final Theme systemTheme = context.getTheme();
2016         if (systemTheme.getChangingConfigurations() != 0) {
2017             systemTheme.rebase();
2018         }
2019 
2020         traceBeginAndSlog("MakePowerManagerServiceReady");
2021         try {
2022             // TODO: use boot phase
2023             mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
2024         } catch (Throwable e) {
2025             reportWtf("making Power Manager Service ready", e);
2026         }
2027         traceEnd();
2028 
2029         // Permission policy service
2030         traceBeginAndSlog("StartPermissionPolicyService");
2031         mSystemServiceManager.startService(PermissionPolicyService.class);
2032         traceEnd();
2033 
2034         traceBeginAndSlog("MakePackageManagerServiceReady");
2035         mPackageManagerService.systemReady();
2036         traceEnd();
2037 
2038         traceBeginAndSlog("MakeDisplayManagerServiceReady");
2039         try {
2040             // TODO: use boot phase and communicate these flags some other way
2041             mDisplayManagerService.systemReady(safeMode, mOnlyCore);
2042         } catch (Throwable e) {
2043             reportWtf("making Display Manager Service ready", e);
2044         }
2045         traceEnd();
2046 
2047         mSystemServiceManager.setSafeMode(safeMode);
2048 
2049         // Start device specific services
2050         traceBeginAndSlog("StartDeviceSpecificServices");
2051         final String[] classes = mSystemContext.getResources().getStringArray(
2052                 R.array.config_deviceSpecificSystemServices);
2053         for (final String className : classes) {
2054             traceBeginAndSlog("StartDeviceSpecificServices " + className);
2055             try {
2056                 mSystemServiceManager.startService(className);
2057             } catch (Throwable e) {
2058                 reportWtf("starting " + className, e);
2059             }
2060             traceEnd();
2061         }
2062         traceEnd();
2063 
2064         traceBeginAndSlog("StartBootPhaseDeviceSpecificServicesReady");
2065         mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);
2066         traceEnd();
2067 
2068         // These are needed to propagate to the runnable below.
2069         final NetworkManagementService networkManagementF = networkManagement;
2070         final NetworkStatsService networkStatsF = networkStats;
2071         final NetworkPolicyManagerService networkPolicyF = networkPolicy;
2072         final ConnectivityService connectivityF = connectivity;
2073         final LocationManagerService locationF = location;
2074         final CountryDetectorService countryDetectorF = countryDetector;
2075         final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
2076         final InputManagerService inputManagerF = inputManager;
2077         final TelephonyRegistry telephonyRegistryF = telephonyRegistry;
2078         final MediaRouterService mediaRouterF = mediaRouter;
2079         final MmsServiceBroker mmsServiceF = mmsService;
2080         final IpSecService ipSecServiceF = ipSecService;
2081         final WindowManagerService windowManagerF = wm;
2082 
2083         // We now tell the activity manager it is okay to run third party
2084         // code.  It will call back into us once it has gotten to the state
2085         // where third party code can really run (but before it has actually
2086         // started launching the initial applications), for us to complete our
2087         // initialization.
2088         mActivityManagerService.systemReady(() -> {
2089             Slog.i(TAG, "Making services ready");
2090             traceBeginAndSlog("StartActivityManagerReadyPhase");
2091             mSystemServiceManager.startBootPhase(
2092                     SystemService.PHASE_ACTIVITY_MANAGER_READY);
2093             traceEnd();
2094             traceBeginAndSlog("StartObservingNativeCrashes");
2095             try {
2096                 mActivityManagerService.startObservingNativeCrashes();
2097             } catch (Throwable e) {
2098                 reportWtf("observing native crashes", e);
2099             }
2100             traceEnd();
2101 
2102             // No dependency on Webview preparation in system server. But this should
2103             // be completed before allowing 3rd party
2104             final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
2105             Future<?> webviewPrep = null;
2106             if (!mOnlyCore && mWebViewUpdateService != null) {
2107                 webviewPrep = SystemServerInitThreadPool.get().submit(() -> {
2108                     Slog.i(TAG, WEBVIEW_PREPARATION);
2109                     TimingsTraceLog traceLog = new TimingsTraceLog(
2110                             SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
2111                     traceLog.traceBegin(WEBVIEW_PREPARATION);
2112                     ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
2113                     mZygotePreload = null;
2114                     mWebViewUpdateService.prepareWebViewInSystemServer();
2115                     traceLog.traceEnd();
2116                 }, WEBVIEW_PREPARATION);
2117             }
2118 
2119             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
2120                 traceBeginAndSlog("StartCarServiceHelperService");
2121                 mSystemServiceManager.startService(CAR_SERVICE_HELPER_SERVICE_CLASS);
2122                 traceEnd();
2123             }
2124 
2125             traceBeginAndSlog("StartSystemUI");
2126             try {
2127                 startSystemUi(context, windowManagerF);
2128             } catch (Throwable e) {
2129                 reportWtf("starting System UI", e);
2130             }
2131             traceEnd();
2132             // Enable airplane mode in safe mode. setAirplaneMode() cannot be called
2133             // earlier as it sends broadcasts to other services.
2134             // TODO: This may actually be too late if radio firmware already started leaking
2135             // RF before the respective services start. However, fixing this requires changes
2136             // to radio firmware and interfaces.
2137             if (safeMode) {
2138                 traceBeginAndSlog("EnableAirplaneModeInSafeMode");
2139                 try {
2140                     connectivityF.setAirplaneMode(true);
2141                 } catch (Throwable e) {
2142                     reportWtf("enabling Airplane Mode during Safe Mode bootup", e);
2143                 }
2144                 traceEnd();
2145             }
2146             traceBeginAndSlog("MakeNetworkManagementServiceReady");
2147             try {
2148                 if (networkManagementF != null) {
2149                     networkManagementF.systemReady();
2150                 }
2151             } catch (Throwable e) {
2152                 reportWtf("making Network Managment Service ready", e);
2153             }
2154             CountDownLatch networkPolicyInitReadySignal = null;
2155             if (networkPolicyF != null) {
2156                 networkPolicyInitReadySignal = networkPolicyF
2157                         .networkScoreAndNetworkManagementServiceReady();
2158             }
2159             traceEnd();
2160             traceBeginAndSlog("MakeIpSecServiceReady");
2161             try {
2162                 if (ipSecServiceF != null) {
2163                     ipSecServiceF.systemReady();
2164                 }
2165             } catch (Throwable e) {
2166                 reportWtf("making IpSec Service ready", e);
2167             }
2168             traceEnd();
2169             traceBeginAndSlog("MakeNetworkStatsServiceReady");
2170             try {
2171                 if (networkStatsF != null) {
2172                     networkStatsF.systemReady();
2173                 }
2174             } catch (Throwable e) {
2175                 reportWtf("making Network Stats Service ready", e);
2176             }
2177             traceEnd();
2178             traceBeginAndSlog("MakeConnectivityServiceReady");
2179             try {
2180                 if (connectivityF != null) {
2181                     connectivityF.systemReady();
2182                 }
2183             } catch (Throwable e) {
2184                 reportWtf("making Connectivity Service ready", e);
2185             }
2186             traceEnd();
2187             traceBeginAndSlog("MakeNetworkPolicyServiceReady");
2188             try {
2189                 if (networkPolicyF != null) {
2190                     networkPolicyF.systemReady(networkPolicyInitReadySignal);
2191                 }
2192             } catch (Throwable e) {
2193                 reportWtf("making Network Policy Service ready", e);
2194             }
2195             traceEnd();
2196 
2197             // Wait for all packages to be prepared
2198             mPackageManagerService.waitForAppDataPrepared();
2199 
2200             // It is now okay to let the various system services start their
2201             // third party code...
2202             traceBeginAndSlog("PhaseThirdPartyAppsCanStart");
2203             // confirm webview completion before starting 3rd party
2204             if (webviewPrep != null) {
2205                 ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);
2206             }
2207             mSystemServiceManager.startBootPhase(
2208                     SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
2209             traceEnd();
2210 
2211             traceBeginAndSlog("StartNetworkStack");
2212             try {
2213                 // Note : the network stack is creating on-demand objects that need to send
2214                 // broadcasts, which means it currently depends on being started after
2215                 // ActivityManagerService.mSystemReady and ActivityManagerService.mProcessesReady
2216                 // are set to true. Be careful if moving this to a different place in the
2217                 // startup sequence.
2218                 NetworkStackClient.getInstance().start();
2219             } catch (Throwable e) {
2220                 reportWtf("starting Network Stack", e);
2221             }
2222             traceEnd();
2223 
2224             traceBeginAndSlog("StartTethering");
2225             try {
2226                 // TODO: hide implementation details, b/146312721.
2227                 ConnectivityModuleConnector.getInstance().startModuleService(
2228                         TETHERING_CONNECTOR_CLASS,
2229                         PERMISSION_MAINLINE_NETWORK_STACK, service -> {
2230                             ServiceManager.addService(Context.TETHERING_SERVICE, service,
2231                                     false /* allowIsolated */,
2232                                     DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL);
2233                         });
2234             } catch (Throwable e) {
2235                 reportWtf("starting Tethering", e);
2236             }
2237             traceEnd();
2238 
2239             traceBeginAndSlog("MakeLocationServiceReady");
2240             try {
2241                 if (locationF != null) {
2242                     locationF.systemRunning();
2243                 }
2244             } catch (Throwable e) {
2245                 reportWtf("Notifying Location Service running", e);
2246             }
2247             traceEnd();
2248             traceBeginAndSlog("MakeCountryDetectionServiceReady");
2249             try {
2250                 if (countryDetectorF != null) {
2251                     countryDetectorF.systemRunning();
2252                 }
2253             } catch (Throwable e) {
2254                 reportWtf("Notifying CountryDetectorService running", e);
2255             }
2256             traceEnd();
2257             traceBeginAndSlog("MakeNetworkTimeUpdateReady");
2258             try {
2259                 if (networkTimeUpdaterF != null) {
2260                     networkTimeUpdaterF.systemRunning();
2261                 }
2262             } catch (Throwable e) {
2263                 reportWtf("Notifying NetworkTimeService running", e);
2264             }
2265             traceEnd();
2266             traceBeginAndSlog("MakeInputManagerServiceReady");
2267             try {
2268                 // TODO(BT) Pass parameter to input manager
2269                 if (inputManagerF != null) {
2270                     inputManagerF.systemRunning();
2271                 }
2272             } catch (Throwable e) {
2273                 reportWtf("Notifying InputManagerService running", e);
2274             }
2275             traceEnd();
2276             traceBeginAndSlog("MakeTelephonyRegistryReady");
2277             try {
2278                 if (telephonyRegistryF != null) {
2279                     telephonyRegistryF.systemRunning();
2280                 }
2281             } catch (Throwable e) {
2282                 reportWtf("Notifying TelephonyRegistry running", e);
2283             }
2284             traceEnd();
2285             traceBeginAndSlog("MakeMediaRouterServiceReady");
2286             try {
2287                 if (mediaRouterF != null) {
2288                     mediaRouterF.systemRunning();
2289                 }
2290             } catch (Throwable e) {
2291                 reportWtf("Notifying MediaRouterService running", e);
2292             }
2293             traceEnd();
2294             traceBeginAndSlog("MakeMmsServiceReady");
2295             try {
2296                 if (mmsServiceF != null) {
2297                     mmsServiceF.systemRunning();
2298                 }
2299             } catch (Throwable e) {
2300                 reportWtf("Notifying MmsService running", e);
2301             }
2302             traceEnd();
2303 
2304             traceBeginAndSlog("IncidentDaemonReady");
2305             try {
2306                 // TODO: Switch from checkService to getService once it's always
2307                 // in the build and should reliably be there.
2308                 final IIncidentManager incident = IIncidentManager.Stub.asInterface(
2309                         ServiceManager.getService(Context.INCIDENT_SERVICE));
2310                 if (incident != null) {
2311                     incident.systemRunning();
2312                 }
2313             } catch (Throwable e) {
2314                 reportWtf("Notifying incident daemon running", e);
2315             }
2316             traceEnd();
2317         }, BOOT_TIMINGS_TRACE_LOG);
2318     }
2319 
deviceHasConfigString(@onNull Context context, @StringRes int resId)2320     private boolean deviceHasConfigString(@NonNull Context context, @StringRes int resId) {
2321         String serviceName = context.getString(resId);
2322         return !TextUtils.isEmpty(serviceName);
2323     }
2324 
startSystemCaptionsManagerService(@onNull Context context)2325     private void startSystemCaptionsManagerService(@NonNull Context context) {
2326         if (!deviceHasConfigString(context, R.string.config_defaultSystemCaptionsManagerService)) {
2327             Slog.d(TAG, "SystemCaptionsManagerService disabled because resource is not overlaid");
2328             return;
2329         }
2330 
2331         traceBeginAndSlog("StartSystemCaptionsManagerService");
2332         mSystemServiceManager.startService(SYSTEM_CAPTIONS_MANAGER_SERVICE_CLASS);
2333         traceEnd();
2334     }
2335 
startContentCaptureService(@onNull Context context)2336     private void startContentCaptureService(@NonNull Context context) {
2337         // First check if it was explicitly enabled by DeviceConfig
2338         boolean explicitlyEnabled = false;
2339         String settings = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_CONTENT_CAPTURE,
2340                 ContentCaptureManager.DEVICE_CONFIG_PROPERTY_SERVICE_EXPLICITLY_ENABLED);
2341         if (settings != null && !settings.equalsIgnoreCase("default")) {
2342             explicitlyEnabled = Boolean.parseBoolean(settings);
2343             if (explicitlyEnabled) {
2344                 Slog.d(TAG, "ContentCaptureService explicitly enabled by DeviceConfig");
2345             } else {
2346                 Slog.d(TAG, "ContentCaptureService explicitly disabled by DeviceConfig");
2347                 return;
2348             }
2349         }
2350 
2351         // Then check if OEM overlaid the resource that defines the service.
2352         if (!explicitlyEnabled) {
2353             if (!deviceHasConfigString(context, R.string.config_defaultContentCaptureService)) {
2354                 Slog.d(TAG, "ContentCaptureService disabled because resource is not overlaid");
2355                 return;
2356             }
2357         }
2358 
2359         traceBeginAndSlog("StartContentCaptureService");
2360         mSystemServiceManager.startService(CONTENT_CAPTURE_MANAGER_SERVICE_CLASS);
2361 
2362         ContentCaptureManagerInternal ccmi =
2363                 LocalServices.getService(ContentCaptureManagerInternal.class);
2364         if (ccmi != null && mActivityManagerService != null) {
2365             mActivityManagerService.setContentCaptureManager(ccmi);
2366         }
2367 
2368         traceEnd();
2369     }
2370 
startAttentionService(@onNull Context context)2371     private void startAttentionService(@NonNull Context context) {
2372         if (!AttentionManagerService.isServiceConfigured(context)) {
2373             Slog.d(TAG, "AttentionService is not configured on this device");
2374             return;
2375         }
2376 
2377         traceBeginAndSlog("StartAttentionManagerService");
2378         mSystemServiceManager.startService(AttentionManagerService.class);
2379         traceEnd();
2380     }
2381 
startSystemUi(Context context, WindowManagerService windowManager)2382     private static void startSystemUi(Context context, WindowManagerService windowManager) {
2383         Intent intent = new Intent();
2384         intent.setComponent(new ComponentName("com.android.systemui",
2385                 "com.android.systemui.SystemUIService"));
2386         intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
2387         //Slog.d(TAG, "Starting service: " + intent);
2388         context.startServiceAsUser(intent, UserHandle.SYSTEM);
2389         windowManager.onSystemUiStarted();
2390     }
2391 
traceBeginAndSlog(@onNull String name)2392     private static void traceBeginAndSlog(@NonNull String name) {
2393         Slog.i(TAG, name);
2394         BOOT_TIMINGS_TRACE_LOG.traceBegin(name);
2395     }
2396 
traceEnd()2397     private static void traceEnd() {
2398         BOOT_TIMINGS_TRACE_LOG.traceEnd();
2399     }
2400 }
2401