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