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