• 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.system.OsConstants.O_CLOEXEC;
27 import static android.system.OsConstants.O_RDONLY;
28 import static android.view.Display.DEFAULT_DISPLAY;
29 
30 import static com.android.server.utils.TimingsTraceAndSlog.SYSTEM_SERVER_TIMING_TAG;
31 
32 import android.annotation.NonNull;
33 import android.annotation.StringRes;
34 import android.app.ActivityThread;
35 import android.app.AppCompatCallbacks;
36 import android.app.ApplicationErrorReport;
37 import android.app.INotificationManager;
38 import android.app.SystemServiceRegistry;
39 import android.app.admin.DevicePolicySafetyChecker;
40 import android.app.usage.UsageStatsManagerInternal;
41 import android.content.ContentResolver;
42 import android.content.Context;
43 import android.content.Intent;
44 import android.content.pm.IPackageManager;
45 import android.content.pm.PackageItemInfo;
46 import android.content.pm.PackageManager;
47 import android.content.pm.PackageManagerInternal;
48 import android.content.res.Configuration;
49 import android.content.res.Resources.Theme;
50 import android.database.sqlite.SQLiteCompatibilityWalFlags;
51 import android.database.sqlite.SQLiteGlobal;
52 import android.graphics.GraphicsStatsService;
53 import android.graphics.Typeface;
54 import android.hardware.display.DisplayManagerInternal;
55 import android.net.ConnectivityManager;
56 import android.net.ConnectivityModuleConnector;
57 import android.net.NetworkStackClient;
58 import android.os.BaseBundle;
59 import android.os.Binder;
60 import android.os.Build;
61 import android.os.Debug;
62 import android.os.Environment;
63 import android.os.FactoryTest;
64 import android.os.FileUtils;
65 import android.os.IBinder;
66 import android.os.IIncidentManager;
67 import android.os.Looper;
68 import android.os.Message;
69 import android.os.Parcel;
70 import android.os.PowerManager;
71 import android.os.Process;
72 import android.os.ServiceManager;
73 import android.os.StrictMode;
74 import android.os.SystemClock;
75 import android.os.SystemProperties;
76 import android.os.UserHandle;
77 import android.os.UserManager;
78 import android.os.storage.IStorageManager;
79 import android.provider.DeviceConfig;
80 import android.provider.Settings;
81 import android.server.ServerProtoEnums;
82 import android.sysprop.VoldProperties;
83 import android.system.ErrnoException;
84 import android.system.Os;
85 import android.text.TextUtils;
86 import android.util.ArrayMap;
87 import android.util.DisplayMetrics;
88 import android.util.Dumpable;
89 import android.util.EventLog;
90 import android.util.IndentingPrintWriter;
91 import android.util.Pair;
92 import android.util.Slog;
93 import android.util.TimeUtils;
94 import android.view.contentcapture.ContentCaptureManager;
95 
96 import com.android.i18n.timezone.ZoneInfoDb;
97 import com.android.internal.R;
98 import com.android.internal.annotations.GuardedBy;
99 import com.android.internal.notification.SystemNotificationChannels;
100 import com.android.internal.os.BinderInternal;
101 import com.android.internal.os.RuntimeInit;
102 import com.android.internal.policy.AttributeCache;
103 import com.android.internal.util.ConcurrentUtils;
104 import com.android.internal.util.EmergencyAffordanceManager;
105 import com.android.internal.util.FrameworkStatsLog;
106 import com.android.internal.widget.ILockSettings;
107 import com.android.server.am.ActivityManagerService;
108 import com.android.server.ambientcontext.AmbientContextManagerService;
109 import com.android.server.appbinding.AppBindingService;
110 import com.android.server.art.ArtManagerLocal;
111 import com.android.server.attention.AttentionManagerService;
112 import com.android.server.audio.AudioService;
113 import com.android.server.biometrics.AuthService;
114 import com.android.server.biometrics.BiometricService;
115 import com.android.server.biometrics.sensors.face.FaceService;
116 import com.android.server.biometrics.sensors.fingerprint.FingerprintService;
117 import com.android.server.biometrics.sensors.iris.IrisService;
118 import com.android.server.broadcastradio.BroadcastRadioService;
119 import com.android.server.camera.CameraServiceProxy;
120 import com.android.server.clipboard.ClipboardService;
121 import com.android.server.compat.PlatformCompat;
122 import com.android.server.compat.PlatformCompatNative;
123 import com.android.server.connectivity.PacProxyService;
124 import com.android.server.contentcapture.ContentCaptureManagerInternal;
125 import com.android.server.coverage.CoverageService;
126 import com.android.server.devicepolicy.DevicePolicyManagerService;
127 import com.android.server.devicestate.DeviceStateManagerService;
128 import com.android.server.display.DisplayManagerService;
129 import com.android.server.display.color.ColorDisplayService;
130 import com.android.server.dreams.DreamManagerService;
131 import com.android.server.emergency.EmergencyAffordanceService;
132 import com.android.server.gpu.GpuService;
133 import com.android.server.graphics.fonts.FontManagerService;
134 import com.android.server.hdmi.HdmiControlService;
135 import com.android.server.incident.IncidentCompanionService;
136 import com.android.server.input.InputManagerService;
137 import com.android.server.inputmethod.InputMethodManagerService;
138 import com.android.server.integrity.AppIntegrityManagerService;
139 import com.android.server.lights.LightsService;
140 import com.android.server.locales.LocaleManagerService;
141 import com.android.server.location.LocationManagerService;
142 import com.android.server.logcat.LogcatManagerService;
143 import com.android.server.media.MediaRouterService;
144 import com.android.server.media.metrics.MediaMetricsManagerService;
145 import com.android.server.media.projection.MediaProjectionManagerService;
146 import com.android.server.net.NetworkPolicyManagerService;
147 import com.android.server.net.watchlist.NetworkWatchlistService;
148 import com.android.server.notification.NotificationManagerService;
149 import com.android.server.oemlock.OemLockService;
150 import com.android.server.om.OverlayManagerService;
151 import com.android.server.os.BugreportManagerService;
152 import com.android.server.os.DeviceIdentifiersPolicyService;
153 import com.android.server.os.NativeTombstoneManagerService;
154 import com.android.server.os.SchedulingPolicyService;
155 import com.android.server.people.PeopleService;
156 import com.android.server.pm.ApexManager;
157 import com.android.server.pm.ApexSystemServiceInfo;
158 import com.android.server.pm.CrossProfileAppsService;
159 import com.android.server.pm.DataLoaderManagerService;
160 import com.android.server.pm.DynamicCodeLoggingService;
161 import com.android.server.pm.Installer;
162 import com.android.server.pm.LauncherAppsService;
163 import com.android.server.pm.OtaDexoptService;
164 import com.android.server.pm.PackageManagerService;
165 import com.android.server.pm.ShortcutService;
166 import com.android.server.pm.UserManagerService;
167 import com.android.server.pm.dex.OdsignStatsLogger;
168 import com.android.server.pm.dex.SystemServerDexLoadReporter;
169 import com.android.server.pm.verify.domain.DomainVerificationService;
170 import com.android.server.policy.AppOpsPolicy;
171 import com.android.server.policy.PermissionPolicyService;
172 import com.android.server.policy.PhoneWindowManager;
173 import com.android.server.policy.role.RoleServicePlatformHelperImpl;
174 import com.android.server.power.PowerManagerService;
175 import com.android.server.power.ShutdownThread;
176 import com.android.server.power.ThermalManagerService;
177 import com.android.server.power.hint.HintManagerService;
178 import com.android.server.powerstats.PowerStatsService;
179 import com.android.server.profcollect.ProfcollectForwardingService;
180 import com.android.server.recoverysystem.RecoverySystemService;
181 import com.android.server.resources.ResourcesManagerService;
182 import com.android.server.restrictions.RestrictionsManagerService;
183 import com.android.server.role.RoleServicePlatformHelper;
184 import com.android.server.rotationresolver.RotationResolverManagerService;
185 import com.android.server.security.AttestationVerificationManagerService;
186 import com.android.server.security.FileIntegrityService;
187 import com.android.server.security.KeyAttestationApplicationIdProviderService;
188 import com.android.server.security.KeyChainSystemService;
189 import com.android.server.sensorprivacy.SensorPrivacyService;
190 import com.android.server.sensors.SensorService;
191 import com.android.server.signedconfig.SignedConfigService;
192 import com.android.server.soundtrigger.SoundTriggerService;
193 import com.android.server.soundtrigger_middleware.SoundTriggerMiddlewareService;
194 import com.android.server.statusbar.StatusBarManagerService;
195 import com.android.server.storage.DeviceStorageMonitorService;
196 import com.android.server.telecom.TelecomLoaderService;
197 import com.android.server.testharness.TestHarnessModeService;
198 import com.android.server.textclassifier.TextClassificationManagerService;
199 import com.android.server.textservices.TextServicesManagerService;
200 import com.android.server.tracing.TracingServiceProxy;
201 import com.android.server.trust.TrustManagerService;
202 import com.android.server.tv.TvInputManagerService;
203 import com.android.server.tv.TvRemoteService;
204 import com.android.server.tv.interactive.TvInteractiveAppManagerService;
205 import com.android.server.tv.tunerresourcemanager.TunerResourceManagerService;
206 import com.android.server.twilight.TwilightService;
207 import com.android.server.uri.UriGrantsManagerService;
208 import com.android.server.usage.UsageStatsService;
209 import com.android.server.utils.TimingsTraceAndSlog;
210 import com.android.server.vibrator.VibratorManagerService;
211 import com.android.server.vr.VrManagerService;
212 import com.android.server.webkit.WebViewUpdateService;
213 import com.android.server.wm.ActivityTaskManagerService;
214 import com.android.server.wm.WindowManagerGlobalLock;
215 import com.android.server.wm.WindowManagerService;
216 
217 import dalvik.system.VMRuntime;
218 
219 import java.io.File;
220 import java.io.FileDescriptor;
221 import java.io.IOException;
222 import java.io.PrintWriter;
223 import java.text.SimpleDateFormat;
224 import java.util.Arrays;
225 import java.util.Date;
226 import java.util.LinkedList;
227 import java.util.List;
228 import java.util.Locale;
229 import java.util.Timer;
230 import java.util.TreeSet;
231 import java.util.concurrent.CountDownLatch;
232 import java.util.concurrent.Future;
233 
234 /**
235  * Entry point to {@code system_server}.
236  */
237 public final class SystemServer implements Dumpable {
238 
239     private static final String TAG = "SystemServer";
240 
241     private static final String ENCRYPTING_STATE = "trigger_restart_min_framework";
242     private static final String ENCRYPTED_STATE = "1";
243 
244     private static final long SLOW_DISPATCH_THRESHOLD_MS = 100;
245     private static final long SLOW_DELIVERY_THRESHOLD_MS = 200;
246 
247     /*
248      * Implementation class names. TODO: Move them to a codegen class or load
249      * them from the build system somehow.
250      */
251     private static final String BACKUP_MANAGER_SERVICE_CLASS =
252             "com.android.server.backup.BackupManagerService$Lifecycle";
253     private static final String APPWIDGET_SERVICE_CLASS =
254             "com.android.server.appwidget.AppWidgetService";
255     private static final String VOICE_RECOGNITION_MANAGER_SERVICE_CLASS =
256             "com.android.server.voiceinteraction.VoiceInteractionManagerService";
257     private static final String APP_HIBERNATION_SERVICE_CLASS =
258             "com.android.server.apphibernation.AppHibernationService";
259     private static final String PRINT_MANAGER_SERVICE_CLASS =
260             "com.android.server.print.PrintManagerService";
261     private static final String COMPANION_DEVICE_MANAGER_SERVICE_CLASS =
262             "com.android.server.companion.CompanionDeviceManagerService";
263     private static final String VIRTUAL_DEVICE_MANAGER_SERVICE_CLASS =
264             "com.android.server.companion.virtual.VirtualDeviceManagerService";
265     private static final String STATS_COMPANION_APEX_PATH =
266             "/apex/com.android.os.statsd/javalib/service-statsd.jar";
267     private static final String SCHEDULING_APEX_PATH =
268             "/apex/com.android.scheduling/javalib/service-scheduling.jar";
269     private static final String REBOOT_READINESS_LIFECYCLE_CLASS =
270             "com.android.server.scheduling.RebootReadinessManagerService$Lifecycle";
271     private static final String CONNECTIVITY_SERVICE_APEX_PATH =
272             "/apex/com.android.tethering/javalib/service-connectivity.jar";
273     private static final String STATS_COMPANION_LIFECYCLE_CLASS =
274             "com.android.server.stats.StatsCompanion$Lifecycle";
275     private static final String STATS_PULL_ATOM_SERVICE_CLASS =
276             "com.android.server.stats.pull.StatsPullAtomService";
277     private static final String STATS_BOOTSTRAP_ATOM_SERVICE_LIFECYCLE_CLASS =
278             "com.android.server.stats.bootstrap.StatsBootstrapAtomService$Lifecycle";
279     private static final String USB_SERVICE_CLASS =
280             "com.android.server.usb.UsbService$Lifecycle";
281     private static final String MIDI_SERVICE_CLASS =
282             "com.android.server.midi.MidiService$Lifecycle";
283     private static final String WIFI_APEX_SERVICE_JAR_PATH =
284             "/apex/com.android.wifi/javalib/service-wifi.jar";
285     private static final String WIFI_SERVICE_CLASS =
286             "com.android.server.wifi.WifiService";
287     private static final String WIFI_SCANNING_SERVICE_CLASS =
288             "com.android.server.wifi.scanner.WifiScanningService";
289     private static final String WIFI_RTT_SERVICE_CLASS =
290             "com.android.server.wifi.rtt.RttService";
291     private static final String WIFI_AWARE_SERVICE_CLASS =
292             "com.android.server.wifi.aware.WifiAwareService";
293     private static final String WIFI_P2P_SERVICE_CLASS =
294             "com.android.server.wifi.p2p.WifiP2pService";
295     private static final String LOWPAN_SERVICE_CLASS =
296             "com.android.server.lowpan.LowpanService";
297     private static final String JOB_SCHEDULER_SERVICE_CLASS =
298             "com.android.server.job.JobSchedulerService";
299     private static final String LOCK_SETTINGS_SERVICE_CLASS =
300             "com.android.server.locksettings.LockSettingsService$Lifecycle";
301     private static final String RESOURCE_ECONOMY_SERVICE_CLASS =
302             "com.android.server.tare.InternalResourceService";
303     private static final String STORAGE_MANAGER_SERVICE_CLASS =
304             "com.android.server.StorageManagerService$Lifecycle";
305     private static final String STORAGE_STATS_SERVICE_CLASS =
306             "com.android.server.usage.StorageStatsService$Lifecycle";
307     private static final String SEARCH_MANAGER_SERVICE_CLASS =
308             "com.android.server.search.SearchManagerService$Lifecycle";
309     private static final String THERMAL_OBSERVER_CLASS =
310             "com.google.android.clockwork.ThermalObserver";
311     private static final String WEAR_CONNECTIVITY_SERVICE_CLASS =
312             "com.android.clockwork.connectivity.WearConnectivityService";
313     private static final String WEAR_POWER_SERVICE_CLASS =
314             "com.android.clockwork.power.WearPowerService";
315     private static final String HEALTH_SERVICE_CLASS =
316             "com.google.android.clockwork.healthservices.HealthService";
317     private static final String WEAR_SIDEKICK_SERVICE_CLASS =
318             "com.google.android.clockwork.sidekick.SidekickService";
319     private static final String WEAR_DISPLAYOFFLOAD_SERVICE_CLASS =
320             "com.google.android.clockwork.displayoffload.DisplayOffloadService";
321     private static final String WEAR_DISPLAY_SERVICE_CLASS =
322             "com.google.android.clockwork.display.WearDisplayService";
323     private static final String WEAR_LEFTY_SERVICE_CLASS =
324             "com.google.android.clockwork.lefty.WearLeftyService";
325     private static final String WEAR_TIME_SERVICE_CLASS =
326             "com.google.android.clockwork.time.WearTimeService";
327     private static final String WEAR_GLOBAL_ACTIONS_SERVICE_CLASS =
328             "com.android.clockwork.globalactions.GlobalActionsService";
329     private static final String ACCOUNT_SERVICE_CLASS =
330             "com.android.server.accounts.AccountManagerService$Lifecycle";
331     private static final String CONTENT_SERVICE_CLASS =
332             "com.android.server.content.ContentService$Lifecycle";
333     private static final String WALLPAPER_SERVICE_CLASS =
334             "com.android.server.wallpaper.WallpaperManagerService$Lifecycle";
335     private static final String AUTO_FILL_MANAGER_SERVICE_CLASS =
336             "com.android.server.autofill.AutofillManagerService";
337     private static final String CONTENT_CAPTURE_MANAGER_SERVICE_CLASS =
338             "com.android.server.contentcapture.ContentCaptureManagerService";
339     private static final String TRANSLATION_MANAGER_SERVICE_CLASS =
340             "com.android.server.translation.TranslationManagerService";
341     private static final String MUSIC_RECOGNITION_MANAGER_SERVICE_CLASS =
342             "com.android.server.musicrecognition.MusicRecognitionManagerService";
343     private static final String SYSTEM_CAPTIONS_MANAGER_SERVICE_CLASS =
344             "com.android.server.systemcaptions.SystemCaptionsManagerService";
345     private static final String TEXT_TO_SPEECH_MANAGER_SERVICE_CLASS =
346             "com.android.server.texttospeech.TextToSpeechManagerService";
347     private static final String TIME_ZONE_RULES_MANAGER_SERVICE_CLASS =
348             "com.android.server.timezone.RulesManagerService$Lifecycle";
349     private static final String IOT_SERVICE_CLASS =
350             "com.android.things.server.IoTSystemService";
351     private static final String SLICE_MANAGER_SERVICE_CLASS =
352             "com.android.server.slice.SliceManagerService$Lifecycle";
353     private static final String CAR_SERVICE_HELPER_SERVICE_CLASS =
354             "com.android.internal.car.CarServiceHelperService";
355     private static final String TIME_DETECTOR_SERVICE_CLASS =
356             "com.android.server.timedetector.TimeDetectorService$Lifecycle";
357     private static final String TIME_ZONE_DETECTOR_SERVICE_CLASS =
358             "com.android.server.timezonedetector.TimeZoneDetectorService$Lifecycle";
359     private static final String LOCATION_TIME_ZONE_MANAGER_SERVICE_CLASS =
360             "com.android.server.timezonedetector.location.LocationTimeZoneManagerService$Lifecycle";
361     private static final String GNSS_TIME_UPDATE_SERVICE_CLASS =
362             "com.android.server.timedetector.GnssTimeUpdateService$Lifecycle";
363     private static final String ACCESSIBILITY_MANAGER_SERVICE_CLASS =
364             "com.android.server.accessibility.AccessibilityManagerService$Lifecycle";
365     private static final String ADB_SERVICE_CLASS =
366             "com.android.server.adb.AdbService$Lifecycle";
367     private static final String SPEECH_RECOGNITION_MANAGER_SERVICE_CLASS =
368             "com.android.server.speech.SpeechRecognitionManagerService";
369     private static final String WALLPAPER_EFFECTS_GENERATION_MANAGER_SERVICE_CLASS =
370             "com.android.server.wallpapereffectsgeneration.WallpaperEffectsGenerationManagerService";
371     private static final String APP_PREDICTION_MANAGER_SERVICE_CLASS =
372             "com.android.server.appprediction.AppPredictionManagerService";
373     private static final String CONTENT_SUGGESTIONS_SERVICE_CLASS =
374             "com.android.server.contentsuggestions.ContentSuggestionsManagerService";
375     private static final String SEARCH_UI_MANAGER_SERVICE_CLASS =
376             "com.android.server.searchui.SearchUiManagerService";
377     private static final String SMARTSPACE_MANAGER_SERVICE_CLASS =
378             "com.android.server.smartspace.SmartspaceManagerService";
379     private static final String DEVICE_IDLE_CONTROLLER_CLASS =
380             "com.android.server.DeviceIdleController";
381     private static final String BLOB_STORE_MANAGER_SERVICE_CLASS =
382             "com.android.server.blob.BlobStoreManagerService";
383     private static final String APPSEARCH_MODULE_LIFECYCLE_CLASS =
384             "com.android.server.appsearch.AppSearchModule$Lifecycle";
385     private static final String ISOLATED_COMPILATION_SERVICE_CLASS =
386             "com.android.server.compos.IsolatedCompilationService";
387     private static final String ROLLBACK_MANAGER_SERVICE_CLASS =
388             "com.android.server.rollback.RollbackManagerService";
389     private static final String ALARM_MANAGER_SERVICE_CLASS =
390             "com.android.server.alarm.AlarmManagerService";
391     private static final String MEDIA_SESSION_SERVICE_CLASS =
392             "com.android.server.media.MediaSessionService";
393     private static final String MEDIA_RESOURCE_MONITOR_SERVICE_CLASS =
394             "com.android.server.media.MediaResourceMonitorService";
395     private static final String CONNECTIVITY_SERVICE_INITIALIZER_CLASS =
396             "com.android.server.ConnectivityServiceInitializer";
397     private static final String NETWORK_STATS_SERVICE_INITIALIZER_CLASS =
398             "com.android.server.NetworkStatsServiceInitializer";
399     private static final String IP_CONNECTIVITY_METRICS_CLASS =
400             "com.android.server.connectivity.IpConnectivityMetrics";
401     private static final String MEDIA_COMMUNICATION_SERVICE_CLASS =
402             "com.android.server.media.MediaCommunicationService";
403     private static final String APP_COMPAT_OVERRIDES_SERVICE_CLASS =
404             "com.android.server.compat.overrides.AppCompatOverridesService$Lifecycle";
405 
406     private static final String ROLE_SERVICE_CLASS = "com.android.role.RoleService";
407     private static final String GAME_MANAGER_SERVICE_CLASS =
408             "com.android.server.app.GameManagerService$Lifecycle";
409     private static final String UWB_APEX_SERVICE_JAR_PATH =
410             "/apex/com.android.uwb/javalib/service-uwb.jar";
411     private static final String UWB_SERVICE_CLASS = "com.android.server.uwb.UwbService";
412     private static final String BLUETOOTH_APEX_SERVICE_JAR_PATH =
413             "/apex/com.android.btservices/javalib/service-bluetooth.jar";
414     private static final String BLUETOOTH_SERVICE_CLASS =
415             "com.android.server.bluetooth.BluetoothService";
416     private static final String SAFETY_CENTER_SERVICE_CLASS =
417             "com.android.safetycenter.SafetyCenterService";
418 
419     private static final String SDK_SANDBOX_MANAGER_SERVICE_CLASS =
420             "com.android.server.sdksandbox.SdkSandboxManagerService$Lifecycle";
421     private static final String AD_SERVICES_MANAGER_SERVICE_CLASS =
422             "com.android.server.adservices.AdServicesManagerService$Lifecycle";
423 
424     private static final String TETHERING_CONNECTOR_CLASS = "android.net.ITetheringConnector";
425 
426     private static final String PERSISTENT_DATA_BLOCK_PROP = "ro.frp.pst";
427 
428     private static final String UNCRYPT_PACKAGE_FILE = "/cache/recovery/uncrypt_file";
429     private static final String BLOCK_MAP_FILE = "/cache/recovery/block.map";
430 
431     // maximum number of binder threads used for system_server
432     // will be higher than the system default
433     private static final int sMaxBinderThreads = 31;
434 
435     /**
436      * Default theme used by the system context. This is used to style system-provided dialogs, such
437      * as the Power Off dialog, and other visual content.
438      */
439     private static final int DEFAULT_SYSTEM_THEME =
440             com.android.internal.R.style.Theme_DeviceDefault_System;
441 
442     private final int mFactoryTestMode;
443     private Timer mProfilerSnapshotTimer;
444 
445     private Context mSystemContext;
446     private SystemServiceManager mSystemServiceManager;
447 
448     // TODO: remove all of these references by improving dependency resolution and boot phases
449     private PowerManagerService mPowerManagerService;
450     private ActivityManagerService mActivityManagerService;
451     private WindowManagerGlobalLock mWindowManagerGlobalLock;
452     private WebViewUpdateService mWebViewUpdateService;
453     private DisplayManagerService mDisplayManagerService;
454     private PackageManagerService mPackageManagerService;
455     private PackageManager mPackageManager;
456     private ContentResolver mContentResolver;
457     private EntropyMixer mEntropyMixer;
458     private DataLoaderManagerService mDataLoaderManagerService;
459     private long mIncrementalServiceHandle = 0;
460 
461     private boolean mOnlyCore;
462     private boolean mFirstBoot;
463     private final int mStartCount;
464     private final boolean mRuntimeRestart;
465     private final long mRuntimeStartElapsedTime;
466     private final long mRuntimeStartUptime;
467 
468     private static final String START_HIDL_SERVICES = "StartHidlServices";
469     private static final String START_BLOB_STORE_SERVICE = "startBlobStoreManagerService";
470 
471     private static final String SYSPROP_START_COUNT = "sys.system_server.start_count";
472     private static final String SYSPROP_START_ELAPSED = "sys.system_server.start_elapsed";
473     private static final String SYSPROP_START_UPTIME = "sys.system_server.start_uptime";
474 
475     private Future<?> mZygotePreload;
476 
477     private final SystemServerDumper mDumper = new SystemServerDumper();
478 
479     /**
480      * The pending WTF to be logged into dropbox.
481      */
482     private static LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> sPendingWtfs;
483 
484     /** Start the IStats services. This is a blocking call and can take time. */
startIStatsService()485     private static native void startIStatsService();
486 
487     /**
488      * Start the memtrack proxy service.
489      */
startMemtrackProxyService()490     private static native void startMemtrackProxyService();
491 
492     /**
493      * Start all HIDL services that are run inside the system server. This may take some time.
494      */
startHidlServices()495     private static native void startHidlServices();
496 
497     /**
498      * Mark this process' heap as profileable. Only for debug builds.
499      */
initZygoteChildHeapProfiling()500     private static native void initZygoteChildHeapProfiling();
501 
502     private static final String SYSPROP_FDTRACK_ENABLE_THRESHOLD =
503             "persist.sys.debug.fdtrack_enable_threshold";
504     private static final String SYSPROP_FDTRACK_ABORT_THRESHOLD =
505             "persist.sys.debug.fdtrack_abort_threshold";
506     private static final String SYSPROP_FDTRACK_INTERVAL =
507             "persist.sys.debug.fdtrack_interval";
508 
getMaxFd()509     private static int getMaxFd() {
510         FileDescriptor fd = null;
511         try {
512             fd = Os.open("/dev/null", O_RDONLY | O_CLOEXEC, 0);
513             return fd.getInt$();
514         } catch (ErrnoException ex) {
515             Slog.e("System", "Failed to get maximum fd: " + ex);
516         } finally {
517             if (fd != null) {
518                 try {
519                     Os.close(fd);
520                 } catch (ErrnoException ex) {
521                     // If Os.close threw, something went horribly wrong.
522                     throw new RuntimeException(ex);
523                 }
524             }
525         }
526 
527         return Integer.MAX_VALUE;
528     }
529 
fdtrackAbort()530     private static native void fdtrackAbort();
531 
532     private static final File HEAP_DUMP_PATH = new File("/data/system/heapdump/");
533     private static final int MAX_HEAP_DUMPS = 2;
534 
535     /**
536      * Dump system_server's heap.
537      *
538      * For privacy reasons, these aren't automatically pulled into bugreports:
539      * they must be manually pulled by the user.
540      */
dumpHprof()541     private static void dumpHprof() {
542         // hprof dumps are rather large, so ensure we don't fill the disk by generating
543         // hundreds of these that will live forever.
544         TreeSet<File> existingTombstones = new TreeSet<>();
545         for (File file : HEAP_DUMP_PATH.listFiles()) {
546             if (!file.isFile()) {
547                 continue;
548             }
549             if (!file.getName().startsWith("fdtrack-")) {
550                 continue;
551             }
552             existingTombstones.add(file);
553         }
554         if (existingTombstones.size() >= MAX_HEAP_DUMPS) {
555             for (int i = 0; i < MAX_HEAP_DUMPS - 1; ++i) {
556                 // Leave the newest `MAX_HEAP_DUMPS - 1` tombstones in place.
557                 existingTombstones.pollLast();
558             }
559             for (File file : existingTombstones) {
560                 if (!file.delete()) {
561                     Slog.w("System", "Failed to clean up hprof " + file);
562                 }
563             }
564         }
565 
566         try {
567             String date = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
568             String filename = "/data/system/heapdump/fdtrack-" + date + ".hprof";
569             Debug.dumpHprofData(filename);
570         } catch (IOException ex) {
571             Slog.e("System", "Failed to dump fdtrack hprof", ex);
572         }
573     }
574 
575     /**
576      * Spawn a thread that monitors for fd leaks.
577      */
spawnFdLeakCheckThread()578     private static void spawnFdLeakCheckThread() {
579         final int enableThreshold = SystemProperties.getInt(SYSPROP_FDTRACK_ENABLE_THRESHOLD, 1024);
580         final int abortThreshold = SystemProperties.getInt(SYSPROP_FDTRACK_ABORT_THRESHOLD, 2048);
581         final int checkInterval = SystemProperties.getInt(SYSPROP_FDTRACK_INTERVAL, 120);
582 
583         new Thread(() -> {
584             boolean enabled = false;
585             long nextWrite = 0;
586 
587             while (true) {
588                 int maxFd = getMaxFd();
589                 if (maxFd > enableThreshold) {
590                     // Do a manual GC to clean up fds that are hanging around as garbage.
591                     System.gc();
592                     System.runFinalization();
593                     maxFd = getMaxFd();
594                 }
595 
596                 if (maxFd > enableThreshold && !enabled) {
597                     Slog.i("System", "fdtrack enable threshold reached, enabling");
598                     FrameworkStatsLog.write(FrameworkStatsLog.FDTRACK_EVENT_OCCURRED,
599                             FrameworkStatsLog.FDTRACK_EVENT_OCCURRED__EVENT__ENABLED,
600                             maxFd);
601 
602                     System.loadLibrary("fdtrack");
603                     enabled = true;
604                 } else if (maxFd > abortThreshold) {
605                     Slog.i("System", "fdtrack abort threshold reached, dumping and aborting");
606                     FrameworkStatsLog.write(FrameworkStatsLog.FDTRACK_EVENT_OCCURRED,
607                             FrameworkStatsLog.FDTRACK_EVENT_OCCURRED__EVENT__ABORTING,
608                             maxFd);
609 
610                     dumpHprof();
611                     fdtrackAbort();
612                 } else {
613                     // Limit this to once per hour.
614                     long now = SystemClock.elapsedRealtime();
615                     if (now > nextWrite) {
616                         nextWrite = now + 60 * 60 * 1000;
617                         FrameworkStatsLog.write(FrameworkStatsLog.FDTRACK_EVENT_OCCURRED,
618                                 enabled ? FrameworkStatsLog.FDTRACK_EVENT_OCCURRED__EVENT__ENABLED
619                                         : FrameworkStatsLog.FDTRACK_EVENT_OCCURRED__EVENT__DISABLED,
620                                 maxFd);
621                     }
622                 }
623 
624                 try {
625                     Thread.sleep(checkInterval * 1000);
626                 } catch (InterruptedException ex) {
627                     continue;
628                 }
629             }
630         }).start();
631     }
632 
633     /**
634      * Start native Incremental Service and get its handle.
635      */
startIncrementalService()636     private static native long startIncrementalService();
637 
638     /**
639      * Inform Incremental Service that system is ready.
640      */
setIncrementalServiceSystemReady(long incrementalServiceHandle)641     private static native void setIncrementalServiceSystemReady(long incrementalServiceHandle);
642 
643     /**
644      * The main entry point from zygote.
645      */
main(String[] args)646     public static void main(String[] args) {
647         new SystemServer().run();
648     }
649 
SystemServer()650     public SystemServer() {
651         // Check for factory test mode.
652         mFactoryTestMode = FactoryTest.getMode();
653 
654         // Record process start information.
655         // Note SYSPROP_START_COUNT will increment by *2* on a FDE device when it fully boots;
656         // one for the password screen, second for the actual boot.
657         mStartCount = SystemProperties.getInt(SYSPROP_START_COUNT, 0) + 1;
658         mRuntimeStartElapsedTime = SystemClock.elapsedRealtime();
659         mRuntimeStartUptime = SystemClock.uptimeMillis();
660         Process.setStartTimes(mRuntimeStartElapsedTime, mRuntimeStartUptime,
661                 mRuntimeStartElapsedTime, mRuntimeStartUptime);
662 
663         // Remember if it's runtime restart(when sys.boot_completed is already set) or reboot
664         // We don't use "mStartCount > 1" here because it'll be wrong on a FDE device.
665         // TODO: mRuntimeRestart will *not* be set to true if the proccess crashes before
666         // sys.boot_completed is set. Fix it.
667         mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));
668     }
669 
670     @Override
getDumpableName()671     public String getDumpableName() {
672         return SystemServer.class.getSimpleName();
673     }
674 
675     @Override
dump(PrintWriter pw, String[] args)676     public void dump(PrintWriter pw, String[] args) {
677         pw.printf("Runtime restart: %b\n", mRuntimeRestart);
678         pw.printf("Start count: %d\n", mStartCount);
679         pw.print("Runtime start-up time: ");
680         TimeUtils.formatDuration(mRuntimeStartUptime, pw); pw.println();
681         pw.print("Runtime start-elapsed time: ");
682         TimeUtils.formatDuration(mRuntimeStartElapsedTime, pw); pw.println();
683     }
684 
685     /**
686      * Service used to dump {@link SystemServer} state that is not associated with any service.
687      *
688      * <p>To dump all services:
689      *
690      * <pre><code>adb shell dumpsys system_server_dumper</code></pre>
691      *
692      * <p>To get a list of all services:
693      *
694      * <pre><code>adb shell dumpsys system_server_dumper --list</code></pre>
695      *
696      * <p>To dump a specific service (use {@code --list} above to get service names):
697      *
698      * <pre><code>adb shell dumpsys system_server_dumper --name NAME</code></pre>
699      */
700     private final class SystemServerDumper extends Binder {
701 
702         @GuardedBy("mDumpables")
703         private final ArrayMap<String, Dumpable> mDumpables = new ArrayMap<>(4);
704 
705         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)706         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
707             final boolean hasArgs = args != null && args.length > 0;
708 
709             synchronized (mDumpables) {
710                 if (hasArgs && "--list".equals(args[0])) {
711                     final int dumpablesSize = mDumpables.size();
712                     for (int i = 0; i < dumpablesSize; i++) {
713                         pw.println(mDumpables.keyAt(i));
714                     }
715                     return;
716                 }
717 
718                 if (hasArgs && "--name".equals(args[0])) {
719                     if (args.length < 2) {
720                         pw.println("Must pass at least one argument to --name");
721                         return;
722                     }
723                     final String name = args[1];
724                     final Dumpable dumpable = mDumpables.get(name);
725                     if (dumpable == null) {
726                         pw.printf("No dummpable named %s\n", name);
727                         return;
728                     }
729 
730                     try (IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
731                         // Strip --name DUMPABLE from args
732                         final String[] actualArgs = Arrays.copyOfRange(args, 2, args.length);
733                         dumpable.dump(ipw, actualArgs);
734                     }
735                     return;
736                 }
737 
738                 final int dumpablesSize = mDumpables.size();
739                 try (IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
740                     for (int i = 0; i < dumpablesSize; i++) {
741                         final Dumpable dumpable = mDumpables.valueAt(i);
742                         ipw.printf("%s:\n", dumpable.getDumpableName());
743                         ipw.increaseIndent();
744                         dumpable.dump(ipw, args);
745                         ipw.decreaseIndent();
746                         ipw.println();
747                     }
748                 }
749             }
750         }
751 
addDumpable(@onNull Dumpable dumpable)752         private void addDumpable(@NonNull Dumpable dumpable) {
753             synchronized (mDumpables) {
754                 mDumpables.put(dumpable.getDumpableName(), dumpable);
755             }
756         }
757     }
758 
run()759     private void run() {
760         TimingsTraceAndSlog t = new TimingsTraceAndSlog();
761         try {
762             t.traceBegin("InitBeforeStartServices");
763 
764             // Record the process start information in sys props.
765             SystemProperties.set(SYSPROP_START_COUNT, String.valueOf(mStartCount));
766             SystemProperties.set(SYSPROP_START_ELAPSED, String.valueOf(mRuntimeStartElapsedTime));
767             SystemProperties.set(SYSPROP_START_UPTIME, String.valueOf(mRuntimeStartUptime));
768 
769             EventLog.writeEvent(EventLogTags.SYSTEM_SERVER_START,
770                     mStartCount, mRuntimeStartUptime, mRuntimeStartElapsedTime);
771 
772             //
773             // Default the timezone property to GMT if not set.
774             //
775             String timezoneProperty = SystemProperties.get("persist.sys.timezone");
776             if (!isValidTimeZoneId(timezoneProperty)) {
777                 Slog.w(TAG, "persist.sys.timezone is not valid (" + timezoneProperty
778                         + "); setting to GMT.");
779                 SystemProperties.set("persist.sys.timezone", "GMT");
780             }
781 
782             // If the system has "persist.sys.language" and friends set, replace them with
783             // "persist.sys.locale". Note that the default locale at this point is calculated
784             // using the "-Duser.locale" command line flag. That flag is usually populated by
785             // AndroidRuntime using the same set of system properties, but only the system_server
786             // and system apps are allowed to set them.
787             //
788             // NOTE: Most changes made here will need an equivalent change to
789             // core/jni/AndroidRuntime.cpp
790             if (!SystemProperties.get("persist.sys.language").isEmpty()) {
791                 final String languageTag = Locale.getDefault().toLanguageTag();
792 
793                 SystemProperties.set("persist.sys.locale", languageTag);
794                 SystemProperties.set("persist.sys.language", "");
795                 SystemProperties.set("persist.sys.country", "");
796                 SystemProperties.set("persist.sys.localevar", "");
797             }
798 
799             // The system server should never make non-oneway calls
800             Binder.setWarnOnBlocking(true);
801             // The system server should always load safe labels
802             PackageItemInfo.forceSafeLabels();
803 
804             // Default to FULL within the system server.
805             SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;
806 
807             // Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
808             SQLiteCompatibilityWalFlags.init(null);
809 
810             // Here we go!
811             Slog.i(TAG, "Entered the Android system server!");
812             final long uptimeMillis = SystemClock.elapsedRealtime();
813             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
814             if (!mRuntimeRestart) {
815                 FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
816                         FrameworkStatsLog
817                                 .BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SYSTEM_SERVER_INIT_START,
818                         uptimeMillis);
819             }
820 
821             // In case the runtime switched since last boot (such as when
822             // the old runtime was removed in an OTA), set the system
823             // property so that it is in sync. We can't do this in
824             // libnativehelper's JniInvocation::Init code where we already
825             // had to fallback to a different runtime because it is
826             // running as root and we need to be the system user to set
827             // the property. http://b/11463182
828             SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
829 
830             // Mmmmmm... more memory!
831             VMRuntime.getRuntime().clearGrowthLimit();
832 
833             // Some devices rely on runtime fingerprint generation, so make sure
834             // we've defined it before booting further.
835             Build.ensureFingerprintProperty();
836 
837             // Within the system server, it is an error to access Environment paths without
838             // explicitly specifying a user.
839             Environment.setUserRequired(true);
840 
841             // Within the system server, any incoming Bundles should be defused
842             // to avoid throwing BadParcelableException.
843             BaseBundle.setShouldDefuse(true);
844 
845             // Within the system server, when parceling exceptions, include the stack trace
846             Parcel.setStackTraceParceling(true);
847 
848             // Ensure binder calls into the system always run at foreground priority.
849             BinderInternal.disableBackgroundScheduling(true);
850 
851             // Increase the number of binder threads in system_server
852             BinderInternal.setMaxThreads(sMaxBinderThreads);
853 
854             // Prepare the main looper thread (this thread).
855             android.os.Process.setThreadPriority(
856                     android.os.Process.THREAD_PRIORITY_FOREGROUND);
857             android.os.Process.setCanSelfBackground(false);
858             Looper.prepareMainLooper();
859             Looper.getMainLooper().setSlowLogThresholdMs(
860                     SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
861 
862             SystemServiceRegistry.sEnableServiceNotFoundWtf = true;
863 
864             // Initialize native services.
865             System.loadLibrary("android_servers");
866 
867             // Allow heap / perf profiling.
868             initZygoteChildHeapProfiling();
869 
870             // Debug builds - spawn a thread to monitor for fd leaks.
871             if (Build.IS_DEBUGGABLE) {
872                 spawnFdLeakCheckThread();
873             }
874 
875             // Check whether we failed to shut down last time we tried.
876             // This call may not return.
877             performPendingShutdown();
878 
879             // Initialize the system context.
880             createSystemContext();
881 
882             // Call per-process mainline module initialization.
883             ActivityThread.initializeMainlineModules();
884 
885             // Sets the dumper service
886             ServiceManager.addService("system_server_dumper", mDumper);
887             mDumper.addDumpable(this);
888 
889             // Create the system service manager.
890             mSystemServiceManager = new SystemServiceManager(mSystemContext);
891             mSystemServiceManager.setStartInfo(mRuntimeRestart,
892                     mRuntimeStartElapsedTime, mRuntimeStartUptime);
893             mDumper.addDumpable(mSystemServiceManager);
894 
895             LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
896             // Prepare the thread pool for init tasks that can be parallelized
897             SystemServerInitThreadPool tp = SystemServerInitThreadPool.start();
898             mDumper.addDumpable(tp);
899 
900             // Load preinstalled system fonts for system server, so that WindowManagerService, etc
901             // can start using Typeface. Note that fonts are required not only for text rendering,
902             // but also for some text operations (e.g. TextUtils.makeSafeForPresentation()).
903             if (Typeface.ENABLE_LAZY_TYPEFACE_INITIALIZATION) {
904                 Typeface.loadPreinstalledSystemFontMap();
905             }
906 
907             // Attach JVMTI agent if this is a debuggable build and the system property is set.
908             if (Build.IS_DEBUGGABLE) {
909                 // Property is of the form "library_path=parameters".
910                 String jvmtiAgent = SystemProperties.get("persist.sys.dalvik.jvmtiagent");
911                 if (!jvmtiAgent.isEmpty()) {
912                     int equalIndex = jvmtiAgent.indexOf('=');
913                     String libraryPath = jvmtiAgent.substring(0, equalIndex);
914                     String parameterList =
915                             jvmtiAgent.substring(equalIndex + 1, jvmtiAgent.length());
916                     // Attach the agent.
917                     try {
918                         Debug.attachJvmtiAgent(libraryPath, parameterList, null);
919                     } catch (Exception e) {
920                         Slog.e("System", "*************************************************");
921                         Slog.e("System", "********** Failed to load jvmti plugin: " + jvmtiAgent);
922                     }
923                 }
924             }
925         } finally {
926             t.traceEnd();  // InitBeforeStartServices
927         }
928 
929         // Setup the default WTF handler
930         RuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf);
931 
932         // Start services.
933         try {
934             t.traceBegin("StartServices");
935             startBootstrapServices(t);
936             startCoreServices(t);
937             startOtherServices(t);
938             startApexServices(t);
939         } catch (Throwable ex) {
940             Slog.e("System", "******************************************");
941             Slog.e("System", "************ Failure starting system services", ex);
942             throw ex;
943         } finally {
944             t.traceEnd(); // StartServices
945         }
946 
947         StrictMode.initVmDefaults(null);
948 
949         if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
950             final long uptimeMillis = SystemClock.elapsedRealtime();
951             FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
952                     FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SYSTEM_SERVER_READY,
953                     uptimeMillis);
954             final long maxUptimeMillis = 60 * 1000;
955             if (uptimeMillis > maxUptimeMillis) {
956                 Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
957                         "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
958             }
959         }
960 
961         // Loop forever.
962         Looper.loop();
963         throw new RuntimeException("Main thread loop unexpectedly exited");
964     }
965 
isValidTimeZoneId(String timezoneProperty)966     private static boolean isValidTimeZoneId(String timezoneProperty) {
967         return timezoneProperty != null
968                 && !timezoneProperty.isEmpty()
969                 && ZoneInfoDb.getInstance().hasTimeZone(timezoneProperty);
970     }
971 
isFirstBootOrUpgrade()972     private boolean isFirstBootOrUpgrade() {
973         return mPackageManagerService.isFirstBoot() || mPackageManagerService.isDeviceUpgrading();
974     }
975 
reportWtf(String msg, Throwable e)976     private void reportWtf(String msg, Throwable e) {
977         Slog.w(TAG, "***********************************************");
978         Slog.wtf(TAG, "BOOT FAILURE " + msg, e);
979     }
980 
performPendingShutdown()981     private void performPendingShutdown() {
982         final String shutdownAction = SystemProperties.get(
983                 ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
984         if (shutdownAction != null && shutdownAction.length() > 0) {
985             boolean reboot = (shutdownAction.charAt(0) == '1');
986 
987             final String reason;
988             if (shutdownAction.length() > 1) {
989                 reason = shutdownAction.substring(1, shutdownAction.length());
990             } else {
991                 reason = null;
992             }
993 
994             // If it's a pending reboot into recovery to apply an update,
995             // always make sure uncrypt gets executed properly when needed.
996             // If '/cache/recovery/block.map' hasn't been created, stop the
997             // reboot which will fail for sure, and get a chance to capture a
998             // bugreport when that's still feasible. (Bug: 26444951)
999             if (reason != null && reason.startsWith(PowerManager.REBOOT_RECOVERY_UPDATE)) {
1000                 File packageFile = new File(UNCRYPT_PACKAGE_FILE);
1001                 if (packageFile.exists()) {
1002                     String filename = null;
1003                     try {
1004                         filename = FileUtils.readTextFile(packageFile, 0, null);
1005                     } catch (IOException e) {
1006                         Slog.e(TAG, "Error reading uncrypt package file", e);
1007                     }
1008 
1009                     if (filename != null && filename.startsWith("/data")) {
1010                         if (!new File(BLOCK_MAP_FILE).exists()) {
1011                             Slog.e(TAG, "Can't find block map file, uncrypt failed or " +
1012                                     "unexpected runtime restart?");
1013                             return;
1014                         }
1015                     }
1016                 }
1017             }
1018             Runnable runnable = new Runnable() {
1019                 @Override
1020                 public void run() {
1021                     synchronized (this) {
1022                         ShutdownThread.rebootOrShutdown(null, reboot, reason);
1023                     }
1024                 }
1025             };
1026 
1027             // ShutdownThread must run on a looper capable of displaying the UI.
1028             Message msg = Message.obtain(UiThread.getHandler(), runnable);
1029             msg.setAsynchronous(true);
1030             UiThread.getHandler().sendMessage(msg);
1031 
1032         }
1033     }
1034 
createSystemContext()1035     private void createSystemContext() {
1036         ActivityThread activityThread = ActivityThread.systemMain();
1037         mSystemContext = activityThread.getSystemContext();
1038         mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
1039 
1040         final Context systemUiContext = activityThread.getSystemUiContext();
1041         systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
1042     }
1043 
1044     /**
1045      * Starts the small tangle of critical services that are needed to get the system off the
1046      * ground.  These services have complex mutual dependencies which is why we initialize them all
1047      * in one place here.  Unless your service is also entwined in these dependencies, it should be
1048      * initialized in one of the other functions.
1049      */
startBootstrapServices(@onNull TimingsTraceAndSlog t)1050     private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
1051         t.traceBegin("startBootstrapServices");
1052 
1053         // Start the watchdog as early as possible so we can crash the system server
1054         // if we deadlock during early boot
1055         t.traceBegin("StartWatchdog");
1056         final Watchdog watchdog = Watchdog.getInstance();
1057         watchdog.start();
1058         mDumper.addDumpable(watchdog);
1059         t.traceEnd();
1060 
1061         Slog.i(TAG, "Reading configuration...");
1062         final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
1063         t.traceBegin(TAG_SYSTEM_CONFIG);
1064         SystemServerInitThreadPool.submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
1065         t.traceEnd();
1066 
1067         // Platform compat service is used by ActivityManagerService, PackageManagerService, and
1068         // possibly others in the future. b/135010838.
1069         t.traceBegin("PlatformCompat");
1070         PlatformCompat platformCompat = new PlatformCompat(mSystemContext);
1071         ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE, platformCompat);
1072         ServiceManager.addService(Context.PLATFORM_COMPAT_NATIVE_SERVICE,
1073                 new PlatformCompatNative(platformCompat));
1074         AppCompatCallbacks.install(new long[0]);
1075         t.traceEnd();
1076 
1077         // FileIntegrityService responds to requests from apps and the system. It needs to run after
1078         // the source (i.e. keystore) is ready, and before the apps (or the first customer in the
1079         // system) run.
1080         t.traceBegin("StartFileIntegrityService");
1081         mSystemServiceManager.startService(FileIntegrityService.class);
1082         t.traceEnd();
1083 
1084         // Wait for installd to finish starting up so that it has a chance to
1085         // create critical directories such as /data/user with the appropriate
1086         // permissions.  We need this to complete before we initialize other services.
1087         t.traceBegin("StartInstaller");
1088         Installer installer = mSystemServiceManager.startService(Installer.class);
1089         t.traceEnd();
1090 
1091         // In some cases after launching an app we need to access device identifiers,
1092         // therefore register the device identifier policy before the activity manager.
1093         t.traceBegin("DeviceIdentifiersPolicyService");
1094         mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
1095         t.traceEnd();
1096 
1097         // Uri Grants Manager.
1098         t.traceBegin("UriGrantsManagerService");
1099         mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);
1100         t.traceEnd();
1101 
1102         t.traceBegin("StartPowerStatsService");
1103         // Tracks rail data to be used for power statistics.
1104         mSystemServiceManager.startService(PowerStatsService.class);
1105         t.traceEnd();
1106 
1107         t.traceBegin("StartIStatsService");
1108         startIStatsService();
1109         t.traceEnd();
1110 
1111         // Start MemtrackProxyService before ActivityManager, so that early calls
1112         // to Memtrack::getMemory() don't fail.
1113         t.traceBegin("MemtrackProxyService");
1114         startMemtrackProxyService();
1115         t.traceEnd();
1116 
1117         // Activity manager runs the show.
1118         t.traceBegin("StartActivityManager");
1119         // TODO: Might need to move after migration to WM.
1120         ActivityTaskManagerService atm = mSystemServiceManager.startService(
1121                 ActivityTaskManagerService.Lifecycle.class).getService();
1122         mActivityManagerService = ActivityManagerService.Lifecycle.startService(
1123                 mSystemServiceManager, atm);
1124         mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
1125         mActivityManagerService.setInstaller(installer);
1126         mWindowManagerGlobalLock = atm.getGlobalLock();
1127         t.traceEnd();
1128 
1129         // Data loader manager service needs to be started before package manager
1130         t.traceBegin("StartDataLoaderManagerService");
1131         mDataLoaderManagerService = mSystemServiceManager.startService(
1132                 DataLoaderManagerService.class);
1133         t.traceEnd();
1134 
1135         // Incremental service needs to be started before package manager
1136         t.traceBegin("StartIncrementalService");
1137         mIncrementalServiceHandle = startIncrementalService();
1138         t.traceEnd();
1139 
1140         // Power manager needs to be started early because other services need it.
1141         // Native daemons may be watching for it to be registered so it must be ready
1142         // to handle incoming binder calls immediately (including being able to verify
1143         // the permissions for those calls).
1144         t.traceBegin("StartPowerManager");
1145         mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
1146         t.traceEnd();
1147 
1148         t.traceBegin("StartThermalManager");
1149         mSystemServiceManager.startService(ThermalManagerService.class);
1150         t.traceEnd();
1151 
1152         t.traceBegin("StartHintManager");
1153         mSystemServiceManager.startService(HintManagerService.class);
1154         t.traceEnd();
1155 
1156         // Now that the power manager has been started, let the activity manager
1157         // initialize power management features.
1158         t.traceBegin("InitPowerManagement");
1159         mActivityManagerService.initPowerManagement();
1160         t.traceEnd();
1161 
1162         // Bring up recovery system in case a rescue party needs a reboot
1163         t.traceBegin("StartRecoverySystemService");
1164         mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class);
1165         t.traceEnd();
1166 
1167         // Now that we have the bare essentials of the OS up and running, take
1168         // note that we just booted, which might send out a rescue party if
1169         // we're stuck in a runtime restart loop.
1170         RescueParty.registerHealthObserver(mSystemContext);
1171         PackageWatchdog.getInstance(mSystemContext).noteBoot();
1172 
1173         // Manages LEDs and display backlight so we need it to bring up the display.
1174         t.traceBegin("StartLightsService");
1175         mSystemServiceManager.startService(LightsService.class);
1176         t.traceEnd();
1177 
1178         t.traceBegin("StartDisplayOffloadService");
1179         // Package manager isn't started yet; need to use SysProp not hardware feature
1180         if (SystemProperties.getBoolean("config.enable_display_offload", false)) {
1181             mSystemServiceManager.startService(WEAR_DISPLAYOFFLOAD_SERVICE_CLASS);
1182         }
1183         t.traceEnd();
1184 
1185         t.traceBegin("StartSidekickService");
1186         // Package manager isn't started yet; need to use SysProp not hardware feature
1187         if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
1188             mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
1189         }
1190         t.traceEnd();
1191 
1192         // Display manager is needed to provide display metrics before package manager
1193         // starts up.
1194         t.traceBegin("StartDisplayManager");
1195         mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
1196         t.traceEnd();
1197 
1198         // We need the default display before we can initialize the package manager.
1199         t.traceBegin("WaitForDisplay");
1200         mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
1201         t.traceEnd();
1202 
1203         // Only run "core" apps if we're encrypting the device.
1204         String cryptState = VoldProperties.decrypt().orElse("");
1205         if (ENCRYPTING_STATE.equals(cryptState)) {
1206             Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
1207             mOnlyCore = true;
1208         } else if (ENCRYPTED_STATE.equals(cryptState)) {
1209             Slog.w(TAG, "Device encrypted - only parsing core apps");
1210             mOnlyCore = true;
1211         }
1212 
1213         // Start the package manager.
1214         if (!mRuntimeRestart) {
1215             FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
1216                     FrameworkStatsLog
1217                             .BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__PACKAGE_MANAGER_INIT_START,
1218                     SystemClock.elapsedRealtime());
1219         }
1220 
1221         t.traceBegin("StartDomainVerificationService");
1222         DomainVerificationService domainVerificationService = new DomainVerificationService(
1223                 mSystemContext, SystemConfig.getInstance(), platformCompat);
1224         mSystemServiceManager.startService(domainVerificationService);
1225         t.traceEnd();
1226 
1227         IPackageManager iPackageManager;
1228         t.traceBegin("StartPackageManagerService");
1229         try {
1230             Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
1231             Pair<PackageManagerService, IPackageManager> pmsPair = PackageManagerService.main(
1232                     mSystemContext, installer, domainVerificationService,
1233                     mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
1234             mPackageManagerService = pmsPair.first;
1235             iPackageManager = pmsPair.second;
1236         } finally {
1237             Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
1238         }
1239 
1240         // Now that the package manager has started, register the dex load reporter to capture any
1241         // dex files loaded by system server.
1242         // These dex files will be optimized by the BackgroundDexOptService.
1243         SystemServerDexLoadReporter.configureSystemServerDexReporter(iPackageManager);
1244 
1245         mFirstBoot = mPackageManagerService.isFirstBoot();
1246         mPackageManager = mSystemContext.getPackageManager();
1247         t.traceEnd();
1248         if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
1249             FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
1250                     FrameworkStatsLog
1251                             .BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__PACKAGE_MANAGER_INIT_READY,
1252                     SystemClock.elapsedRealtime());
1253         }
1254         // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
1255         // A/B artifacts after boot, before anything else might touch/need them.
1256         // Note: this isn't needed during decryption (we don't have /data anyways).
1257         if (!mOnlyCore) {
1258             boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
1259                     false);
1260             if (!disableOtaDexopt) {
1261                 t.traceBegin("StartOtaDexOptService");
1262                 try {
1263                     Watchdog.getInstance().pauseWatchingCurrentThread("moveab");
1264                     OtaDexoptService.main(mSystemContext, mPackageManagerService);
1265                 } catch (Throwable e) {
1266                     reportWtf("starting OtaDexOptService", e);
1267                 } finally {
1268                     Watchdog.getInstance().resumeWatchingCurrentThread("moveab");
1269                     t.traceEnd();
1270                 }
1271             }
1272         }
1273 
1274         t.traceBegin("StartUserManagerService");
1275         mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
1276         t.traceEnd();
1277 
1278         // Initialize attribute cache used to cache resources from packages.
1279         t.traceBegin("InitAttributerCache");
1280         AttributeCache.init(mSystemContext);
1281         t.traceEnd();
1282 
1283         // Set up the Application instance for the system process and get started.
1284         t.traceBegin("SetSystemProcess");
1285         mActivityManagerService.setSystemProcess();
1286         t.traceEnd();
1287 
1288         // The package receiver depends on the activity service in order to get registered.
1289         platformCompat.registerPackageReceiver(mSystemContext);
1290 
1291         // Complete the watchdog setup with an ActivityManager instance and listen for reboots
1292         // Do this only after the ActivityManagerService is properly started as a system process
1293         t.traceBegin("InitWatchdog");
1294         watchdog.init(mSystemContext, mActivityManagerService);
1295         t.traceEnd();
1296 
1297         // DisplayManagerService needs to setup android.display scheduling related policies
1298         // since setSystemProcess() would have overridden policies due to setProcessGroup
1299         mDisplayManagerService.setupSchedulerPolicies();
1300 
1301         // Manages Overlay packages
1302         t.traceBegin("StartOverlayManagerService");
1303         mSystemServiceManager.startService(new OverlayManagerService(mSystemContext));
1304         t.traceEnd();
1305 
1306         // Manages Resources packages
1307         t.traceBegin("StartResourcesManagerService");
1308         ResourcesManagerService resourcesService = new ResourcesManagerService(mSystemContext);
1309         resourcesService.setActivityManagerService(mActivityManagerService);
1310         mSystemServiceManager.startService(resourcesService);
1311         t.traceEnd();
1312 
1313         t.traceBegin("StartSensorPrivacyService");
1314         mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext));
1315         t.traceEnd();
1316 
1317         if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {
1318             // DisplayManager needs the overlay immediately.
1319             mActivityManagerService.updateSystemUiContext();
1320             LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();
1321         }
1322 
1323         // The sensor service needs access to package manager service, app ops
1324         // service, and permissions service, therefore we start it after them.
1325         t.traceBegin("StartSensorService");
1326         mSystemServiceManager.startService(SensorService.class);
1327         t.traceEnd();
1328         t.traceEnd(); // startBootstrapServices
1329     }
1330 
1331     /**
1332      * Starts some essential services that are not tangled up in the bootstrap process.
1333      */
startCoreServices(@onNull TimingsTraceAndSlog t)1334     private void startCoreServices(@NonNull TimingsTraceAndSlog t) {
1335         t.traceBegin("startCoreServices");
1336 
1337         // Service for system config
1338         t.traceBegin("StartSystemConfigService");
1339         mSystemServiceManager.startService(SystemConfigService.class);
1340         t.traceEnd();
1341 
1342         t.traceBegin("StartBatteryService");
1343         // Tracks the battery level.  Requires LightService.
1344         mSystemServiceManager.startService(BatteryService.class);
1345         t.traceEnd();
1346 
1347         // Tracks application usage stats.
1348         t.traceBegin("StartUsageService");
1349         mSystemServiceManager.startService(UsageStatsService.class);
1350         mActivityManagerService.setUsageStatsManager(
1351                 LocalServices.getService(UsageStatsManagerInternal.class));
1352         t.traceEnd();
1353 
1354         // Tracks whether the updatable WebView is in a ready state and watches for update installs.
1355         if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
1356             t.traceBegin("StartWebViewUpdateService");
1357             mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
1358             t.traceEnd();
1359         }
1360 
1361         // Tracks and caches the device state.
1362         t.traceBegin("StartCachedDeviceStateService");
1363         mSystemServiceManager.startService(CachedDeviceStateService.class);
1364         t.traceEnd();
1365 
1366         // Tracks cpu time spent in binder calls
1367         t.traceBegin("StartBinderCallsStatsService");
1368         mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);
1369         t.traceEnd();
1370 
1371         // Tracks time spent in handling messages in handlers.
1372         t.traceBegin("StartLooperStatsService");
1373         mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);
1374         t.traceEnd();
1375 
1376         // Manages apk rollbacks.
1377         t.traceBegin("StartRollbackManagerService");
1378         mSystemServiceManager.startService(ROLLBACK_MANAGER_SERVICE_CLASS);
1379         t.traceEnd();
1380 
1381         // Tracks native tombstones.
1382         t.traceBegin("StartNativeTombstoneManagerService");
1383         mSystemServiceManager.startService(NativeTombstoneManagerService.class);
1384         t.traceEnd();
1385 
1386         // Service to capture bugreports.
1387         t.traceBegin("StartBugreportManagerService");
1388         mSystemServiceManager.startService(BugreportManagerService.class);
1389         t.traceEnd();
1390 
1391         // Serivce for GPU and GPU driver.
1392         t.traceBegin("GpuService");
1393         mSystemServiceManager.startService(GpuService.class);
1394         t.traceEnd();
1395 
1396         t.traceEnd(); // startCoreServices
1397     }
1398 
1399     /**
1400      * Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized.
1401      */
startOtherServices(@onNull TimingsTraceAndSlog t)1402     private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
1403         t.traceBegin("startOtherServices");
1404         mSystemServiceManager.updateOtherServicesStartIndex();
1405 
1406         final Context context = mSystemContext;
1407         DynamicSystemService dynamicSystem = null;
1408         IStorageManager storageManager = null;
1409         NetworkManagementService networkManagement = null;
1410         VpnManagerService vpnManager = null;
1411         VcnManagementService vcnManagement = null;
1412         NetworkPolicyManagerService networkPolicy = null;
1413         WindowManagerService wm = null;
1414         SerialService serial = null;
1415         NetworkTimeUpdateService networkTimeUpdater = null;
1416         InputManagerService inputManager = null;
1417         TelephonyRegistry telephonyRegistry = null;
1418         ConsumerIrService consumerIr = null;
1419         MmsServiceBroker mmsService = null;
1420         HardwarePropertiesManagerService hardwarePropertiesService = null;
1421         PacProxyService pacProxyService = null;
1422 
1423         boolean disableSystemTextClassifier = SystemProperties.getBoolean(
1424                 "config.disable_systemtextclassifier", false);
1425 
1426         boolean disableNetworkTime = SystemProperties.getBoolean("config.disable_networktime",
1427                 false);
1428         boolean disableCameraService = SystemProperties.getBoolean("config.disable_cameraservice",
1429                 false);
1430         boolean enableLeftyService = SystemProperties.getBoolean("config.enable_lefty", false);
1431 
1432         boolean isEmulator = SystemProperties.get("ro.boot.qemu").equals("1");
1433 
1434         boolean isWatch = context.getPackageManager().hasSystemFeature(
1435                 PackageManager.FEATURE_WATCH);
1436 
1437         boolean isArc = context.getPackageManager().hasSystemFeature(
1438                 "org.chromium.arc");
1439 
1440         boolean enableVrService = context.getPackageManager().hasSystemFeature(
1441                 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE);
1442 
1443         // For debugging RescueParty
1444         if (Build.IS_DEBUGGABLE && SystemProperties.getBoolean("debug.crash_system", false)) {
1445             throw new RuntimeException();
1446         }
1447 
1448         try {
1449             final String SECONDARY_ZYGOTE_PRELOAD = "SecondaryZygotePreload";
1450             // We start the preload ~1s before the webview factory preparation, to
1451             // ensure that it completes before the 32 bit relro process is forked
1452             // from the zygote. In the event that it takes too long, the webview
1453             // RELRO process will block, but it will do so without holding any locks.
1454             mZygotePreload = SystemServerInitThreadPool.submit(() -> {
1455                 try {
1456                     Slog.i(TAG, SECONDARY_ZYGOTE_PRELOAD);
1457                     TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
1458                     traceLog.traceBegin(SECONDARY_ZYGOTE_PRELOAD);
1459                     String[] abis32 = Build.SUPPORTED_32_BIT_ABIS;
1460                     if (abis32.length > 0 && !Process.ZYGOTE_PROCESS.preloadDefault(abis32[0])) {
1461                         Slog.e(TAG, "Unable to preload default resources for secondary");
1462                     }
1463                     traceLog.traceEnd();
1464                 } catch (Exception ex) {
1465                     Slog.e(TAG, "Exception preloading default resources", ex);
1466                 }
1467             }, SECONDARY_ZYGOTE_PRELOAD);
1468 
1469             t.traceBegin("StartKeyAttestationApplicationIdProviderService");
1470             ServiceManager.addService("sec_key_att_app_id_provider",
1471                     new KeyAttestationApplicationIdProviderService(context));
1472             t.traceEnd();
1473 
1474             t.traceBegin("StartKeyChainSystemService");
1475             mSystemServiceManager.startService(KeyChainSystemService.class);
1476             t.traceEnd();
1477 
1478             t.traceBegin("StartBinaryTransparencyService");
1479             mSystemServiceManager.startService(BinaryTransparencyService.class);
1480             t.traceEnd();
1481 
1482             t.traceBegin("StartSchedulingPolicyService");
1483             ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
1484             t.traceEnd();
1485 
1486             // TelecomLoader hooks into classes with defined HFP logic,
1487             // so check for either telephony or microphone.
1488             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE)
1489                     || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELECOM)
1490                     || mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
1491                 t.traceBegin("StartTelecomLoaderService");
1492                 mSystemServiceManager.startService(TelecomLoaderService.class);
1493                 t.traceEnd();
1494             }
1495 
1496             t.traceBegin("StartTelephonyRegistry");
1497             telephonyRegistry = new TelephonyRegistry(
1498                     context, new TelephonyRegistry.ConfigurationProvider());
1499             ServiceManager.addService("telephony.registry", telephonyRegistry);
1500             t.traceEnd();
1501 
1502             t.traceBegin("StartEntropyMixer");
1503             mEntropyMixer = new EntropyMixer(context);
1504             t.traceEnd();
1505 
1506             mContentResolver = context.getContentResolver();
1507 
1508             // The AccountManager must come before the ContentService
1509             t.traceBegin("StartAccountManagerService");
1510             mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
1511             t.traceEnd();
1512 
1513             t.traceBegin("StartContentService");
1514             mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);
1515             t.traceEnd();
1516 
1517             t.traceBegin("InstallSystemProviders");
1518             mActivityManagerService.getContentProviderHelper().installSystemProviders();
1519             // Now that SettingsProvider is ready, reactivate SQLiteCompatibilityWalFlags
1520             SQLiteCompatibilityWalFlags.reset();
1521             t.traceEnd();
1522 
1523             t.traceBegin("UpdateWatchdogTimeout");
1524             Watchdog.getInstance().registerSettingsObserver(context);
1525             t.traceEnd();
1526 
1527             // Records errors and logs, for example wtf()
1528             // Currently this service indirectly depends on SettingsProvider so do this after
1529             // InstallSystemProviders.
1530             t.traceBegin("StartDropBoxManager");
1531             mSystemServiceManager.startService(DropBoxManagerService.class);
1532             t.traceEnd();
1533 
1534             // Grants default permissions and defines roles
1535             t.traceBegin("StartRoleManagerService");
1536             LocalManagerRegistry.addManager(RoleServicePlatformHelper.class,
1537                     new RoleServicePlatformHelperImpl(mSystemContext));
1538             mSystemServiceManager.startService(ROLE_SERVICE_CLASS);
1539             t.traceEnd();
1540 
1541             t.traceBegin("StartVibratorManagerService");
1542             mSystemServiceManager.startService(VibratorManagerService.Lifecycle.class);
1543             t.traceEnd();
1544 
1545             t.traceBegin("StartDynamicSystemService");
1546             dynamicSystem = new DynamicSystemService(context);
1547             ServiceManager.addService("dynamic_system", dynamicSystem);
1548             t.traceEnd();
1549 
1550             if (!isWatch) {
1551                 t.traceBegin("StartConsumerIrService");
1552                 consumerIr = new ConsumerIrService(context);
1553                 ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);
1554                 t.traceEnd();
1555             }
1556 
1557             // TODO(aml-jobscheduler): Think about how to do it properly.
1558             t.traceBegin("StartResourceEconomy");
1559             mSystemServiceManager.startService(RESOURCE_ECONOMY_SERVICE_CLASS);
1560             t.traceEnd();
1561 
1562             // TODO(aml-jobscheduler): Think about how to do it properly.
1563             t.traceBegin("StartAlarmManagerService");
1564             mSystemServiceManager.startService(ALARM_MANAGER_SERVICE_CLASS);
1565             t.traceEnd();
1566 
1567             t.traceBegin("StartInputManagerService");
1568             inputManager = new InputManagerService(context);
1569             t.traceEnd();
1570 
1571             t.traceBegin("DeviceStateManagerService");
1572             mSystemServiceManager.startService(DeviceStateManagerService.class);
1573             t.traceEnd();
1574 
1575             if (!disableCameraService) {
1576                 t.traceBegin("StartCameraServiceProxy");
1577                 mSystemServiceManager.startService(CameraServiceProxy.class);
1578                 t.traceEnd();
1579             }
1580 
1581             t.traceBegin("StartWindowManagerService");
1582             // WMS needs sensor service ready
1583             mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_SENSOR_SERVICE);
1584             wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
1585                     new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
1586             ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
1587                     DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
1588             ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
1589                     /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
1590             t.traceEnd();
1591 
1592             t.traceBegin("SetWindowManagerService");
1593             mActivityManagerService.setWindowManager(wm);
1594             t.traceEnd();
1595 
1596             t.traceBegin("WindowManagerServiceOnInitReady");
1597             wm.onInitReady();
1598             t.traceEnd();
1599 
1600             // Start receiving calls from HIDL services. Start in in a separate thread
1601             // because it need to connect to SensorManager. This has to start
1602             // after PHASE_WAIT_FOR_SENSOR_SERVICE is done.
1603             SystemServerInitThreadPool.submit(() -> {
1604                 TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
1605                 traceLog.traceBegin(START_HIDL_SERVICES);
1606                 startHidlServices();
1607                 traceLog.traceEnd();
1608             }, START_HIDL_SERVICES);
1609 
1610             if (!isWatch && enableVrService) {
1611                 t.traceBegin("StartVrManagerService");
1612                 mSystemServiceManager.startService(VrManagerService.class);
1613                 t.traceEnd();
1614             }
1615 
1616             t.traceBegin("StartInputManager");
1617             inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback());
1618             inputManager.start();
1619             t.traceEnd();
1620 
1621             // TODO: Use service dependencies instead.
1622             t.traceBegin("DisplayManagerWindowManagerAndInputReady");
1623             mDisplayManagerService.windowManagerAndInputReady();
1624             t.traceEnd();
1625 
1626             if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
1627                 Slog.i(TAG, "No Bluetooth Service (factory test)");
1628             } else if (!context.getPackageManager().hasSystemFeature
1629                     (PackageManager.FEATURE_BLUETOOTH)) {
1630                 Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");
1631             } else {
1632                 t.traceBegin("StartBluetoothService");
1633                 mSystemServiceManager.startServiceFromJar(BLUETOOTH_SERVICE_CLASS,
1634                     BLUETOOTH_APEX_SERVICE_JAR_PATH);
1635                 t.traceEnd();
1636             }
1637 
1638             t.traceBegin("IpConnectivityMetrics");
1639             mSystemServiceManager.startService(IP_CONNECTIVITY_METRICS_CLASS);
1640             t.traceEnd();
1641 
1642             t.traceBegin("NetworkWatchlistService");
1643             mSystemServiceManager.startService(NetworkWatchlistService.Lifecycle.class);
1644             t.traceEnd();
1645 
1646             t.traceBegin("PinnerService");
1647             mSystemServiceManager.startService(PinnerService.class);
1648             t.traceEnd();
1649 
1650             if (Build.IS_DEBUGGABLE && ProfcollectForwardingService.enabled()) {
1651                 t.traceBegin("ProfcollectForwardingService");
1652                 mSystemServiceManager.startService(ProfcollectForwardingService.class);
1653                 t.traceEnd();
1654             }
1655 
1656             t.traceBegin("SignedConfigService");
1657             SignedConfigService.registerUpdateReceiver(mSystemContext);
1658             t.traceEnd();
1659 
1660             t.traceBegin("AppIntegrityService");
1661             mSystemServiceManager.startService(AppIntegrityManagerService.class);
1662             t.traceEnd();
1663 
1664             t.traceBegin("StartLogcatManager");
1665             mSystemServiceManager.startService(LogcatManagerService.class);
1666             t.traceEnd();
1667 
1668         } catch (Throwable e) {
1669             Slog.e("System", "******************************************");
1670             Slog.e("System", "************ Failure starting core service");
1671             throw e;
1672         }
1673 
1674         // Before things start rolling, be sure we have decided whether
1675         // we are in safe mode.
1676         final boolean safeMode = wm.detectSafeMode();
1677         if (safeMode) {
1678             // If yes, immediately turn on the global setting for airplane mode.
1679             // Note that this does not send broadcasts at this stage because
1680             // subsystems are not yet up. We will send broadcasts later to ensure
1681             // all listeners have the chance to react with special handling.
1682             Settings.Global.putInt(context.getContentResolver(),
1683                     Settings.Global.AIRPLANE_MODE_ON, 1);
1684         } else if (context.getResources().getBoolean(R.bool.config_autoResetAirplaneMode)) {
1685             Settings.Global.putInt(context.getContentResolver(),
1686                     Settings.Global.AIRPLANE_MODE_ON, 0);
1687         }
1688 
1689         StatusBarManagerService statusBar = null;
1690         INotificationManager notification = null;
1691         CountryDetectorService countryDetector = null;
1692         ILockSettings lockSettings = null;
1693         MediaRouterService mediaRouter = null;
1694 
1695         // Bring up services needed for UI.
1696         if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
1697             t.traceBegin("StartInputMethodManagerLifecycle");
1698             mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);
1699             t.traceEnd();
1700 
1701             t.traceBegin("StartAccessibilityManagerService");
1702             try {
1703                 mSystemServiceManager.startService(ACCESSIBILITY_MANAGER_SERVICE_CLASS);
1704             } catch (Throwable e) {
1705                 reportWtf("starting Accessibility Manager", e);
1706             }
1707             t.traceEnd();
1708         }
1709 
1710         t.traceBegin("MakeDisplayReady");
1711         try {
1712             wm.displayReady();
1713         } catch (Throwable e) {
1714             reportWtf("making display ready", e);
1715         }
1716         t.traceEnd();
1717 
1718         if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
1719             if (!"0".equals(SystemProperties.get("system_init.startmountservice"))) {
1720                 t.traceBegin("StartStorageManagerService");
1721                 try {
1722                     /*
1723                      * NotificationManagerService is dependant on StorageManagerService,
1724                      * (for media / usb notifications) so we must start StorageManagerService first.
1725                      */
1726                     mSystemServiceManager.startService(STORAGE_MANAGER_SERVICE_CLASS);
1727                     storageManager = IStorageManager.Stub.asInterface(
1728                             ServiceManager.getService("mount"));
1729                 } catch (Throwable e) {
1730                     reportWtf("starting StorageManagerService", e);
1731                 }
1732                 t.traceEnd();
1733 
1734                 t.traceBegin("StartStorageStatsService");
1735                 try {
1736                     mSystemServiceManager.startService(STORAGE_STATS_SERVICE_CLASS);
1737                 } catch (Throwable e) {
1738                     reportWtf("starting StorageStatsService", e);
1739                 }
1740                 t.traceEnd();
1741             }
1742         }
1743 
1744         // We start this here so that we update our configuration to set watch or television
1745         // as appropriate.
1746         t.traceBegin("StartUiModeManager");
1747         mSystemServiceManager.startService(UiModeManagerService.class);
1748         t.traceEnd();
1749 
1750         t.traceBegin("StartLocaleManagerService");
1751         try {
1752             mSystemServiceManager.startService(LocaleManagerService.class);
1753         } catch (Throwable e) {
1754             reportWtf("starting LocaleManagerService service", e);
1755         }
1756         t.traceEnd();
1757 
1758 
1759         if (!mOnlyCore) {
1760             t.traceBegin("UpdatePackagesIfNeeded");
1761             try {
1762                 Watchdog.getInstance().pauseWatchingCurrentThread("dexopt");
1763                 mPackageManagerService.updatePackagesIfNeeded();
1764             } catch (Throwable e) {
1765                 reportWtf("update packages", e);
1766             } finally {
1767                 Watchdog.getInstance().resumeWatchingCurrentThread("dexopt");
1768             }
1769             t.traceEnd();
1770         }
1771 
1772         t.traceBegin("PerformFstrimIfNeeded");
1773         try {
1774             mPackageManagerService.performFstrimIfNeeded();
1775         } catch (Throwable e) {
1776             reportWtf("performing fstrim", e);
1777         }
1778         t.traceEnd();
1779 
1780         final DevicePolicyManagerService.Lifecycle dpms;
1781         if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
1782             dpms = null;
1783         } else {
1784             t.traceBegin("StartLockSettingsService");
1785             try {
1786                 mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);
1787                 lockSettings = ILockSettings.Stub.asInterface(
1788                         ServiceManager.getService("lock_settings"));
1789             } catch (Throwable e) {
1790                 reportWtf("starting LockSettingsService service", e);
1791             }
1792             t.traceEnd();
1793 
1794             final boolean hasPdb = !SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("");
1795             if (hasPdb) {
1796                 t.traceBegin("StartPersistentDataBlock");
1797                 mSystemServiceManager.startService(PersistentDataBlockService.class);
1798                 t.traceEnd();
1799             }
1800 
1801             t.traceBegin("StartTestHarnessMode");
1802             mSystemServiceManager.startService(TestHarnessModeService.class);
1803             t.traceEnd();
1804 
1805             if (hasPdb || OemLockService.isHalPresent()) {
1806                 // Implementation depends on pdb or the OemLock HAL
1807                 t.traceBegin("StartOemLockService");
1808                 mSystemServiceManager.startService(OemLockService.class);
1809                 t.traceEnd();
1810             }
1811 
1812             t.traceBegin("StartDeviceIdleController");
1813             mSystemServiceManager.startService(DEVICE_IDLE_CONTROLLER_CLASS);
1814             t.traceEnd();
1815 
1816             // Always start the Device Policy Manager, so that the API is compatible with
1817             // API8.
1818             t.traceBegin("StartDevicePolicyManager");
1819             dpms = mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class);
1820             t.traceEnd();
1821 
1822             if (!isWatch) {
1823                 t.traceBegin("StartStatusBarManagerService");
1824                 try {
1825                     statusBar = new StatusBarManagerService(context);
1826                     ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar, false,
1827                             DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
1828                 } catch (Throwable e) {
1829                     reportWtf("starting StatusBarManagerService", e);
1830                 }
1831                 t.traceEnd();
1832             }
1833 
1834             if (deviceHasConfigString(context,
1835                     R.string.config_defaultMusicRecognitionService)) {
1836                 t.traceBegin("StartMusicRecognitionManagerService");
1837                 mSystemServiceManager.startService(MUSIC_RECOGNITION_MANAGER_SERVICE_CLASS);
1838                 t.traceEnd();
1839             } else {
1840                 Slog.d(TAG,
1841                         "MusicRecognitionManagerService not defined by OEM or disabled by flag");
1842             }
1843 
1844             startContentCaptureService(context, t);
1845             startAttentionService(context, t);
1846             startRotationResolverService(context, t);
1847             startSystemCaptionsManagerService(context, t);
1848             startTextToSpeechManagerService(context, t);
1849             startAmbientContextService(t);
1850 
1851             // System Speech Recognition Service
1852             t.traceBegin("StartSpeechRecognitionManagerService");
1853             mSystemServiceManager.startService(SPEECH_RECOGNITION_MANAGER_SERVICE_CLASS);
1854             t.traceEnd();
1855 
1856             // App prediction manager service
1857             if (deviceHasConfigString(context, R.string.config_defaultAppPredictionService)) {
1858                 t.traceBegin("StartAppPredictionService");
1859                 mSystemServiceManager.startService(APP_PREDICTION_MANAGER_SERVICE_CLASS);
1860                 t.traceEnd();
1861             } else {
1862                 Slog.d(TAG, "AppPredictionService not defined by OEM");
1863             }
1864 
1865             // Content suggestions manager service
1866             if (deviceHasConfigString(context, R.string.config_defaultContentSuggestionsService)) {
1867                 t.traceBegin("StartContentSuggestionsService");
1868                 mSystemServiceManager.startService(CONTENT_SUGGESTIONS_SERVICE_CLASS);
1869                 t.traceEnd();
1870             } else {
1871                 Slog.d(TAG, "ContentSuggestionsService not defined by OEM");
1872             }
1873 
1874             // Search UI manager service
1875             // TODO: add deviceHasConfigString(context, R.string.config_defaultSearchUiService)
1876             t.traceBegin("StartSearchUiService");
1877             mSystemServiceManager.startService(SEARCH_UI_MANAGER_SERVICE_CLASS);
1878             t.traceEnd();
1879 
1880             // Smartspace manager service
1881             // TODO: add deviceHasConfigString(context, R.string.config_defaultSmartspaceService)
1882             t.traceBegin("StartSmartspaceService");
1883             mSystemServiceManager.startService(SMARTSPACE_MANAGER_SERVICE_CLASS);
1884             t.traceEnd();
1885 
1886             t.traceBegin("InitConnectivityModuleConnector");
1887             try {
1888                 ConnectivityModuleConnector.getInstance().init(context);
1889             } catch (Throwable e) {
1890                 reportWtf("initializing ConnectivityModuleConnector", e);
1891             }
1892             t.traceEnd();
1893 
1894             t.traceBegin("InitNetworkStackClient");
1895             try {
1896                 NetworkStackClient.getInstance().init();
1897             } catch (Throwable e) {
1898                 reportWtf("initializing NetworkStackClient", e);
1899             }
1900             t.traceEnd();
1901 
1902             t.traceBegin("StartNetworkManagementService");
1903             try {
1904                 networkManagement = NetworkManagementService.create(context);
1905                 ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
1906             } catch (Throwable e) {
1907                 reportWtf("starting NetworkManagement Service", e);
1908             }
1909             t.traceEnd();
1910 
1911             t.traceBegin("StartFontManagerService");
1912             mSystemServiceManager.startService(new FontManagerService.Lifecycle(context, safeMode));
1913             t.traceEnd();
1914 
1915             t.traceBegin("StartTextServicesManager");
1916             mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);
1917             t.traceEnd();
1918 
1919             if (!disableSystemTextClassifier) {
1920                 t.traceBegin("StartTextClassificationManagerService");
1921                 mSystemServiceManager
1922                         .startService(TextClassificationManagerService.Lifecycle.class);
1923                 t.traceEnd();
1924             }
1925 
1926             t.traceBegin("StartNetworkScoreService");
1927             mSystemServiceManager.startService(NetworkScoreService.Lifecycle.class);
1928             t.traceEnd();
1929 
1930             t.traceBegin("StartNetworkStatsService");
1931             // This has to be called before NetworkPolicyManager because NetworkPolicyManager
1932             // needs to take NetworkStatsService to initialize.
1933             mSystemServiceManager.startServiceFromJar(NETWORK_STATS_SERVICE_INITIALIZER_CLASS,
1934                     CONNECTIVITY_SERVICE_APEX_PATH);
1935             t.traceEnd();
1936 
1937             t.traceBegin("StartNetworkPolicyManagerService");
1938             try {
1939                 networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService,
1940                         networkManagement);
1941                 ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
1942             } catch (Throwable e) {
1943                 reportWtf("starting NetworkPolicy Service", e);
1944             }
1945             t.traceEnd();
1946 
1947             if (context.getPackageManager().hasSystemFeature(
1948                     PackageManager.FEATURE_WIFI)) {
1949                 // Wifi Service must be started first for wifi-related services.
1950                 t.traceBegin("StartWifi");
1951                 mSystemServiceManager.startServiceFromJar(
1952                         WIFI_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
1953                 t.traceEnd();
1954                 t.traceBegin("StartWifiScanning");
1955                 mSystemServiceManager.startServiceFromJar(
1956                         WIFI_SCANNING_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
1957                 t.traceEnd();
1958             }
1959 
1960             if (context.getPackageManager().hasSystemFeature(
1961                     PackageManager.FEATURE_WIFI_RTT)) {
1962                 t.traceBegin("StartRttService");
1963                 mSystemServiceManager.startServiceFromJar(
1964                         WIFI_RTT_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
1965                 t.traceEnd();
1966             }
1967 
1968             if (context.getPackageManager().hasSystemFeature(
1969                     PackageManager.FEATURE_WIFI_AWARE)) {
1970                 t.traceBegin("StartWifiAware");
1971                 mSystemServiceManager.startServiceFromJar(
1972                         WIFI_AWARE_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
1973                 t.traceEnd();
1974             }
1975 
1976             if (context.getPackageManager().hasSystemFeature(
1977                     PackageManager.FEATURE_WIFI_DIRECT)) {
1978                 t.traceBegin("StartWifiP2P");
1979                 mSystemServiceManager.startServiceFromJar(
1980                         WIFI_P2P_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
1981                 t.traceEnd();
1982             }
1983 
1984             if (context.getPackageManager().hasSystemFeature(
1985                     PackageManager.FEATURE_LOWPAN)) {
1986                 t.traceBegin("StartLowpan");
1987                 mSystemServiceManager.startService(LOWPAN_SERVICE_CLASS);
1988                 t.traceEnd();
1989             }
1990 
1991             t.traceBegin("StartPacProxyService");
1992             try {
1993                 pacProxyService = new PacProxyService(context);
1994                 ServiceManager.addService(Context.PAC_PROXY_SERVICE, pacProxyService);
1995             } catch (Throwable e) {
1996                 reportWtf("starting PacProxyService", e);
1997             }
1998             t.traceEnd();
1999 
2000             t.traceBegin("StartConnectivityService");
2001             // This has to be called after NetworkManagementService, NetworkStatsService
2002             // and NetworkPolicyManager because ConnectivityService needs to take these
2003             // services to initialize.
2004             mSystemServiceManager.startServiceFromJar(CONNECTIVITY_SERVICE_INITIALIZER_CLASS,
2005                     CONNECTIVITY_SERVICE_APEX_PATH);
2006             networkPolicy.bindConnectivityManager();
2007             t.traceEnd();
2008 
2009             t.traceBegin("StartVpnManagerService");
2010             try {
2011                 vpnManager = VpnManagerService.create(context);
2012                 ServiceManager.addService(Context.VPN_MANAGEMENT_SERVICE, vpnManager);
2013             } catch (Throwable e) {
2014                 reportWtf("starting VPN Manager Service", e);
2015             }
2016             t.traceEnd();
2017 
2018             t.traceBegin("StartVcnManagementService");
2019             try {
2020                 vcnManagement = VcnManagementService.create(context);
2021                 ServiceManager.addService(Context.VCN_MANAGEMENT_SERVICE, vcnManagement);
2022             } catch (Throwable e) {
2023                 reportWtf("starting VCN Management Service", e);
2024             }
2025             t.traceEnd();
2026 
2027             t.traceBegin("StartSystemUpdateManagerService");
2028             try {
2029                 ServiceManager.addService(Context.SYSTEM_UPDATE_SERVICE,
2030                         new SystemUpdateManagerService(context));
2031             } catch (Throwable e) {
2032                 reportWtf("starting SystemUpdateManagerService", e);
2033             }
2034             t.traceEnd();
2035 
2036             t.traceBegin("StartUpdateLockService");
2037             try {
2038                 ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
2039                         new UpdateLockService(context));
2040             } catch (Throwable e) {
2041                 reportWtf("starting UpdateLockService", e);
2042             }
2043             t.traceEnd();
2044 
2045             t.traceBegin("StartNotificationManager");
2046             mSystemServiceManager.startService(NotificationManagerService.class);
2047             SystemNotificationChannels.removeDeprecated(context);
2048             SystemNotificationChannels.createAll(context);
2049             notification = INotificationManager.Stub.asInterface(
2050                     ServiceManager.getService(Context.NOTIFICATION_SERVICE));
2051             t.traceEnd();
2052 
2053             t.traceBegin("StartDeviceMonitor");
2054             mSystemServiceManager.startService(DeviceStorageMonitorService.class);
2055             t.traceEnd();
2056 
2057             t.traceBegin("StartLocationManagerService");
2058             mSystemServiceManager.startService(LocationManagerService.Lifecycle.class);
2059             t.traceEnd();
2060 
2061             t.traceBegin("StartCountryDetectorService");
2062             try {
2063                 countryDetector = new CountryDetectorService(context);
2064                 ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
2065             } catch (Throwable e) {
2066                 reportWtf("starting Country Detector", e);
2067             }
2068             t.traceEnd();
2069 
2070             t.traceBegin("StartTimeDetectorService");
2071             try {
2072                 mSystemServiceManager.startService(TIME_DETECTOR_SERVICE_CLASS);
2073             } catch (Throwable e) {
2074                 reportWtf("starting TimeDetectorService service", e);
2075             }
2076             t.traceEnd();
2077 
2078             t.traceBegin("StartTimeZoneDetectorService");
2079             try {
2080                 mSystemServiceManager.startService(TIME_ZONE_DETECTOR_SERVICE_CLASS);
2081             } catch (Throwable e) {
2082                 reportWtf("starting TimeZoneDetectorService service", e);
2083             }
2084             t.traceEnd();
2085 
2086             t.traceBegin("StartLocationTimeZoneManagerService");
2087             try {
2088                 mSystemServiceManager.startService(LOCATION_TIME_ZONE_MANAGER_SERVICE_CLASS);
2089             } catch (Throwable e) {
2090                 reportWtf("starting LocationTimeZoneManagerService service", e);
2091             }
2092             t.traceEnd();
2093 
2094             if (context.getResources().getBoolean(R.bool.config_enableGnssTimeUpdateService)) {
2095                 t.traceBegin("StartGnssTimeUpdateService");
2096                 try {
2097                     mSystemServiceManager.startService(GNSS_TIME_UPDATE_SERVICE_CLASS);
2098                 } catch (Throwable e) {
2099                     reportWtf("starting GnssTimeUpdateService service", e);
2100                 }
2101                 t.traceEnd();
2102             }
2103 
2104             if (!isWatch) {
2105                 t.traceBegin("StartSearchManagerService");
2106                 try {
2107                     mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS);
2108                 } catch (Throwable e) {
2109                     reportWtf("starting Search Service", e);
2110                 }
2111                 t.traceEnd();
2112             }
2113 
2114             if (context.getResources().getBoolean(R.bool.config_enableWallpaperService)) {
2115                 t.traceBegin("StartWallpaperManagerService");
2116                 mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
2117                 t.traceEnd();
2118             } else {
2119                 Slog.i(TAG, "Wallpaper service disabled by config");
2120             }
2121 
2122             // WallpaperEffectsGeneration manager service
2123             // TODO (b/135218095): Use deviceHasConfigString(context,
2124             //  R.string.config_defaultWallpaperEffectsGenerationService)
2125             t.traceBegin("StartWallpaperEffectsGenerationService");
2126             mSystemServiceManager.startService(
2127                     WALLPAPER_EFFECTS_GENERATION_MANAGER_SERVICE_CLASS);
2128             t.traceEnd();
2129 
2130             t.traceBegin("StartAudioService");
2131             if (!isArc) {
2132                 mSystemServiceManager.startService(AudioService.Lifecycle.class);
2133             } else {
2134                 String className = context.getResources()
2135                         .getString(R.string.config_deviceSpecificAudioService);
2136                 try {
2137                     mSystemServiceManager.startService(className + "$Lifecycle");
2138                 } catch (Throwable e) {
2139                     reportWtf("starting " + className, e);
2140                 }
2141             }
2142             t.traceEnd();
2143 
2144             t.traceBegin("StartSoundTriggerMiddlewareService");
2145             mSystemServiceManager.startService(SoundTriggerMiddlewareService.Lifecycle.class);
2146             t.traceEnd();
2147 
2148             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BROADCAST_RADIO)) {
2149                 t.traceBegin("StartBroadcastRadioService");
2150                 mSystemServiceManager.startService(BroadcastRadioService.class);
2151                 t.traceEnd();
2152             }
2153 
2154             t.traceBegin("StartDockObserver");
2155             mSystemServiceManager.startService(DockObserver.class);
2156             t.traceEnd();
2157 
2158             if (isWatch) {
2159                 t.traceBegin("StartThermalObserver");
2160                 mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS);
2161                 t.traceEnd();
2162             }
2163 
2164             if (!isWatch) {
2165                 t.traceBegin("StartWiredAccessoryManager");
2166                 try {
2167                     // Listen for wired headset changes
2168                     inputManager.setWiredAccessoryCallbacks(
2169                             new WiredAccessoryManager(context, inputManager));
2170                 } catch (Throwable e) {
2171                     reportWtf("starting WiredAccessoryManager", e);
2172                 }
2173                 t.traceEnd();
2174             }
2175 
2176             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) {
2177                 // Start MIDI Manager service
2178                 t.traceBegin("StartMidiManager");
2179                 mSystemServiceManager.startService(MIDI_SERVICE_CLASS);
2180                 t.traceEnd();
2181             }
2182 
2183             // Start ADB Debugging Service
2184             t.traceBegin("StartAdbService");
2185             try {
2186                 mSystemServiceManager.startService(ADB_SERVICE_CLASS);
2187             } catch (Throwable e) {
2188                 Slog.e(TAG, "Failure starting AdbService");
2189             }
2190             t.traceEnd();
2191 
2192             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)
2193                     || mPackageManager.hasSystemFeature(
2194                     PackageManager.FEATURE_USB_ACCESSORY)
2195                     || isEmulator) {
2196                 // Manage USB host and device support
2197                 t.traceBegin("StartUsbService");
2198                 mSystemServiceManager.startService(USB_SERVICE_CLASS);
2199                 t.traceEnd();
2200             }
2201 
2202             if (!isWatch) {
2203                 t.traceBegin("StartSerialService");
2204                 try {
2205                     // Serial port support
2206                     serial = new SerialService(context);
2207                     ServiceManager.addService(Context.SERIAL_SERVICE, serial);
2208                 } catch (Throwable e) {
2209                     Slog.e(TAG, "Failure starting SerialService", e);
2210                 }
2211                 t.traceEnd();
2212             }
2213 
2214             t.traceBegin("StartHardwarePropertiesManagerService");
2215             try {
2216                 hardwarePropertiesService = new HardwarePropertiesManagerService(context);
2217                 ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE,
2218                         hardwarePropertiesService);
2219             } catch (Throwable e) {
2220                 Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e);
2221             }
2222             t.traceEnd();
2223 
2224             if (!isWatch) {
2225                 t.traceBegin("StartTwilightService");
2226                 mSystemServiceManager.startService(TwilightService.class);
2227                 t.traceEnd();
2228             }
2229 
2230             t.traceBegin("StartColorDisplay");
2231             mSystemServiceManager.startService(ColorDisplayService.class);
2232             t.traceEnd();
2233 
2234             // TODO(aml-jobscheduler): Think about how to do it properly.
2235             t.traceBegin("StartJobScheduler");
2236             mSystemServiceManager.startService(JOB_SCHEDULER_SERVICE_CLASS);
2237             t.traceEnd();
2238 
2239             t.traceBegin("StartSoundTrigger");
2240             mSystemServiceManager.startService(SoundTriggerService.class);
2241             t.traceEnd();
2242 
2243             t.traceBegin("StartTrustManager");
2244             mSystemServiceManager.startService(TrustManagerService.class);
2245             t.traceEnd();
2246 
2247             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) {
2248                 t.traceBegin("StartBackupManager");
2249                 mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS);
2250                 t.traceEnd();
2251             }
2252 
2253             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)
2254                     || context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {
2255                 t.traceBegin("StartAppWidgetService");
2256                 mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS);
2257                 t.traceEnd();
2258             }
2259 
2260             // We need to always start this service, regardless of whether the
2261             // FEATURE_VOICE_RECOGNIZERS feature is set, because it needs to take care
2262             // of initializing various settings.  It will internally modify its behavior
2263             // based on that feature.
2264             t.traceBegin("StartVoiceRecognitionManager");
2265             mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS);
2266             t.traceEnd();
2267 
2268             t.traceBegin("StartAppHibernationService");
2269             mSystemServiceManager.startService(APP_HIBERNATION_SERVICE_CLASS);
2270             t.traceEnd();
2271 
2272             if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) {
2273                 t.traceBegin("StartGestureLauncher");
2274                 mSystemServiceManager.startService(GestureLauncherService.class);
2275                 t.traceEnd();
2276             }
2277             t.traceBegin("StartSensorNotification");
2278             mSystemServiceManager.startService(SensorNotificationService.class);
2279             t.traceEnd();
2280 
2281             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_CONTEXT_HUB)) {
2282                 t.traceBegin("StartContextHubSystemService");
2283                 mSystemServiceManager.startService(ContextHubSystemService.class);
2284                 t.traceEnd();
2285             }
2286 
2287             t.traceBegin("StartDiskStatsService");
2288             try {
2289                 ServiceManager.addService("diskstats", new DiskStatsService(context));
2290             } catch (Throwable e) {
2291                 reportWtf("starting DiskStats Service", e);
2292             }
2293             t.traceEnd();
2294 
2295             t.traceBegin("RuntimeService");
2296             try {
2297                 ServiceManager.addService("runtime", new RuntimeService(context));
2298             } catch (Throwable e) {
2299                 reportWtf("starting RuntimeService", e);
2300             }
2301             t.traceEnd();
2302 
2303             // timezone.RulesManagerService will prevent a device starting up if the chain of trust
2304             // required for safe time zone updates might be broken. RuleManagerService cannot do
2305             // this check when mOnlyCore == true, so we don't enable the service in this case.
2306             // This service requires that JobSchedulerService is already started when it starts.
2307             final boolean startRulesManagerService =
2308                     !mOnlyCore && context.getResources().getBoolean(
2309                             R.bool.config_enableUpdateableTimeZoneRules);
2310             if (startRulesManagerService) {
2311                 t.traceBegin("StartTimeZoneRulesManagerService");
2312                 mSystemServiceManager.startService(TIME_ZONE_RULES_MANAGER_SERVICE_CLASS);
2313                 t.traceEnd();
2314             }
2315 
2316             if (!isWatch && !disableNetworkTime) {
2317                 t.traceBegin("StartNetworkTimeUpdateService");
2318                 try {
2319                     networkTimeUpdater = new NetworkTimeUpdateService(context);
2320                     ServiceManager.addService("network_time_update_service", networkTimeUpdater);
2321                 } catch (Throwable e) {
2322                     reportWtf("starting NetworkTimeUpdate service", e);
2323                 }
2324                 t.traceEnd();
2325             }
2326 
2327             t.traceBegin("CertBlacklister");
2328             try {
2329                 CertBlacklister blacklister = new CertBlacklister(context);
2330             } catch (Throwable e) {
2331                 reportWtf("starting CertBlacklister", e);
2332             }
2333             t.traceEnd();
2334 
2335             if (EmergencyAffordanceManager.ENABLED) {
2336                 // EmergencyMode service
2337                 t.traceBegin("StartEmergencyAffordanceService");
2338                 mSystemServiceManager.startService(EmergencyAffordanceService.class);
2339                 t.traceEnd();
2340             }
2341 
2342             t.traceBegin(START_BLOB_STORE_SERVICE);
2343             mSystemServiceManager.startService(BLOB_STORE_MANAGER_SERVICE_CLASS);
2344             t.traceEnd();
2345 
2346             // Dreams (interactive idle-time views, a/k/a screen savers, and doze mode)
2347             t.traceBegin("StartDreamManager");
2348             mSystemServiceManager.startService(DreamManagerService.class);
2349             t.traceEnd();
2350 
2351             t.traceBegin("AddGraphicsStatsService");
2352             ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE,
2353                     new GraphicsStatsService(context));
2354             t.traceEnd();
2355 
2356             if (CoverageService.ENABLED) {
2357                 t.traceBegin("AddCoverageService");
2358                 ServiceManager.addService(CoverageService.COVERAGE_SERVICE, new CoverageService());
2359                 t.traceEnd();
2360             }
2361 
2362             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) {
2363                 t.traceBegin("StartPrintManager");
2364                 mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS);
2365                 t.traceEnd();
2366             }
2367 
2368             t.traceBegin("StartAttestationVerificationService");
2369             mSystemServiceManager.startService(AttestationVerificationManagerService.class);
2370             t.traceEnd();
2371 
2372             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_COMPANION_DEVICE_SETUP)) {
2373                 t.traceBegin("StartCompanionDeviceManager");
2374                 mSystemServiceManager.startService(COMPANION_DEVICE_MANAGER_SERVICE_CLASS);
2375                 t.traceEnd();
2376 
2377                 // VirtualDeviceManager depends on CDM to control the associations.
2378                 t.traceBegin("StartVirtualDeviceManager");
2379                 mSystemServiceManager.startService(VIRTUAL_DEVICE_MANAGER_SERVICE_CLASS);
2380                 t.traceEnd();
2381             }
2382 
2383             t.traceBegin("StartRestrictionManager");
2384             mSystemServiceManager.startService(RestrictionsManagerService.class);
2385             t.traceEnd();
2386 
2387             t.traceBegin("StartMediaSessionService");
2388             mSystemServiceManager.startService(MEDIA_SESSION_SERVICE_CLASS);
2389             t.traceEnd();
2390 
2391             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) {
2392                 t.traceBegin("StartHdmiControlService");
2393                 mSystemServiceManager.startService(HdmiControlService.class);
2394                 t.traceEnd();
2395             }
2396 
2397             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)
2398                     || mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
2399                 t.traceBegin("StartTvInteractiveAppManager");
2400                 mSystemServiceManager.startService(TvInteractiveAppManagerService.class);
2401                 t.traceEnd();
2402             }
2403 
2404             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)
2405                     || mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
2406                 t.traceBegin("StartTvInputManager");
2407                 mSystemServiceManager.startService(TvInputManagerService.class);
2408                 t.traceEnd();
2409             }
2410 
2411             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_TUNER)) {
2412                 t.traceBegin("StartTunerResourceManager");
2413                 mSystemServiceManager.startService(TunerResourceManagerService.class);
2414                 t.traceEnd();
2415             }
2416 
2417             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
2418                 t.traceBegin("StartMediaResourceMonitor");
2419                 mSystemServiceManager.startService(MEDIA_RESOURCE_MONITOR_SERVICE_CLASS);
2420                 t.traceEnd();
2421             }
2422 
2423             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
2424                 t.traceBegin("StartTvRemoteService");
2425                 mSystemServiceManager.startService(TvRemoteService.class);
2426                 t.traceEnd();
2427             }
2428 
2429             t.traceBegin("StartMediaRouterService");
2430             try {
2431                 mediaRouter = new MediaRouterService(context);
2432                 ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);
2433             } catch (Throwable e) {
2434                 reportWtf("starting MediaRouterService", e);
2435             }
2436             t.traceEnd();
2437 
2438             final boolean hasFeatureFace
2439                     = mPackageManager.hasSystemFeature(PackageManager.FEATURE_FACE);
2440             final boolean hasFeatureIris
2441                     = mPackageManager.hasSystemFeature(PackageManager.FEATURE_IRIS);
2442             final boolean hasFeatureFingerprint
2443                     = mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);
2444 
2445             if (hasFeatureFace) {
2446                 t.traceBegin("StartFaceSensor");
2447                 final FaceService faceService =
2448                         mSystemServiceManager.startService(FaceService.class);
2449                 t.traceEnd();
2450             }
2451 
2452             if (hasFeatureIris) {
2453                 t.traceBegin("StartIrisSensor");
2454                 mSystemServiceManager.startService(IrisService.class);
2455                 t.traceEnd();
2456             }
2457 
2458             if (hasFeatureFingerprint) {
2459                 t.traceBegin("StartFingerprintSensor");
2460                 final FingerprintService fingerprintService =
2461                         mSystemServiceManager.startService(FingerprintService.class);
2462                 t.traceEnd();
2463             }
2464 
2465             // Start this service after all biometric sensor services are started.
2466             t.traceBegin("StartBiometricService");
2467             mSystemServiceManager.startService(BiometricService.class);
2468             t.traceEnd();
2469 
2470             t.traceBegin("StartAuthService");
2471             mSystemServiceManager.startService(AuthService.class);
2472             t.traceEnd();
2473 
2474             if (!isWatch) {
2475                 // We don't run this on watches as there are no plans to use the data logged
2476                 // on watch devices.
2477                 t.traceBegin("StartDynamicCodeLoggingService");
2478                 try {
2479                     DynamicCodeLoggingService.schedule(context);
2480                 } catch (Throwable e) {
2481                     reportWtf("starting DynamicCodeLoggingService", e);
2482                 }
2483                 t.traceEnd();
2484             }
2485 
2486             if (!isWatch) {
2487                 t.traceBegin("StartPruneInstantAppsJobService");
2488                 try {
2489                     PruneInstantAppsJobService.schedule(context);
2490                 } catch (Throwable e) {
2491                     reportWtf("StartPruneInstantAppsJobService", e);
2492                 }
2493                 t.traceEnd();
2494             }
2495 
2496             // LauncherAppsService uses ShortcutService.
2497             t.traceBegin("StartShortcutServiceLifecycle");
2498             mSystemServiceManager.startService(ShortcutService.Lifecycle.class);
2499             t.traceEnd();
2500 
2501             t.traceBegin("StartLauncherAppsService");
2502             mSystemServiceManager.startService(LauncherAppsService.class);
2503             t.traceEnd();
2504 
2505             t.traceBegin("StartCrossProfileAppsService");
2506             mSystemServiceManager.startService(CrossProfileAppsService.class);
2507             t.traceEnd();
2508 
2509             t.traceBegin("StartPeopleService");
2510             mSystemServiceManager.startService(PeopleService.class);
2511             t.traceEnd();
2512 
2513             t.traceBegin("StartMediaMetricsManager");
2514             mSystemServiceManager.startService(MediaMetricsManagerService.class);
2515             t.traceEnd();
2516         }
2517 
2518         t.traceBegin("StartMediaProjectionManager");
2519         mSystemServiceManager.startService(MediaProjectionManagerService.class);
2520         t.traceEnd();
2521 
2522        if (isWatch) {
2523             // Must be started before services that depend it, e.g. WearConnectivityService
2524             t.traceBegin("StartWearPowerService");
2525             mSystemServiceManager.startService(WEAR_POWER_SERVICE_CLASS);
2526             t.traceEnd();
2527 
2528             t.traceBegin("StartHealthService");
2529             mSystemServiceManager.startService(HEALTH_SERVICE_CLASS);
2530             t.traceEnd();
2531 
2532             t.traceBegin("StartWearConnectivityService");
2533             mSystemServiceManager.startService(WEAR_CONNECTIVITY_SERVICE_CLASS);
2534             t.traceEnd();
2535 
2536             t.traceBegin("StartWearDisplayService");
2537             mSystemServiceManager.startService(WEAR_DISPLAY_SERVICE_CLASS);
2538             t.traceEnd();
2539 
2540             t.traceBegin("StartWearTimeService");
2541             mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS);
2542             t.traceEnd();
2543 
2544             if (enableLeftyService) {
2545                 t.traceBegin("StartWearLeftyService");
2546                 mSystemServiceManager.startService(WEAR_LEFTY_SERVICE_CLASS);
2547                 t.traceEnd();
2548             }
2549 
2550             t.traceBegin("StartWearGlobalActionsService");
2551             mSystemServiceManager.startService(WEAR_GLOBAL_ACTIONS_SERVICE_CLASS);
2552             t.traceEnd();
2553         }
2554 
2555         if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_SLICES_DISABLED)) {
2556             t.traceBegin("StartSliceManagerService");
2557             mSystemServiceManager.startService(SLICE_MANAGER_SERVICE_CLASS);
2558             t.traceEnd();
2559         }
2560 
2561         if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_EMBEDDED)) {
2562             t.traceBegin("StartIoTSystemService");
2563             mSystemServiceManager.startService(IOT_SERVICE_CLASS);
2564             t.traceEnd();
2565         }
2566 
2567         // Statsd helper
2568         t.traceBegin("StartStatsCompanion");
2569         mSystemServiceManager.startServiceFromJar(
2570                 STATS_COMPANION_LIFECYCLE_CLASS, STATS_COMPANION_APEX_PATH);
2571         t.traceEnd();
2572 
2573         // Reboot Readiness
2574         t.traceBegin("StartRebootReadinessManagerService");
2575         mSystemServiceManager.startServiceFromJar(
2576                 REBOOT_READINESS_LIFECYCLE_CLASS, SCHEDULING_APEX_PATH);
2577         t.traceEnd();
2578 
2579         // Statsd pulled atoms
2580         t.traceBegin("StartStatsPullAtomService");
2581         mSystemServiceManager.startService(STATS_PULL_ATOM_SERVICE_CLASS);
2582         t.traceEnd();
2583 
2584         // Log atoms to statsd from bootstrap processes.
2585         t.traceBegin("StatsBootstrapAtomService");
2586         mSystemServiceManager.startService(STATS_BOOTSTRAP_ATOM_SERVICE_LIFECYCLE_CLASS);
2587         t.traceEnd();
2588 
2589         // Incidentd and dumpstated helper
2590         t.traceBegin("StartIncidentCompanionService");
2591         mSystemServiceManager.startService(IncidentCompanionService.class);
2592         t.traceEnd();
2593 
2594         // SdkSandboxManagerService
2595         t.traceBegin("StarSdkSandboxManagerService");
2596         mSystemServiceManager.startService(SDK_SANDBOX_MANAGER_SERVICE_CLASS);
2597         t.traceEnd();
2598 
2599         // AdServicesManagerService (PP API service)
2600         t.traceBegin("StartAdServicesManagerService");
2601         mSystemServiceManager.startService(AD_SERVICES_MANAGER_SERVICE_CLASS);
2602         t.traceEnd();
2603 
2604         if (safeMode) {
2605             mActivityManagerService.enterSafeMode();
2606         }
2607 
2608         if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
2609             // MMS service broker
2610             t.traceBegin("StartMmsService");
2611             mmsService = mSystemServiceManager.startService(MmsServiceBroker.class);
2612             t.traceEnd();
2613         }
2614 
2615         if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOFILL)) {
2616             t.traceBegin("StartAutoFillService");
2617             mSystemServiceManager.startService(AUTO_FILL_MANAGER_SERVICE_CLASS);
2618             t.traceEnd();
2619         }
2620 
2621         // Translation manager service
2622         if (deviceHasConfigString(context, R.string.config_defaultTranslationService)) {
2623             t.traceBegin("StartTranslationManagerService");
2624             mSystemServiceManager.startService(TRANSLATION_MANAGER_SERVICE_CLASS);
2625             t.traceEnd();
2626         } else {
2627             Slog.d(TAG, "TranslationService not defined by OEM");
2628         }
2629 
2630         // NOTE: ClipboardService depends on ContentCapture and Autofill
2631         t.traceBegin("StartClipboardService");
2632         mSystemServiceManager.startService(ClipboardService.class);
2633         t.traceEnd();
2634 
2635         t.traceBegin("AppServiceManager");
2636         mSystemServiceManager.startService(AppBindingService.Lifecycle.class);
2637         t.traceEnd();
2638 
2639         // Perfetto TracingServiceProxy
2640         t.traceBegin("startTracingServiceProxy");
2641         mSystemServiceManager.startService(TracingServiceProxy.class);
2642         t.traceEnd();
2643 
2644         // It is now time to start up the app processes...
2645 
2646         t.traceBegin("MakeLockSettingsServiceReady");
2647         if (lockSettings != null) {
2648             try {
2649                 lockSettings.systemReady();
2650             } catch (Throwable e) {
2651                 reportWtf("making Lock Settings Service ready", e);
2652             }
2653         }
2654         t.traceEnd();
2655 
2656         // Needed by DevicePolicyManager for initialization
2657         t.traceBegin("StartBootPhaseLockSettingsReady");
2658         mSystemServiceManager.startBootPhase(t, SystemService.PHASE_LOCK_SETTINGS_READY);
2659         t.traceEnd();
2660 
2661         t.traceBegin("StartBootPhaseSystemServicesReady");
2662         mSystemServiceManager.startBootPhase(t, SystemService.PHASE_SYSTEM_SERVICES_READY);
2663         t.traceEnd();
2664 
2665         t.traceBegin("MakeWindowManagerServiceReady");
2666         try {
2667             wm.systemReady();
2668         } catch (Throwable e) {
2669             reportWtf("making Window Manager Service ready", e);
2670         }
2671         t.traceEnd();
2672 
2673         // Emit any pending system_server WTFs
2674         synchronized (SystemService.class) {
2675             if (sPendingWtfs != null) {
2676                 mActivityManagerService.schedulePendingSystemServerWtfs(sPendingWtfs);
2677                 sPendingWtfs = null;
2678             }
2679         }
2680 
2681         if (safeMode) {
2682             mActivityManagerService.showSafeModeOverlay();
2683         }
2684 
2685         // Update the configuration for this context by hand, because we're going
2686         // to start using it before the config change done in wm.systemReady() will
2687         // propagate to it.
2688         final Configuration config = wm.computeNewConfiguration(DEFAULT_DISPLAY);
2689         DisplayMetrics metrics = new DisplayMetrics();
2690         context.getDisplay().getMetrics(metrics);
2691         context.getResources().updateConfiguration(config, metrics);
2692 
2693         // The system context's theme may be configuration-dependent.
2694         final Theme systemTheme = context.getTheme();
2695         if (systemTheme.getChangingConfigurations() != 0) {
2696             systemTheme.rebase();
2697         }
2698 
2699         // Permission policy service
2700         t.traceBegin("StartPermissionPolicyService");
2701         mSystemServiceManager.startService(PermissionPolicyService.class);
2702         t.traceEnd();
2703 
2704         t.traceBegin("MakePackageManagerServiceReady");
2705         mPackageManagerService.systemReady();
2706         t.traceEnd();
2707 
2708         t.traceBegin("MakeDisplayManagerServiceReady");
2709         try {
2710             // TODO: use boot phase and communicate these flags some other way
2711             mDisplayManagerService.systemReady(safeMode, mOnlyCore);
2712         } catch (Throwable e) {
2713             reportWtf("making Display Manager Service ready", e);
2714         }
2715         t.traceEnd();
2716 
2717         mSystemServiceManager.setSafeMode(safeMode);
2718 
2719         // Start device specific services
2720         t.traceBegin("StartDeviceSpecificServices");
2721         final String[] classes = mSystemContext.getResources().getStringArray(
2722                 R.array.config_deviceSpecificSystemServices);
2723         for (final String className : classes) {
2724             t.traceBegin("StartDeviceSpecificServices " + className);
2725             try {
2726                 mSystemServiceManager.startService(className);
2727             } catch (Throwable e) {
2728                 reportWtf("starting " + className, e);
2729             }
2730             t.traceEnd();
2731         }
2732         t.traceEnd();
2733 
2734         t.traceBegin("GameManagerService");
2735         mSystemServiceManager.startService(GAME_MANAGER_SERVICE_CLASS);
2736         t.traceEnd();
2737 
2738         t.traceBegin("ArtManagerLocal");
2739         LocalManagerRegistry.addManager(ArtManagerLocal.class, new ArtManagerLocal());
2740         t.traceEnd();
2741 
2742         if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_UWB)) {
2743             t.traceBegin("UwbService");
2744             mSystemServiceManager.startServiceFromJar(UWB_SERVICE_CLASS, UWB_APEX_SERVICE_JAR_PATH);
2745             t.traceEnd();
2746         }
2747 
2748         t.traceBegin("StartBootPhaseDeviceSpecificServicesReady");
2749         mSystemServiceManager.startBootPhase(t, SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);
2750         t.traceEnd();
2751 
2752         t.traceBegin("StartSafetyCenterService");
2753         mSystemServiceManager.startService(SAFETY_CENTER_SERVICE_CLASS);
2754         t.traceEnd();
2755 
2756         t.traceBegin("AppSearchModule");
2757         mSystemServiceManager.startService(APPSEARCH_MODULE_LIFECYCLE_CLASS);
2758         t.traceEnd();
2759 
2760         if (SystemProperties.getBoolean("ro.config.isolated_compilation_enabled", false)) {
2761             t.traceBegin("IsolatedCompilationService");
2762             mSystemServiceManager.startService(ISOLATED_COMPILATION_SERVICE_CLASS);
2763             t.traceEnd();
2764         }
2765 
2766         t.traceBegin("StartMediaCommunicationService");
2767         mSystemServiceManager.startService(MEDIA_COMMUNICATION_SERVICE_CLASS);
2768         t.traceEnd();
2769 
2770         t.traceBegin("AppCompatOverridesService");
2771         mSystemServiceManager.startService(APP_COMPAT_OVERRIDES_SERVICE_CLASS);
2772         t.traceEnd();
2773 
2774         // These are needed to propagate to the runnable below.
2775         final NetworkManagementService networkManagementF = networkManagement;
2776         final NetworkPolicyManagerService networkPolicyF = networkPolicy;
2777         final CountryDetectorService countryDetectorF = countryDetector;
2778         final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
2779         final InputManagerService inputManagerF = inputManager;
2780         final TelephonyRegistry telephonyRegistryF = telephonyRegistry;
2781         final MediaRouterService mediaRouterF = mediaRouter;
2782         final MmsServiceBroker mmsServiceF = mmsService;
2783         final VpnManagerService vpnManagerF = vpnManager;
2784         final VcnManagementService vcnManagementF = vcnManagement;
2785         final WindowManagerService windowManagerF = wm;
2786         final ConnectivityManager connectivityF = (ConnectivityManager)
2787                 context.getSystemService(Context.CONNECTIVITY_SERVICE);
2788 
2789         // We now tell the activity manager it is okay to run third party
2790         // code.  It will call back into us once it has gotten to the state
2791         // where third party code can really run (but before it has actually
2792         // started launching the initial applications), for us to complete our
2793         // initialization.
2794         mActivityManagerService.systemReady(() -> {
2795             Slog.i(TAG, "Making services ready");
2796             t.traceBegin("StartActivityManagerReadyPhase");
2797             mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);
2798             t.traceEnd();
2799             t.traceBegin("StartObservingNativeCrashes");
2800             try {
2801                 mActivityManagerService.startObservingNativeCrashes();
2802             } catch (Throwable e) {
2803                 reportWtf("observing native crashes", e);
2804             }
2805             t.traceEnd();
2806 
2807             t.traceBegin("RegisterAppOpsPolicy");
2808             try {
2809                 mActivityManagerService.setAppOpsPolicy(new AppOpsPolicy(mSystemContext));
2810             } catch (Throwable e) {
2811                 reportWtf("registering app ops policy", e);
2812             }
2813             t.traceEnd();
2814 
2815             // No dependency on Webview preparation in system server. But this should
2816             // be completed before allowing 3rd party
2817             final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
2818             Future<?> webviewPrep = null;
2819             if (!mOnlyCore && mWebViewUpdateService != null) {
2820                 webviewPrep = SystemServerInitThreadPool.submit(() -> {
2821                     Slog.i(TAG, WEBVIEW_PREPARATION);
2822                     TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
2823                     traceLog.traceBegin(WEBVIEW_PREPARATION);
2824                     ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
2825                     mZygotePreload = null;
2826                     mWebViewUpdateService.prepareWebViewInSystemServer();
2827                     traceLog.traceEnd();
2828                 }, WEBVIEW_PREPARATION);
2829             }
2830 
2831             boolean isAutomotive = mPackageManager
2832                     .hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
2833             if (isAutomotive) {
2834                 t.traceBegin("StartCarServiceHelperService");
2835                 final SystemService cshs = mSystemServiceManager
2836                         .startService(CAR_SERVICE_HELPER_SERVICE_CLASS);
2837                 if (cshs instanceof Dumpable) {
2838                     mDumper.addDumpable((Dumpable) cshs);
2839                 }
2840                 if (cshs instanceof DevicePolicySafetyChecker) {
2841                     dpms.setDevicePolicySafetyChecker((DevicePolicySafetyChecker) cshs);
2842                 }
2843                 t.traceEnd();
2844             }
2845 
2846             // Enable airplane mode in safe mode. setAirplaneMode() cannot be called
2847             // earlier as it sends broadcasts to other services.
2848             // TODO: This may actually be too late if radio firmware already started leaking
2849             // RF before the respective services start. However, fixing this requires changes
2850             // to radio firmware and interfaces.
2851             if (safeMode) {
2852                 t.traceBegin("EnableAirplaneModeInSafeMode");
2853                 try {
2854                     connectivityF.setAirplaneMode(true);
2855                 } catch (Throwable e) {
2856                     reportWtf("enabling Airplane Mode during Safe Mode bootup", e);
2857                 }
2858                 t.traceEnd();
2859             }
2860             t.traceBegin("MakeNetworkManagementServiceReady");
2861             try {
2862                 if (networkManagementF != null) {
2863                     networkManagementF.systemReady();
2864                 }
2865             } catch (Throwable e) {
2866                 reportWtf("making Network Managment Service ready", e);
2867             }
2868             CountDownLatch networkPolicyInitReadySignal = null;
2869             if (networkPolicyF != null) {
2870                 networkPolicyInitReadySignal = networkPolicyF
2871                         .networkScoreAndNetworkManagementServiceReady();
2872             }
2873             t.traceEnd();
2874             t.traceBegin("MakeConnectivityServiceReady");
2875             try {
2876                 if (connectivityF != null) {
2877                     connectivityF.systemReady();
2878                 }
2879             } catch (Throwable e) {
2880                 reportWtf("making Connectivity Service ready", e);
2881             }
2882             t.traceEnd();
2883             t.traceBegin("MakeVpnManagerServiceReady");
2884             try {
2885                 if (vpnManagerF != null) {
2886                     vpnManagerF.systemReady();
2887                 }
2888             } catch (Throwable e) {
2889                 reportWtf("making VpnManagerService ready", e);
2890             }
2891             t.traceEnd();
2892             t.traceBegin("MakeVcnManagementServiceReady");
2893             try {
2894                 if (vcnManagementF != null) {
2895                     vcnManagementF.systemReady();
2896                 }
2897             } catch (Throwable e) {
2898                 reportWtf("making VcnManagementService ready", e);
2899             }
2900             t.traceEnd();
2901             t.traceBegin("MakeNetworkPolicyServiceReady");
2902             try {
2903                 if (networkPolicyF != null) {
2904                     networkPolicyF.systemReady(networkPolicyInitReadySignal);
2905                 }
2906             } catch (Throwable e) {
2907                 reportWtf("making Network Policy Service ready", e);
2908             }
2909             t.traceEnd();
2910 
2911             // Wait for all packages to be prepared
2912             mPackageManagerService.waitForAppDataPrepared();
2913 
2914             // It is now okay to let the various system services start their
2915             // third party code...
2916             t.traceBegin("PhaseThirdPartyAppsCanStart");
2917             // confirm webview completion before starting 3rd party
2918             if (webviewPrep != null) {
2919                 ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);
2920             }
2921             mSystemServiceManager.startBootPhase(t, SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
2922             t.traceEnd();
2923 
2924             if (UserManager.isHeadlessSystemUserMode() && !isAutomotive) {
2925                 // TODO(b/204091126): remove isAutomotive check once the workflow is finalized
2926                 t.traceBegin("BootUserInitializer");
2927                 new BootUserInitializer(mActivityManagerService, mContentResolver).init(t);
2928                 t.traceEnd();
2929             }
2930 
2931             t.traceBegin("StartNetworkStack");
2932             try {
2933                 // Note : the network stack is creating on-demand objects that need to send
2934                 // broadcasts, which means it currently depends on being started after
2935                 // ActivityManagerService.mSystemReady and ActivityManagerService.mProcessesReady
2936                 // are set to true. Be careful if moving this to a different place in the
2937                 // startup sequence.
2938                 NetworkStackClient.getInstance().start();
2939             } catch (Throwable e) {
2940                 reportWtf("starting Network Stack", e);
2941             }
2942             t.traceEnd();
2943 
2944             t.traceBegin("StartTethering");
2945             try {
2946                 // TODO: hide implementation details, b/146312721.
2947                 ConnectivityModuleConnector.getInstance().startModuleService(
2948                         TETHERING_CONNECTOR_CLASS,
2949                         PERMISSION_MAINLINE_NETWORK_STACK, service -> {
2950                             ServiceManager.addService(Context.TETHERING_SERVICE, service,
2951                                     false /* allowIsolated */,
2952                                     DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL);
2953                         });
2954             } catch (Throwable e) {
2955                 reportWtf("starting Tethering", e);
2956             }
2957             t.traceEnd();
2958 
2959             t.traceBegin("MakeCountryDetectionServiceReady");
2960             try {
2961                 if (countryDetectorF != null) {
2962                     countryDetectorF.systemRunning();
2963                 }
2964             } catch (Throwable e) {
2965                 reportWtf("Notifying CountryDetectorService running", e);
2966             }
2967             t.traceEnd();
2968             t.traceBegin("MakeNetworkTimeUpdateReady");
2969             try {
2970                 if (networkTimeUpdaterF != null) {
2971                     networkTimeUpdaterF.systemRunning();
2972                 }
2973             } catch (Throwable e) {
2974                 reportWtf("Notifying NetworkTimeService running", e);
2975             }
2976             t.traceEnd();
2977             t.traceBegin("MakeInputManagerServiceReady");
2978             try {
2979                 // TODO(BT) Pass parameter to input manager
2980                 if (inputManagerF != null) {
2981                     inputManagerF.systemRunning();
2982                 }
2983             } catch (Throwable e) {
2984                 reportWtf("Notifying InputManagerService running", e);
2985             }
2986             t.traceEnd();
2987             t.traceBegin("MakeTelephonyRegistryReady");
2988             try {
2989                 if (telephonyRegistryF != null) {
2990                     telephonyRegistryF.systemRunning();
2991                 }
2992             } catch (Throwable e) {
2993                 reportWtf("Notifying TelephonyRegistry running", e);
2994             }
2995             t.traceEnd();
2996             t.traceBegin("MakeMediaRouterServiceReady");
2997             try {
2998                 if (mediaRouterF != null) {
2999                     mediaRouterF.systemRunning();
3000                 }
3001             } catch (Throwable e) {
3002                 reportWtf("Notifying MediaRouterService running", e);
3003             }
3004             t.traceEnd();
3005             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
3006                 t.traceBegin("MakeMmsServiceReady");
3007                 try {
3008                     if (mmsServiceF != null) mmsServiceF.systemRunning();
3009                 } catch (Throwable e) {
3010                     reportWtf("Notifying MmsService running", e);
3011                 }
3012                 t.traceEnd();
3013             }
3014 
3015             t.traceBegin("IncidentDaemonReady");
3016             try {
3017                 // TODO: Switch from checkService to getService once it's always
3018                 // in the build and should reliably be there.
3019                 final IIncidentManager incident = IIncidentManager.Stub.asInterface(
3020                         ServiceManager.getService(Context.INCIDENT_SERVICE));
3021                 if (incident != null) {
3022                     incident.systemRunning();
3023                 }
3024             } catch (Throwable e) {
3025                 reportWtf("Notifying incident daemon running", e);
3026             }
3027             t.traceEnd();
3028 
3029             if (mIncrementalServiceHandle != 0) {
3030                 t.traceBegin("MakeIncrementalServiceReady");
3031                 setIncrementalServiceSystemReady(mIncrementalServiceHandle);
3032                 t.traceEnd();
3033             }
3034 
3035             t.traceBegin("OdsignStatsLogger");
3036             try {
3037                 OdsignStatsLogger.triggerStatsWrite();
3038             } catch (Throwable e) {
3039                 reportWtf("Triggering OdsignStatsLogger", e);
3040             }
3041             t.traceEnd();
3042         }, t);
3043 
3044         t.traceBegin("StartSystemUI");
3045         try {
3046             startSystemUi(context, windowManagerF);
3047         } catch (Throwable e) {
3048             reportWtf("starting System UI", e);
3049         }
3050         t.traceEnd();
3051 
3052         t.traceEnd(); // startOtherServices
3053     }
3054 
3055     /**
3056      * Starts system services defined in apexes.
3057      *
3058      * <p>Apex services must be the last category of services to start. No other service must be
3059      * starting after this point. This is to prevent unnecessary stability issues when these apexes
3060      * are updated outside of OTA; and to avoid breaking dependencies from system into apexes.
3061      */
startApexServices(@onNull TimingsTraceAndSlog t)3062     private void startApexServices(@NonNull TimingsTraceAndSlog t) {
3063         t.traceBegin("startApexServices");
3064         // TODO(b/192880996): get the list from "android" package, once the manifest entries
3065         // are migrated to system manifest.
3066         List<ApexSystemServiceInfo> services = ApexManager.getInstance().getApexSystemServices();
3067         for (ApexSystemServiceInfo info : services) {
3068             String name = info.getName();
3069             String jarPath = info.getJarPath();
3070             t.traceBegin("starting " + name);
3071             if (TextUtils.isEmpty(jarPath)) {
3072                 mSystemServiceManager.startService(name);
3073             } else {
3074                 mSystemServiceManager.startServiceFromJar(name, jarPath);
3075             }
3076             t.traceEnd();
3077         }
3078 
3079         // make sure no other services are started after this point
3080         mSystemServiceManager.sealStartedServices();
3081 
3082         t.traceEnd(); // startApexServices
3083     }
3084 
deviceHasConfigString(@onNull Context context, @StringRes int resId)3085     private boolean deviceHasConfigString(@NonNull Context context, @StringRes int resId) {
3086         String serviceName = context.getString(resId);
3087         return !TextUtils.isEmpty(serviceName);
3088     }
3089 
startSystemCaptionsManagerService(@onNull Context context, @NonNull TimingsTraceAndSlog t)3090     private void startSystemCaptionsManagerService(@NonNull Context context,
3091             @NonNull TimingsTraceAndSlog t) {
3092         if (!deviceHasConfigString(context, R.string.config_defaultSystemCaptionsManagerService)) {
3093             Slog.d(TAG, "SystemCaptionsManagerService disabled because resource is not overlaid");
3094             return;
3095         }
3096 
3097         t.traceBegin("StartSystemCaptionsManagerService");
3098         mSystemServiceManager.startService(SYSTEM_CAPTIONS_MANAGER_SERVICE_CLASS);
3099         t.traceEnd();
3100     }
3101 
startTextToSpeechManagerService(@onNull Context context, @NonNull TimingsTraceAndSlog t)3102     private void startTextToSpeechManagerService(@NonNull Context context,
3103             @NonNull TimingsTraceAndSlog t) {
3104         t.traceBegin("StartTextToSpeechManagerService");
3105         mSystemServiceManager.startService(TEXT_TO_SPEECH_MANAGER_SERVICE_CLASS);
3106         t.traceEnd();
3107     }
3108 
startContentCaptureService(@onNull Context context, @NonNull TimingsTraceAndSlog t)3109     private void startContentCaptureService(@NonNull Context context,
3110             @NonNull TimingsTraceAndSlog t) {
3111         // First check if it was explicitly enabled by DeviceConfig
3112         boolean explicitlyEnabled = false;
3113         String settings = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_CONTENT_CAPTURE,
3114                 ContentCaptureManager.DEVICE_CONFIG_PROPERTY_SERVICE_EXPLICITLY_ENABLED);
3115         if (settings != null && !settings.equalsIgnoreCase("default")) {
3116             explicitlyEnabled = Boolean.parseBoolean(settings);
3117             if (explicitlyEnabled) {
3118                 Slog.d(TAG, "ContentCaptureService explicitly enabled by DeviceConfig");
3119             } else {
3120                 Slog.d(TAG, "ContentCaptureService explicitly disabled by DeviceConfig");
3121                 return;
3122             }
3123         }
3124 
3125         // Then check if OEM overlaid the resource that defines the service.
3126         if (!explicitlyEnabled) {
3127             if (!deviceHasConfigString(context, R.string.config_defaultContentCaptureService)) {
3128                 Slog.d(TAG, "ContentCaptureService disabled because resource is not overlaid");
3129                 return;
3130             }
3131         }
3132 
3133         t.traceBegin("StartContentCaptureService");
3134         mSystemServiceManager.startService(CONTENT_CAPTURE_MANAGER_SERVICE_CLASS);
3135 
3136         ContentCaptureManagerInternal ccmi =
3137                 LocalServices.getService(ContentCaptureManagerInternal.class);
3138         if (ccmi != null && mActivityManagerService != null) {
3139             mActivityManagerService.setContentCaptureManager(ccmi);
3140         }
3141 
3142         t.traceEnd();
3143     }
3144 
startAttentionService(@onNull Context context, @NonNull TimingsTraceAndSlog t)3145     private void startAttentionService(@NonNull Context context, @NonNull TimingsTraceAndSlog t) {
3146         if (!AttentionManagerService.isServiceConfigured(context)) {
3147             Slog.d(TAG, "AttentionService is not configured on this device");
3148             return;
3149         }
3150 
3151         t.traceBegin("StartAttentionManagerService");
3152         mSystemServiceManager.startService(AttentionManagerService.class);
3153         t.traceEnd();
3154     }
3155 
startRotationResolverService(@onNull Context context, @NonNull TimingsTraceAndSlog t)3156     private void startRotationResolverService(@NonNull Context context,
3157             @NonNull TimingsTraceAndSlog t) {
3158         if (!RotationResolverManagerService.isServiceConfigured(context)) {
3159             Slog.d(TAG, "RotationResolverService is not configured on this device");
3160             return;
3161         }
3162 
3163         t.traceBegin("StartRotationResolverService");
3164         mSystemServiceManager.startService(RotationResolverManagerService.class);
3165         t.traceEnd();
3166 
3167     }
3168 
startAmbientContextService(@onNull TimingsTraceAndSlog t)3169     private void startAmbientContextService(@NonNull TimingsTraceAndSlog t) {
3170         t.traceBegin("StartAmbientContextService");
3171         mSystemServiceManager.startService(AmbientContextManagerService.class);
3172         t.traceEnd();
3173     }
3174 
startSystemUi(Context context, WindowManagerService windowManager)3175     private static void startSystemUi(Context context, WindowManagerService windowManager) {
3176         PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
3177         Intent intent = new Intent();
3178         intent.setComponent(pm.getSystemUiServiceComponent());
3179         intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
3180         //Slog.d(TAG, "Starting service: " + intent);
3181         context.startServiceAsUser(intent, UserHandle.SYSTEM);
3182         windowManager.onSystemUiStarted();
3183     }
3184 
3185     /**
3186      * Handle the serious errors during early system boot, used by {@link Log} via
3187      * {@link com.android.internal.os.RuntimeInit}.
3188      */
handleEarlySystemWtf(final IBinder app, final String tag, boolean system, final ApplicationErrorReport.ParcelableCrashInfo crashInfo, int immediateCallerPid)3189     private static boolean handleEarlySystemWtf(final IBinder app, final String tag, boolean system,
3190             final ApplicationErrorReport.ParcelableCrashInfo crashInfo, int immediateCallerPid) {
3191         final String processName = "system_server";
3192         final int myPid = myPid();
3193 
3194         com.android.server.am.EventLogTags.writeAmWtf(UserHandle.getUserId(SYSTEM_UID), myPid,
3195                 processName, -1, tag, crashInfo.exceptionMessage);
3196 
3197         FrameworkStatsLog.write(FrameworkStatsLog.WTF_OCCURRED, SYSTEM_UID, tag, processName,
3198                 myPid, ServerProtoEnums.SYSTEM_SERVER);
3199 
3200         synchronized (SystemServer.class) {
3201             if (sPendingWtfs == null) {
3202                 sPendingWtfs = new LinkedList<>();
3203             }
3204             sPendingWtfs.add(new Pair<>(tag, crashInfo));
3205         }
3206         return false;
3207     }
3208 
3209 }
3210