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