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