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