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