Home | History | Annotate | Download | only in server
      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 android.app.ActivityThread;
     20 import android.app.INotificationManager;
     21 import android.app.usage.UsageStatsManagerInternal;
     22 import android.content.ComponentName;
     23 import android.content.ContentResolver;
     24 import android.content.Context;
     25 import android.content.Intent;
     26 import android.content.pm.PackageManager;
     27 import android.content.res.Configuration;
     28 import android.content.res.Resources.Theme;
     29 import android.os.BaseBundle;
     30 import android.os.Binder;
     31 import android.os.Build;
     32 import android.os.Environment;
     33 import android.os.FactoryTest;
     34 import android.os.FileUtils;
     35 import android.os.IIncidentManager;
     36 import android.os.Looper;
     37 import android.os.PowerManager;
     38 import android.os.Process;
     39 import android.os.RemoteException;
     40 import android.os.ServiceManager;
     41 import android.os.StrictMode;
     42 import android.os.SystemClock;
     43 import android.os.SystemProperties;
     44 import android.os.Trace;
     45 import android.os.UserHandle;
     46 import android.os.storage.IStorageManager;
     47 import android.util.BootTimingsTraceLog;
     48 import android.util.DisplayMetrics;
     49 import android.util.EventLog;
     50 import android.util.Slog;
     51 import android.view.WindowManager;
     52 
     53 import com.android.internal.R;
     54 import com.android.internal.app.NightDisplayController;
     55 import com.android.internal.logging.MetricsLogger;
     56 import com.android.internal.notification.SystemNotificationChannels;
     57 import com.android.internal.os.BinderInternal;
     58 import com.android.internal.os.SamplingProfilerIntegration;
     59 import com.android.internal.util.EmergencyAffordanceManager;
     60 import com.android.internal.util.ConcurrentUtils;
     61 import com.android.internal.widget.ILockSettings;
     62 import com.android.server.accessibility.AccessibilityManagerService;
     63 import com.android.server.am.ActivityManagerService;
     64 import com.android.server.audio.AudioService;
     65 import com.android.server.camera.CameraServiceProxy;
     66 import com.android.server.clipboard.ClipboardService;
     67 import com.android.server.connectivity.IpConnectivityMetrics;
     68 import com.android.server.coverage.CoverageService;
     69 import com.android.server.devicepolicy.DevicePolicyManagerService;
     70 import com.android.server.display.DisplayManagerService;
     71 import com.android.server.display.NightDisplayService;
     72 import com.android.server.dreams.DreamManagerService;
     73 import com.android.server.emergency.EmergencyAffordanceService;
     74 import com.android.server.fingerprint.FingerprintService;
     75 import com.android.server.hdmi.HdmiControlService;
     76 import com.android.server.input.InputManagerService;
     77 import com.android.server.job.JobSchedulerService;
     78 import com.android.server.lights.LightsService;
     79 import com.android.server.media.MediaResourceMonitorService;
     80 import com.android.server.media.MediaRouterService;
     81 import com.android.server.media.MediaSessionService;
     82 import com.android.server.media.projection.MediaProjectionManagerService;
     83 import com.android.server.net.NetworkPolicyManagerService;
     84 import com.android.server.net.NetworkStatsService;
     85 import com.android.server.notification.NotificationManagerService;
     86 import com.android.server.om.OverlayManagerService;
     87 import com.android.server.os.DeviceIdentifiersPolicyService;
     88 import com.android.server.os.SchedulingPolicyService;
     89 import com.android.server.pm.BackgroundDexOptService;
     90 import com.android.server.pm.Installer;
     91 import com.android.server.pm.LauncherAppsService;
     92 import com.android.server.pm.OtaDexoptService;
     93 import com.android.server.pm.PackageManagerService;
     94 import com.android.server.pm.ShortcutService;
     95 import com.android.server.pm.UserManagerService;
     96 import com.android.server.policy.PhoneWindowManager;
     97 import com.android.server.power.PowerManagerService;
     98 import com.android.server.power.ShutdownThread;
     99 import com.android.server.restrictions.RestrictionsManagerService;
    100 import com.android.server.retaildemo.RetailDemoModeService;
    101 import com.android.server.security.KeyAttestationApplicationIdProviderService;
    102 import com.android.server.security.KeyChainSystemService;
    103 import com.android.server.soundtrigger.SoundTriggerService;
    104 import com.android.server.statusbar.StatusBarManagerService;
    105 import com.android.server.storage.DeviceStorageMonitorService;
    106 import com.android.server.telecom.TelecomLoaderService;
    107 import com.android.server.trust.TrustManagerService;
    108 import com.android.server.tv.TvInputManagerService;
    109 import com.android.server.tv.TvRemoteService;
    110 import com.android.server.twilight.TwilightService;
    111 import com.android.server.usage.UsageStatsService;
    112 import com.android.server.vr.VrManagerService;
    113 import com.android.server.webkit.WebViewUpdateService;
    114 import com.android.server.wm.WindowManagerService;
    115 
    116 import dalvik.system.VMRuntime;
    117 
    118 import java.io.File;
    119 import java.io.IOException;
    120 import java.util.Locale;
    121 import java.util.Timer;
    122 import java.util.TimerTask;
    123 import java.util.concurrent.CountDownLatch;
    124 import java.util.concurrent.Future;
    125 
    126 import static android.view.Display.DEFAULT_DISPLAY;
    127 
    128 public final class SystemServer {
    129     private static final String TAG = "SystemServer";
    130 
    131     // Tag for timing measurement of main thread.
    132     private static final String SYSTEM_SERVER_TIMING_TAG = "SystemServerTiming";
    133     // Tag for timing measurement of non-main asynchronous operations.
    134     private static final String SYSTEM_SERVER_TIMING_ASYNC_TAG = SYSTEM_SERVER_TIMING_TAG + "Async";
    135 
    136     private static final BootTimingsTraceLog BOOT_TIMINGS_TRACE_LOG
    137             = new BootTimingsTraceLog(SYSTEM_SERVER_TIMING_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
    138 
    139     private static final String ENCRYPTING_STATE = "trigger_restart_min_framework";
    140     private static final String ENCRYPTED_STATE = "1";
    141 
    142     private static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; // 1hr
    143 
    144     // The earliest supported time.  We pick one day into 1970, to
    145     // give any timezone code room without going into negative time.
    146     private static final long EARLIEST_SUPPORTED_TIME = 86400 * 1000;
    147 
    148     /*
    149      * Implementation class names. TODO: Move them to a codegen class or load
    150      * them from the build system somehow.
    151      */
    152     private static final String BACKUP_MANAGER_SERVICE_CLASS =
    153             "com.android.server.backup.BackupManagerService$Lifecycle";
    154     private static final String APPWIDGET_SERVICE_CLASS =
    155             "com.android.server.appwidget.AppWidgetService";
    156     private static final String VOICE_RECOGNITION_MANAGER_SERVICE_CLASS =
    157             "com.android.server.voiceinteraction.VoiceInteractionManagerService";
    158     private static final String PRINT_MANAGER_SERVICE_CLASS =
    159             "com.android.server.print.PrintManagerService";
    160     private static final String COMPANION_DEVICE_MANAGER_SERVICE_CLASS =
    161             "com.android.server.companion.CompanionDeviceManagerService";
    162     private static final String USB_SERVICE_CLASS =
    163             "com.android.server.usb.UsbService$Lifecycle";
    164     private static final String MIDI_SERVICE_CLASS =
    165             "com.android.server.midi.MidiService$Lifecycle";
    166     private static final String WIFI_SERVICE_CLASS =
    167             "com.android.server.wifi.WifiService";
    168     private static final String WIFI_AWARE_SERVICE_CLASS =
    169             "com.android.server.wifi.aware.WifiAwareService";
    170     private static final String WIFI_P2P_SERVICE_CLASS =
    171             "com.android.server.wifi.p2p.WifiP2pService";
    172     private static final String ETHERNET_SERVICE_CLASS =
    173             "com.android.server.ethernet.EthernetService";
    174     private static final String JOB_SCHEDULER_SERVICE_CLASS =
    175             "com.android.server.job.JobSchedulerService";
    176     private static final String LOCK_SETTINGS_SERVICE_CLASS =
    177             "com.android.server.LockSettingsService$Lifecycle";
    178     private static final String STORAGE_MANAGER_SERVICE_CLASS =
    179             "com.android.server.StorageManagerService$Lifecycle";
    180     private static final String STORAGE_STATS_SERVICE_CLASS =
    181             "com.android.server.usage.StorageStatsService$Lifecycle";
    182     private static final String SEARCH_MANAGER_SERVICE_CLASS =
    183             "com.android.server.search.SearchManagerService$Lifecycle";
    184     private static final String THERMAL_OBSERVER_CLASS =
    185             "com.google.android.clockwork.ThermalObserver";
    186     private static final String WEAR_CONNECTIVITY_SERVICE_CLASS =
    187             "com.google.android.clockwork.connectivity.WearConnectivityService";
    188     private static final String WEAR_DISPLAY_SERVICE_CLASS =
    189             "com.google.android.clockwork.display.WearDisplayService";
    190     private static final String WEAR_TIME_SERVICE_CLASS =
    191             "com.google.android.clockwork.time.WearTimeService";
    192     private static final String ACCOUNT_SERVICE_CLASS =
    193             "com.android.server.accounts.AccountManagerService$Lifecycle";
    194     private static final String CONTENT_SERVICE_CLASS =
    195             "com.android.server.content.ContentService$Lifecycle";
    196     private static final String WALLPAPER_SERVICE_CLASS =
    197             "com.android.server.wallpaper.WallpaperManagerService$Lifecycle";
    198     private static final String AUTO_FILL_MANAGER_SERVICE_CLASS =
    199             "com.android.server.autofill.AutofillManagerService";
    200 
    201     private static final String PERSISTENT_DATA_BLOCK_PROP = "ro.frp.pst";
    202 
    203     private static final String UNCRYPT_PACKAGE_FILE = "/cache/recovery/uncrypt_file";
    204     private static final String BLOCK_MAP_FILE = "/cache/recovery/block.map";
    205 
    206     // maximum number of binder threads used for system_server
    207     // will be higher than the system default
    208     private static final int sMaxBinderThreads = 31;
    209 
    210     /**
    211      * Default theme used by the system context. This is used to style
    212      * system-provided dialogs, such as the Power Off dialog, and other
    213      * visual content.
    214      */
    215     private static final int DEFAULT_SYSTEM_THEME =
    216             com.android.internal.R.style.Theme_DeviceDefault_System;
    217 
    218     private final int mFactoryTestMode;
    219     private Timer mProfilerSnapshotTimer;
    220 
    221     private Context mSystemContext;
    222     private SystemServiceManager mSystemServiceManager;
    223 
    224     // TODO: remove all of these references by improving dependency resolution and boot phases
    225     private PowerManagerService mPowerManagerService;
    226     private ActivityManagerService mActivityManagerService;
    227     private WebViewUpdateService mWebViewUpdateService;
    228     private DisplayManagerService mDisplayManagerService;
    229     private PackageManagerService mPackageManagerService;
    230     private PackageManager mPackageManager;
    231     private ContentResolver mContentResolver;
    232     private EntropyMixer mEntropyMixer;
    233 
    234     private boolean mOnlyCore;
    235     private boolean mFirstBoot;
    236     private final boolean mRuntimeRestart;
    237 
    238     private static final String START_SENSOR_SERVICE = "StartSensorService";
    239     private static final String START_HIDL_SERVICES = "StartHidlServices";
    240 
    241 
    242     private Future<?> mSensorServiceStart;
    243     private Future<?> mZygotePreload;
    244 
    245     /**
    246      * Start the sensor service. This is a blocking call and can take time.
    247      */
    248     private static native void startSensorService();
    249 
    250     /**
    251      * Start all HIDL services that are run inside the system server. This
    252      * may take some time.
    253      */
    254     private static native void startHidlServices();
    255 
    256     /**
    257      * The main entry point from zygote.
    258      */
    259     public static void main(String[] args) {
    260         new SystemServer().run();
    261     }
    262 
    263     public SystemServer() {
    264         // Check for factory test mode.
    265         mFactoryTestMode = FactoryTest.getMode();
    266         // Remember if it's runtime restart(when sys.boot_completed is already set) or reboot
    267         mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));
    268     }
    269 
    270     private void run() {
    271         try {
    272             traceBeginAndSlog("InitBeforeStartServices");
    273             // If a device's clock is before 1970 (before 0), a lot of
    274             // APIs crash dealing with negative numbers, notably
    275             // java.io.File#setLastModified, so instead we fake it and
    276             // hope that time from cell towers or NTP fixes it shortly.
    277             if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
    278                 Slog.w(TAG, "System clock is before 1970; setting to 1970.");
    279                 SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
    280             }
    281 
    282             //
    283             // Default the timezone property to GMT if not set.
    284             //
    285             String timezoneProperty =  SystemProperties.get("persist.sys.timezone");
    286             if (timezoneProperty == null || timezoneProperty.isEmpty()) {
    287                 Slog.w(TAG, "Timezone not set; setting to GMT.");
    288                 SystemProperties.set("persist.sys.timezone", "GMT");
    289             }
    290 
    291             // If the system has "persist.sys.language" and friends set, replace them with
    292             // "persist.sys.locale". Note that the default locale at this point is calculated
    293             // using the "-Duser.locale" command line flag. That flag is usually populated by
    294             // AndroidRuntime using the same set of system properties, but only the system_server
    295             // and system apps are allowed to set them.
    296             //
    297             // NOTE: Most changes made here will need an equivalent change to
    298             // core/jni/AndroidRuntime.cpp
    299             if (!SystemProperties.get("persist.sys.language").isEmpty()) {
    300                 final String languageTag = Locale.getDefault().toLanguageTag();
    301 
    302                 SystemProperties.set("persist.sys.locale", languageTag);
    303                 SystemProperties.set("persist.sys.language", "");
    304                 SystemProperties.set("persist.sys.country", "");
    305                 SystemProperties.set("persist.sys.localevar", "");
    306             }
    307 
    308             // The system server should never make non-oneway calls
    309             Binder.setWarnOnBlocking(true);
    310 
    311             // Here we go!
    312             Slog.i(TAG, "Entered the Android system server!");
    313             int uptimeMillis = (int) SystemClock.elapsedRealtime();
    314             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
    315             if (!mRuntimeRestart) {
    316                 MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
    317             }
    318 
    319             // In case the runtime switched since last boot (such as when
    320             // the old runtime was removed in an OTA), set the system
    321             // property so that it is in sync. We can | xq oqi't do this in
    322             // libnativehelper's JniInvocation::Init code where we already
    323             // had to fallback to a different runtime because it is
    324             // running as root and we need to be the system user to set
    325             // the property. http://b/11463182
    326             SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
    327 
    328             // Enable the sampling profiler.
    329             if (SamplingProfilerIntegration.isEnabled()) {
    330                 SamplingProfilerIntegration.start();
    331                 mProfilerSnapshotTimer = new Timer();
    332                 mProfilerSnapshotTimer.schedule(new TimerTask() {
    333                         @Override
    334                         public void run() {
    335                             SamplingProfilerIntegration.writeSnapshot("system_server", null);
    336                         }
    337                     }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
    338             }
    339 
    340             // Mmmmmm... more memory!
    341             VMRuntime.getRuntime().clearGrowthLimit();
    342 
    343             // The system server has to run all of the time, so it needs to be
    344             // as efficient as possible with its memory usage.
    345             VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
    346 
    347             // Some devices rely on runtime fingerprint generation, so make sure
    348             // we've defined it before booting further.
    349             Build.ensureFingerprintProperty();
    350 
    351             // Within the system server, it is an error to access Environment paths without
    352             // explicitly specifying a user.
    353             Environment.setUserRequired(true);
    354 
    355             // Within the system server, any incoming Bundles should be defused
    356             // to avoid throwing BadParcelableException.
    357             BaseBundle.setShouldDefuse(true);
    358 
    359             // Ensure binder calls into the system always run at foreground priority.
    360             BinderInternal.disableBackgroundScheduling(true);
    361 
    362             // Increase the number of binder threads in system_server
    363             BinderInternal.setMaxThreads(sMaxBinderThreads);
    364 
    365             // Prepare the main looper thread (this thread).
    366             android.os.Process.setThreadPriority(
    367                 android.os.Process.THREAD_PRIORITY_FOREGROUND);
    368             android.os.Process.setCanSelfBackground(false);
    369             Looper.prepareMainLooper();
    370 
    371             // Initialize native services.
    372             System.loadLibrary("android_servers");
    373 
    374             // Check whether we failed to shut down last time we tried.
    375             // This call may not return.
    376             performPendingShutdown();
    377 
    378             // Initialize the system context.
    379             createSystemContext();
    380 
    381             // Create the system service manager.
    382             mSystemServiceManager = new SystemServiceManager(mSystemContext);
    383             mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
    384             LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    385             // Prepare the thread pool for init tasks that can be parallelized
    386             SystemServerInitThreadPool.get();
    387         } finally {
    388             traceEnd();  // InitBeforeStartServices
    389         }
    390 
    391         // Start services.
    392         try {
    393             traceBeginAndSlog("StartServices");
    394             startBootstrapServices();
    395             startCoreServices();
    396             startOtherServices();
    397             SystemServerInitThreadPool.shutdown();
    398         } catch (Throwable ex) {
    399             Slog.e("System", "******************************************");
    400             Slog.e("System", "************ Failure starting system services", ex);
    401             throw ex;
    402         } finally {
    403             traceEnd();
    404         }
    405 
    406         // For debug builds, log event loop stalls to dropbox for analysis.
    407         if (StrictMode.conditionallyEnableDebugLogging()) {
    408             Slog.i(TAG, "Enabled StrictMode for system server main thread.");
    409         }
    410         if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
    411             int uptimeMillis = (int) SystemClock.elapsedRealtime();
    412             MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
    413             final int MAX_UPTIME_MILLIS = 60 * 1000;
    414             if (uptimeMillis > MAX_UPTIME_MILLIS) {
    415                 Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
    416                         "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
    417             }
    418         }
    419 
    420         // Loop forever.
    421         Looper.loop();
    422         throw new RuntimeException("Main thread loop unexpectedly exited");
    423     }
    424 
    425     private boolean isFirstBootOrUpgrade() {
    426         return mPackageManagerService.isFirstBoot() || mPackageManagerService.isUpgrade();
    427     }
    428 
    429     private void reportWtf(String msg, Throwable e) {
    430         Slog.w(TAG, "***********************************************");
    431         Slog.wtf(TAG, "BOOT FAILURE " + msg, e);
    432     }
    433 
    434     private void performPendingShutdown() {
    435         final String shutdownAction = SystemProperties.get(
    436                 ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
    437         if (shutdownAction != null && shutdownAction.length() > 0) {
    438             boolean reboot = (shutdownAction.charAt(0) == '1');
    439 
    440             final String reason;
    441             if (shutdownAction.length() > 1) {
    442                 reason = shutdownAction.substring(1, shutdownAction.length());
    443             } else {
    444                 reason = null;
    445             }
    446 
    447             // If it's a pending reboot into recovery to apply an update,
    448             // always make sure uncrypt gets executed properly when needed.
    449             // If '/cache/recovery/block.map' hasn't been created, stop the
    450             // reboot which will fail for sure, and get a chance to capture a
    451             // bugreport when that's still feasible. (Bug: 26444951)
    452             if (reason != null && reason.startsWith(PowerManager.REBOOT_RECOVERY_UPDATE)) {
    453                 File packageFile = new File(UNCRYPT_PACKAGE_FILE);
    454                 if (packageFile.exists()) {
    455                     String filename = null;
    456                     try {
    457                         filename = FileUtils.readTextFile(packageFile, 0, null);
    458                     } catch (IOException e) {
    459                         Slog.e(TAG, "Error reading uncrypt package file", e);
    460                     }
    461 
    462                     if (filename != null && filename.startsWith("/data")) {
    463                         if (!new File(BLOCK_MAP_FILE).exists()) {
    464                             Slog.e(TAG, "Can't find block map file, uncrypt failed or " +
    465                                        "unexpected runtime restart?");
    466                             return;
    467                         }
    468                     }
    469                 }
    470             }
    471             ShutdownThread.rebootOrShutdown(null, reboot, reason);
    472         }
    473     }
    474 
    475     private void createSystemContext() {
    476         ActivityThread activityThread = ActivityThread.systemMain();
    477         mSystemContext = activityThread.getSystemContext();
    478         mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
    479 
    480         final Context systemUiContext = activityThread.getSystemUiContext();
    481         systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
    482     }
    483 
    484     /**
    485      * Starts the small tangle of critical services that are needed to get
    486      * the system off the ground.  These services have complex mutual dependencies
    487      * which is why we initialize them all in one place here.  Unless your service
    488      * is also entwined in these dependencies, it should be initialized in one of
    489      * the other functions.
    490      */
    491     private void startBootstrapServices() {
    492         Slog.i(TAG, "Reading configuration...");
    493         final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
    494         traceBeginAndSlog(TAG_SYSTEM_CONFIG);
    495         SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
    496         traceEnd();
    497 
    498         // Wait for installd to finish starting up so that it has a chance to
    499         // create critical directories such as /data/user with the appropriate
    500         // permissions.  We need this to complete before we initialize other services.
    501         traceBeginAndSlog("StartInstaller");
    502         Installer installer = mSystemServiceManager.startService(Installer.class);
    503         traceEnd();
    504 
    505         // In some cases after launching an app we need to access device identifiers,
    506         // therefore register the device identifier policy before the activity manager.
    507         traceBeginAndSlog("DeviceIdentifiersPolicyService");
    508         mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
    509         traceEnd();
    510 
    511         // Activity manager runs the show.
    512         traceBeginAndSlog("StartActivityManager");
    513         mActivityManagerService = mSystemServiceManager.startService(
    514                 ActivityManagerService.Lifecycle.class).getService();
    515         mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    516         mActivityManagerService.setInstaller(installer);
    517         traceEnd();
    518 
    519         // Power manager needs to be started early because other services need it.
    520         // Native daemons may be watching for it to be registered so it must be ready
    521         // to handle incoming binder calls immediately (including being able to verify
    522         // the permissions for those calls).
    523         traceBeginAndSlog("StartPowerManager");
    524         mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
    525         traceEnd();
    526 
    527         // Now that the power manager has been started, let the activity manager
    528         // initialize power management features.
    529         traceBeginAndSlog("InitPowerManagement");
    530         mActivityManagerService.initPowerManagement();
    531         traceEnd();
    532 
    533         // Bring up recovery system in case a rescue party needs a reboot
    534         if (!SystemProperties.getBoolean("config.disable_noncore", false)) {
    535             traceBeginAndSlog("StartRecoverySystemService");
    536             mSystemServiceManager.startService(RecoverySystemService.class);
    537             traceEnd();
    538         }
    539 
    540         // Now that we have the bare essentials of the OS up and running, take
    541         // note that we just booted, which might send out a rescue party if
    542         // we're stuck in a runtime restart loop.
    543         RescueParty.noteBoot(mSystemContext);
    544 
    545         // Manages LEDs and display backlight so we need it to bring up the display.
    546         traceBeginAndSlog("StartLightsService");
    547         mSystemServiceManager.startService(LightsService.class);
    548         traceEnd();
    549 
    550         // Display manager is needed to provide display metrics before package manager
    551         // starts up.
    552         traceBeginAndSlog("StartDisplayManager");
    553         mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
    554         traceEnd();
    555 
    556         // We need the default display before we can initialize the package manager.
    557         traceBeginAndSlog("WaitForDisplay");
    558         mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
    559         traceEnd();
    560 
    561         // Only run "core" apps if we're encrypting the device.
    562         String cryptState = SystemProperties.get("vold.decrypt");
    563         if (ENCRYPTING_STATE.equals(cryptState)) {
    564             Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
    565             mOnlyCore = true;
    566         } else if (ENCRYPTED_STATE.equals(cryptState)) {
    567             Slog.w(TAG, "Device encrypted - only parsing core apps");
    568             mOnlyCore = true;
    569         }
    570 
    571         // Start the package manager.
    572         if (!mRuntimeRestart) {
    573             MetricsLogger.histogram(null, "boot_package_manager_init_start",
    574                     (int) SystemClock.elapsedRealtime());
    575         }
    576         traceBeginAndSlog("StartPackageManagerService");
    577         mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
    578                 mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    579         mFirstBoot = mPackageManagerService.isFirstBoot();
    580         mPackageManager = mSystemContext.getPackageManager();
    581         traceEnd();
    582         if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
    583             MetricsLogger.histogram(null, "boot_package_manager_init_ready",
    584                     (int) SystemClock.elapsedRealtime());
    585         }
    586         // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
    587         // A/B artifacts after boot, before anything else might touch/need them.
    588         // Note: this isn't needed during decryption (we don't have /data anyways).
    589         if (!mOnlyCore) {
    590             boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
    591                     false);
    592             if (!disableOtaDexopt) {
    593                 traceBeginAndSlog("StartOtaDexOptService");
    594                 try {
    595                     OtaDexoptService.main(mSystemContext, mPackageManagerService);
    596                 } catch (Throwable e) {
    597                     reportWtf("starting OtaDexOptService", e);
    598                 } finally {
    599                     traceEnd();
    600                 }
    601             }
    602         }
    603 
    604         traceBeginAndSlog("StartUserManagerService");
    605         mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
    606         traceEnd();
    607 
    608         // Initialize attribute cache used to cache resources from packages.
    609         traceBeginAndSlog("InitAttributerCache");
    610         AttributeCache.init(mSystemContext);
    611         traceEnd();
    612 
    613         // Set up the Application instance for the system process and get started.
    614         traceBeginAndSlog("SetSystemProcess");
    615         mActivityManagerService.setSystemProcess();
    616         traceEnd();
    617 
    618         // DisplayManagerService needs to setup android.display scheduling related policies
    619         // since setSystemProcess() would have overridden policies due to setProcessGroup
    620         mDisplayManagerService.setupSchedulerPolicies();
    621 
    622         // Manages Overlay packages
    623         traceBeginAndSlog("StartOverlayManagerService");
    624         mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));
    625         traceEnd();
    626 
    627         // The sensor service needs access to package manager service, app ops
    628         // service, and permissions service, therefore we start it after them.
    629         // Start sensor service in a separate thread. Completion should be checked
    630         // before using it.
    631         mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
    632             BootTimingsTraceLog traceLog = new BootTimingsTraceLog(
    633                     SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
    634             traceLog.traceBegin(START_SENSOR_SERVICE);
    635             startSensorService();
    636             traceLog.traceEnd();
    637         }, START_SENSOR_SERVICE);
    638     }
    639 
    640     /**
    641      * Starts some essential services that are not tangled up in the bootstrap process.
    642      */
    643     private void startCoreServices() {
    644         // Records errors and logs, for example wtf()
    645         traceBeginAndSlog("StartDropBoxManager");
    646         mSystemServiceManager.startService(DropBoxManagerService.class);
    647         traceEnd();
    648 
    649         traceBeginAndSlog("StartBatteryService");
    650         // Tracks the battery level.  Requires LightService.
    651         mSystemServiceManager.startService(BatteryService.class);
    652         traceEnd();
    653 
    654         // Tracks application usage stats.
    655         traceBeginAndSlog("StartUsageService");
    656         mSystemServiceManager.startService(UsageStatsService.class);
    657         mActivityManagerService.setUsageStatsManager(
    658                 LocalServices.getService(UsageStatsManagerInternal.class));
    659         traceEnd();
    660 
    661         // Tracks whether the updatable WebView is in a ready state and watches for update installs.
    662         traceBeginAndSlog("StartWebViewUpdateService");
    663         mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
    664         traceEnd();
    665     }
    666 
    667     /**
    668      * Starts a miscellaneous grab bag of stuff that has yet to be refactored
    669      * and organized.
    670      */
    671     private void startOtherServices() {
    672         final Context context = mSystemContext;
    673         VibratorService vibrator = null;
    674         IStorageManager storageManager = null;
    675         NetworkManagementService networkManagement = null;
    676         NetworkStatsService networkStats = null;
    677         NetworkPolicyManagerService networkPolicy = null;
    678         ConnectivityService connectivity = null;
    679         NetworkScoreService networkScore = null;
    680         NsdService serviceDiscovery= null;
    681         WindowManagerService wm = null;
    682         SerialService serial = null;
    683         NetworkTimeUpdateService networkTimeUpdater = null;
    684         CommonTimeManagementService commonTimeMgmtService = null;
    685         InputManagerService inputManager = null;
    686         TelephonyRegistry telephonyRegistry = null;
    687         ConsumerIrService consumerIr = null;
    688         MmsServiceBroker mmsService = null;
    689         HardwarePropertiesManagerService hardwarePropertiesService = null;
    690 
    691         boolean disableStorage = SystemProperties.getBoolean("config.disable_storage", false);
    692         boolean disableBluetooth = SystemProperties.getBoolean("config.disable_bluetooth", false);
    693         boolean disableLocation = SystemProperties.getBoolean("config.disable_location", false);
    694         boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui", false);
    695         boolean disableNonCoreServices = SystemProperties.getBoolean("config.disable_noncore", false);
    696         boolean disableNetwork = SystemProperties.getBoolean("config.disable_network", false);
    697         boolean disableNetworkTime = SystemProperties.getBoolean("config.disable_networktime", false);
    698         boolean disableRtt = SystemProperties.getBoolean("config.disable_rtt", false);
    699         boolean disableMediaProjection = SystemProperties.getBoolean("config.disable_mediaproj",
    700                 false);
    701         boolean disableSerial = SystemProperties.getBoolean("config.disable_serial", false);
    702         boolean disableSearchManager = SystemProperties.getBoolean("config.disable_searchmanager",
    703                 false);
    704         boolean disableTrustManager = SystemProperties.getBoolean("config.disable_trustmanager",
    705                 false);
    706         boolean disableTextServices = SystemProperties.getBoolean("config.disable_textservices",
    707                 false);
    708         boolean disableSamplingProfiler = SystemProperties.getBoolean("config.disable_samplingprof",
    709                 false);
    710         boolean disableConsumerIr = SystemProperties.getBoolean("config.disable_consumerir", false);
    711         boolean disableVrManager = SystemProperties.getBoolean("config.disable_vrmanager", false);
    712         boolean disableCameraService = SystemProperties.getBoolean("config.disable_cameraservice",
    713                 false);
    714 
    715         boolean isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1");
    716 
    717         // For debugging RescueParty
    718         if (Build.IS_DEBUGGABLE && SystemProperties.getBoolean("debug.crash_system", false)) {
    719             throw new RuntimeException();
    720         }
    721 
    722         try {
    723             final String SECONDARY_ZYGOTE_PRELOAD = "SecondaryZygotePreload";
    724             // We start the preload ~1s before the webview factory preparation, to
    725             // ensure that it completes before the 32 bit relro process is forked
    726             // from the zygote. In the event that it takes too long, the webview
    727             // RELRO process will block, but it will do so without holding any locks.
    728             mZygotePreload = SystemServerInitThreadPool.get().submit(() -> {
    729                 try {
    730                     Slog.i(TAG, SECONDARY_ZYGOTE_PRELOAD);
    731                     BootTimingsTraceLog traceLog = new BootTimingsTraceLog(
    732                             SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
    733                     traceLog.traceBegin(SECONDARY_ZYGOTE_PRELOAD);
    734                     if (!Process.zygoteProcess.preloadDefault(Build.SUPPORTED_32_BIT_ABIS[0])) {
    735                         Slog.e(TAG, "Unable to preload default resources");
    736                     }
    737                     traceLog.traceEnd();
    738                 } catch (Exception ex) {
    739                     Slog.e(TAG, "Exception preloading default resources", ex);
    740                 }
    741             }, SECONDARY_ZYGOTE_PRELOAD);
    742 
    743             traceBeginAndSlog("StartKeyAttestationApplicationIdProviderService");
    744             ServiceManager.addService("sec_key_att_app_id_provider",
    745                     new KeyAttestationApplicationIdProviderService(context));
    746             traceEnd();
    747 
    748             traceBeginAndSlog("StartKeyChainSystemService");
    749             mSystemServiceManager.startService(KeyChainSystemService.class);
    750             traceEnd();
    751 
    752             traceBeginAndSlog("StartSchedulingPolicyService");
    753             ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
    754             traceEnd();
    755 
    756             traceBeginAndSlog("StartTelecomLoaderService");
    757             mSystemServiceManager.startService(TelecomLoaderService.class);
    758             traceEnd();
    759 
    760             traceBeginAndSlog("StartTelephonyRegistry");
    761             telephonyRegistry = new TelephonyRegistry(context);
    762             ServiceManager.addService("telephony.registry", telephonyRegistry);
    763             traceEnd();
    764 
    765             traceBeginAndSlog("StartEntropyMixer");
    766             mEntropyMixer = new EntropyMixer(context);
    767             traceEnd();
    768 
    769             mContentResolver = context.getContentResolver();
    770 
    771             if (!disableCameraService) {
    772                 Slog.i(TAG, "Camera Service Proxy");
    773                 traceBeginAndSlog("StartCameraServiceProxy");
    774                 mSystemServiceManager.startService(CameraServiceProxy.class);
    775                 traceEnd();
    776             }
    777 
    778             // The AccountManager must come before the ContentService
    779             traceBeginAndSlog("StartAccountManagerService");
    780             mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
    781             traceEnd();
    782 
    783             traceBeginAndSlog("StartContentService");
    784             mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);
    785             traceEnd();
    786 
    787             traceBeginAndSlog("InstallSystemProviders");
    788             mActivityManagerService.installSystemProviders();
    789             traceEnd();
    790 
    791             traceBeginAndSlog("StartVibratorService");
    792             vibrator = new VibratorService(context);
    793             ServiceManager.addService("vibrator", vibrator);
    794             traceEnd();
    795 
    796             if (!disableConsumerIr) {
    797                 traceBeginAndSlog("StartConsumerIrService");
    798                 consumerIr = new ConsumerIrService(context);
    799                 ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);
    800                 traceEnd();
    801             }
    802 
    803             traceBeginAndSlog("StartAlarmManagerService");
    804             mSystemServiceManager.startService(AlarmManagerService.class);
    805             traceEnd();
    806 
    807             traceBeginAndSlog("InitWatchdog");
    808             final Watchdog watchdog = Watchdog.getInstance();
    809             watchdog.init(context, mActivityManagerService);
    810             traceEnd();
    811 
    812             traceBeginAndSlog("StartInputManagerService");
    813             inputManager = new InputManagerService(context);
    814             traceEnd();
    815 
    816             traceBeginAndSlog("StartWindowManagerService");
    817             // WMS needs sensor service ready
    818             ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
    819             mSensorServiceStart = null;
    820             wm = WindowManagerService.main(context, inputManager,
    821                     mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
    822                     !mFirstBoot, mOnlyCore, new PhoneWindowManager());
    823             ServiceManager.addService(Context.WINDOW_SERVICE, wm);
    824             ServiceManager.addService(Context.INPUT_SERVICE, inputManager);
    825             traceEnd();
    826 
    827             // Start receiving calls from HIDL services. Start in in a separate thread
    828             // because it need to connect to SensorManager. This have to start
    829             // after START_SENSOR_SERVICE is done.
    830             SystemServerInitThreadPool.get().submit(() -> {
    831                 traceBeginAndSlog(START_HIDL_SERVICES);
    832                 startHidlServices();
    833                 traceEnd();
    834             }, START_HIDL_SERVICES);
    835 
    836             if (!disableVrManager) {
    837                 traceBeginAndSlog("StartVrManagerService");
    838                 mSystemServiceManager.startService(VrManagerService.class);
    839                 traceEnd();
    840             }
    841 
    842             traceBeginAndSlog("SetWindowManagerService");
    843             mActivityManagerService.setWindowManager(wm);
    844             traceEnd();
    845 
    846             traceBeginAndSlog("StartInputManager");
    847             inputManager.setWindowManagerCallbacks(wm.getInputMonitor());
    848             inputManager.start();
    849             traceEnd();
    850 
    851             // TODO: Use service dependencies instead.
    852             traceBeginAndSlog("DisplayManagerWindowManagerAndInputReady");
    853             mDisplayManagerService.windowManagerAndInputReady();
    854             traceEnd();
    855 
    856             // Skip Bluetooth if we have an emulator kernel
    857             // TODO: Use a more reliable check to see if this product should
    858             // support Bluetooth - see bug 988521
    859             if (isEmulator) {
    860                 Slog.i(TAG, "No Bluetooth Service (emulator)");
    861             } else if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
    862                 Slog.i(TAG, "No Bluetooth Service (factory test)");
    863             } else if (!context.getPackageManager().hasSystemFeature
    864                        (PackageManager.FEATURE_BLUETOOTH)) {
    865                 Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");
    866             } else if (disableBluetooth) {
    867                 Slog.i(TAG, "Bluetooth Service disabled by config");
    868             } else {
    869                 traceBeginAndSlog("StartBluetoothService");
    870                 mSystemServiceManager.startService(BluetoothService.class);
    871                 traceEnd();
    872             }
    873 
    874             traceBeginAndSlog("IpConnectivityMetrics");
    875             mSystemServiceManager.startService(IpConnectivityMetrics.class);
    876             traceEnd();
    877 
    878             traceBeginAndSlog("PinnerService");
    879             mSystemServiceManager.startService(PinnerService.class);
    880             traceEnd();
    881         } catch (RuntimeException e) {
    882             Slog.e("System", "******************************************");
    883             Slog.e("System", "************ Failure starting core service", e);
    884         }
    885 
    886         StatusBarManagerService statusBar = null;
    887         INotificationManager notification = null;
    888         LocationManagerService location = null;
    889         CountryDetectorService countryDetector = null;
    890         ILockSettings lockSettings = null;
    891         MediaRouterService mediaRouter = null;
    892 
    893         // Bring up services needed for UI.
    894         if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
    895             traceBeginAndSlog("StartInputMethodManagerLifecycle");
    896             mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);
    897             traceEnd();
    898 
    899             traceBeginAndSlog("StartAccessibilityManagerService");
    900             try {
    901                 ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
    902                         new AccessibilityManagerService(context));
    903             } catch (Throwable e) {
    904                 reportWtf("starting Accessibility Manager", e);
    905             }
    906             traceEnd();
    907         }
    908 
    909         traceBeginAndSlog("MakeDisplayReady");
    910         try {
    911             wm.displayReady();
    912         } catch (Throwable e) {
    913             reportWtf("making display ready", e);
    914         }
    915         traceEnd();
    916 
    917         if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
    918             if (!disableStorage &&
    919                     !"0".equals(SystemProperties.get("system_init.startmountservice"))) {
    920                 traceBeginAndSlog("StartStorageManagerService");
    921                 try {
    922                     /*
    923                      * NotificationManagerService is dependant on StorageManagerService,
    924                      * (for media / usb notifications) so we must start StorageManagerService first.
    925                      */
    926                     mSystemServiceManager.startService(STORAGE_MANAGER_SERVICE_CLASS);
    927                     storageManager = IStorageManager.Stub.asInterface(
    928                             ServiceManager.getService("mount"));
    929                 } catch (Throwable e) {
    930                     reportWtf("starting StorageManagerService", e);
    931                 }
    932                 traceEnd();
    933 
    934                 traceBeginAndSlog("StartStorageStatsService");
    935                 try {
    936                     mSystemServiceManager.startService(STORAGE_STATS_SERVICE_CLASS);
    937                 } catch (Throwable e) {
    938                     reportWtf("starting StorageStatsService", e);
    939                 }
    940                 traceEnd();
    941             }
    942         }
    943 
    944         // We start this here so that we update our configuration to set watch or television
    945         // as appropriate.
    946         traceBeginAndSlog("StartUiModeManager");
    947         mSystemServiceManager.startService(UiModeManagerService.class);
    948         traceEnd();
    949 
    950         if (!mOnlyCore) {
    951             traceBeginAndSlog("UpdatePackagesIfNeeded");
    952             try {
    953                 mPackageManagerService.updatePackagesIfNeeded();
    954             } catch (Throwable e) {
    955                 reportWtf("update packages", e);
    956             }
    957             traceEnd();
    958         }
    959 
    960         traceBeginAndSlog("PerformFstrimIfNeeded");
    961         try {
    962             mPackageManagerService.performFstrimIfNeeded();
    963         } catch (Throwable e) {
    964             reportWtf("performing fstrim", e);
    965         }
    966         traceEnd();
    967 
    968         if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
    969             if (!disableNonCoreServices) {
    970                 traceBeginAndSlog("StartLockSettingsService");
    971                 try {
    972                     mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);
    973                     lockSettings = ILockSettings.Stub.asInterface(
    974                             ServiceManager.getService("lock_settings"));
    975                 } catch (Throwable e) {
    976                     reportWtf("starting LockSettingsService service", e);
    977                 }
    978                 traceEnd();
    979 
    980                 if (!SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("")) {
    981                     traceBeginAndSlog("StartPersistentDataBlock");
    982                     mSystemServiceManager.startService(PersistentDataBlockService.class);
    983                     traceEnd();
    984 
    985                     // Implementation depends on persistent data block
    986                     traceBeginAndSlog("StartOemLockService");
    987                     mSystemServiceManager.startService(OemLockService.class);
    988                     traceEnd();
    989                 }
    990 
    991                 traceBeginAndSlog("StartDeviceIdleController");
    992                 mSystemServiceManager.startService(DeviceIdleController.class);
    993                 traceEnd();
    994 
    995                 // Always start the Device Policy Manager, so that the API is compatible with
    996                 // API8.
    997                 traceBeginAndSlog("StartDevicePolicyManager");
    998                 mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class);
    999                 traceEnd();
   1000             }
   1001 
   1002             if (!disableSystemUI) {
   1003                 traceBeginAndSlog("StartStatusBarManagerService");
   1004                 try {
   1005                     statusBar = new StatusBarManagerService(context, wm);
   1006                     ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
   1007                 } catch (Throwable e) {
   1008                     reportWtf("starting StatusBarManagerService", e);
   1009                 }
   1010                 traceEnd();
   1011             }
   1012 
   1013             if (!disableNonCoreServices) {
   1014                 traceBeginAndSlog("StartClipboardService");
   1015                 mSystemServiceManager.startService(ClipboardService.class);
   1016                 traceEnd();
   1017             }
   1018 
   1019             if (!disableNetwork) {
   1020                 traceBeginAndSlog("StartNetworkManagementService");
   1021                 try {
   1022                     networkManagement = NetworkManagementService.create(context);
   1023                     ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
   1024                 } catch (Throwable e) {
   1025                     reportWtf("starting NetworkManagement Service", e);
   1026                 }
   1027                 traceEnd();
   1028             }
   1029 
   1030             if (!disableNonCoreServices && !disableTextServices) {
   1031                 traceBeginAndSlog("StartTextServicesManager");
   1032                 mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);
   1033                 traceEnd();
   1034             }
   1035 
   1036             if (!disableNetwork) {
   1037                 traceBeginAndSlog("StartNetworkScoreService");
   1038                 try {
   1039                     networkScore = new NetworkScoreService(context);
   1040                     ServiceManager.addService(Context.NETWORK_SCORE_SERVICE, networkScore);
   1041                 } catch (Throwable e) {
   1042                     reportWtf("starting Network Score Service", e);
   1043                 }
   1044                 traceEnd();
   1045 
   1046                 traceBeginAndSlog("StartNetworkStatsService");
   1047                 try {
   1048                     networkStats = NetworkStatsService.create(context, networkManagement);
   1049                     ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);
   1050                 } catch (Throwable e) {
   1051                     reportWtf("starting NetworkStats Service", e);
   1052                 }
   1053                 traceEnd();
   1054 
   1055                 traceBeginAndSlog("StartNetworkPolicyManagerService");
   1056                 try {
   1057                     networkPolicy = new NetworkPolicyManagerService(context,
   1058                             mActivityManagerService, networkStats, networkManagement);
   1059                     ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
   1060                 } catch (Throwable e) {
   1061                     reportWtf("starting NetworkPolicy Service", e);
   1062                 }
   1063                 traceEnd();
   1064 
   1065                 // Wifi Service must be started first for wifi-related services.
   1066                 traceBeginAndSlog("StartWifi");
   1067                 mSystemServiceManager.startService(WIFI_SERVICE_CLASS);
   1068                 traceEnd();
   1069                 traceBeginAndSlog("StartWifiScanning");
   1070                 mSystemServiceManager.startService(
   1071                         "com.android.server.wifi.scanner.WifiScanningService");
   1072                 traceEnd();
   1073 
   1074                 if (!disableRtt) {
   1075                     traceBeginAndSlog("StartWifiRtt");
   1076                     mSystemServiceManager.startService("com.android.server.wifi.RttService");
   1077                     traceEnd();
   1078                 }
   1079 
   1080                 if (context.getPackageManager().hasSystemFeature(
   1081                         PackageManager.FEATURE_WIFI_AWARE)) {
   1082                     traceBeginAndSlog("StartWifiAware");
   1083                     mSystemServiceManager.startService(WIFI_AWARE_SERVICE_CLASS);
   1084                     traceEnd();
   1085                 } else {
   1086                     Slog.i(TAG, "No Wi-Fi Aware Service (Aware support Not Present)");
   1087                 }
   1088 
   1089                 if (context.getPackageManager().hasSystemFeature(
   1090                         PackageManager.FEATURE_WIFI_DIRECT)) {
   1091                     traceBeginAndSlog("StartWifiP2P");
   1092                     mSystemServiceManager.startService(WIFI_P2P_SERVICE_CLASS);
   1093                     traceEnd();
   1094                 }
   1095 
   1096                 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) ||
   1097                     mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) {
   1098                     traceBeginAndSlog("StartEthernet");
   1099                     mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS);
   1100                     traceEnd();
   1101                 }
   1102 
   1103                 traceBeginAndSlog("StartConnectivityService");
   1104                 try {
   1105                     connectivity = new ConnectivityService(
   1106                             context, networkManagement, networkStats, networkPolicy);
   1107                     ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
   1108                     networkStats.bindConnectivityManager(connectivity);
   1109                     networkPolicy.bindConnectivityManager(connectivity);
   1110                 } catch (Throwable e) {
   1111                     reportWtf("starting Connectivity Service", e);
   1112                 }
   1113                 traceEnd();
   1114 
   1115                 traceBeginAndSlog("StartNsdService");
   1116                 try {
   1117                     serviceDiscovery = NsdService.create(context);
   1118                     ServiceManager.addService(
   1119                             Context.NSD_SERVICE, serviceDiscovery);
   1120                 } catch (Throwable e) {
   1121                     reportWtf("starting Service Discovery Service", e);
   1122                 }
   1123                 traceEnd();
   1124             }
   1125 
   1126             if (!disableNonCoreServices) {
   1127                 traceBeginAndSlog("StartUpdateLockService");
   1128                 try {
   1129                     ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
   1130                             new UpdateLockService(context));
   1131                 } catch (Throwable e) {
   1132                     reportWtf("starting UpdateLockService", e);
   1133                 }
   1134                 traceEnd();
   1135             }
   1136 
   1137             /*
   1138              * StorageManagerService has a few dependencies: Notification Manager and
   1139              * AppWidget Provider. Make sure StorageManagerService is completely started
   1140              * first before continuing.
   1141              */
   1142             if (storageManager != null && !mOnlyCore) {
   1143                 traceBeginAndSlog("WaitForAsecScan");
   1144                 try {
   1145                     storageManager.waitForAsecScan();
   1146                 } catch (RemoteException ignored) {
   1147                 }
   1148                 traceEnd();
   1149             }
   1150 
   1151             traceBeginAndSlog("StartNotificationManager");
   1152             mSystemServiceManager.startService(NotificationManagerService.class);
   1153             SystemNotificationChannels.createAll(context);
   1154             notification = INotificationManager.Stub.asInterface(
   1155                     ServiceManager.getService(Context.NOTIFICATION_SERVICE));
   1156             networkPolicy.bindNotificationManager(notification);
   1157             traceEnd();
   1158 
   1159             traceBeginAndSlog("StartDeviceMonitor");
   1160             mSystemServiceManager.startService(DeviceStorageMonitorService.class);
   1161             traceEnd();
   1162 
   1163             if (!disableLocation) {
   1164                 traceBeginAndSlog("StartLocationManagerService");
   1165                 try {
   1166                     location = new LocationManagerService(context);
   1167                     ServiceManager.addService(Context.LOCATION_SERVICE, location);
   1168                 } catch (Throwable e) {
   1169                     reportWtf("starting Location Manager", e);
   1170                 }
   1171                 traceEnd();
   1172 
   1173                 traceBeginAndSlog("StartCountryDetectorService");
   1174                 try {
   1175                     countryDetector = new CountryDetectorService(context);
   1176                     ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
   1177                 } catch (Throwable e) {
   1178                     reportWtf("starting Country Detector", e);
   1179                 }
   1180                 traceEnd();
   1181             }
   1182 
   1183             if (!disableNonCoreServices && !disableSearchManager) {
   1184                 traceBeginAndSlog("StartSearchManagerService");
   1185                 try {
   1186                     mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS);
   1187                 } catch (Throwable e) {
   1188                     reportWtf("starting Search Service", e);
   1189                 }
   1190                 traceEnd();
   1191             }
   1192 
   1193             if (!disableNonCoreServices && context.getResources().getBoolean(
   1194                         R.bool.config_enableWallpaperService)) {
   1195                 traceBeginAndSlog("StartWallpaperManagerService");
   1196                 mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
   1197                 traceEnd();
   1198             }
   1199 
   1200             traceBeginAndSlog("StartAudioService");
   1201             mSystemServiceManager.startService(AudioService.Lifecycle.class);
   1202             traceEnd();
   1203 
   1204             if (!disableNonCoreServices) {
   1205                 traceBeginAndSlog("StartDockObserver");
   1206                 mSystemServiceManager.startService(DockObserver.class);
   1207                 traceEnd();
   1208 
   1209                 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
   1210                     traceBeginAndSlog("StartThermalObserver");
   1211                     mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS);
   1212                     traceEnd();
   1213                 }
   1214             }
   1215 
   1216             traceBeginAndSlog("StartWiredAccessoryManager");
   1217             try {
   1218                 // Listen for wired headset changes
   1219                 inputManager.setWiredAccessoryCallbacks(
   1220                         new WiredAccessoryManager(context, inputManager));
   1221             } catch (Throwable e) {
   1222                 reportWtf("starting WiredAccessoryManager", e);
   1223             }
   1224             traceEnd();
   1225 
   1226             if (!disableNonCoreServices) {
   1227                 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) {
   1228                     // Start MIDI Manager service
   1229                     traceBeginAndSlog("StartMidiManager");
   1230                     mSystemServiceManager.startService(MIDI_SERVICE_CLASS);
   1231                     traceEnd();
   1232                 }
   1233 
   1234                 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)
   1235                         || mPackageManager.hasSystemFeature(
   1236                                 PackageManager.FEATURE_USB_ACCESSORY)) {
   1237                     // Manage USB host and device support
   1238                     traceBeginAndSlog("StartUsbService");
   1239                     mSystemServiceManager.startService(USB_SERVICE_CLASS);
   1240                     traceEnd();
   1241                 }
   1242 
   1243                 if (!disableSerial) {
   1244                     traceBeginAndSlog("StartSerialService");
   1245                     try {
   1246                         // Serial port support
   1247                         serial = new SerialService(context);
   1248                         ServiceManager.addService(Context.SERIAL_SERVICE, serial);
   1249                     } catch (Throwable e) {
   1250                         Slog.e(TAG, "Failure starting SerialService", e);
   1251                     }
   1252                     traceEnd();
   1253                 }
   1254 
   1255                 traceBeginAndSlog("StartHardwarePropertiesManagerService");
   1256                 try {
   1257                     hardwarePropertiesService = new HardwarePropertiesManagerService(context);
   1258                     ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE,
   1259                             hardwarePropertiesService);
   1260                 } catch (Throwable e) {
   1261                     Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e);
   1262                 }
   1263                 traceEnd();
   1264             }
   1265 
   1266             traceBeginAndSlog("StartTwilightService");
   1267             mSystemServiceManager.startService(TwilightService.class);
   1268             traceEnd();
   1269 
   1270             if (NightDisplayController.isAvailable(context)) {
   1271                 traceBeginAndSlog("StartNightDisplay");
   1272                 mSystemServiceManager.startService(NightDisplayService.class);
   1273                 traceEnd();
   1274             }
   1275 
   1276             traceBeginAndSlog("StartJobScheduler");
   1277             mSystemServiceManager.startService(JobSchedulerService.class);
   1278             traceEnd();
   1279 
   1280             traceBeginAndSlog("StartSoundTrigger");
   1281             mSystemServiceManager.startService(SoundTriggerService.class);
   1282             traceEnd();
   1283 
   1284             if (!disableNonCoreServices) {
   1285                 if (!disableTrustManager) {
   1286                     traceBeginAndSlog("StartTrustManager");
   1287                     mSystemServiceManager.startService(TrustManagerService.class);
   1288                     traceEnd();
   1289                 }
   1290 
   1291                 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) {
   1292                     traceBeginAndSlog("StartBackupManager");
   1293                     mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS);
   1294                     traceEnd();
   1295                 }
   1296 
   1297                 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)
   1298                     || context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {
   1299                     traceBeginAndSlog("StartAppWidgerService");
   1300                     mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS);
   1301                     traceEnd();
   1302                 }
   1303 
   1304                 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_VOICE_RECOGNIZERS)) {
   1305                     traceBeginAndSlog("StartVoiceRecognitionManager");
   1306                     mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS);
   1307                     traceEnd();
   1308                 }
   1309 
   1310                 if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) {
   1311                     traceBeginAndSlog("StartGestureLauncher");
   1312                     mSystemServiceManager.startService(GestureLauncherService.class);
   1313                     traceEnd();
   1314                 }
   1315                 traceBeginAndSlog("StartSensorNotification");
   1316                 mSystemServiceManager.startService(SensorNotificationService.class);
   1317                 traceEnd();
   1318 
   1319                 traceBeginAndSlog("StartContextHubSystemService");
   1320                 mSystemServiceManager.startService(ContextHubSystemService.class);
   1321                 traceEnd();
   1322             }
   1323 
   1324             traceBeginAndSlog("StartDiskStatsService");
   1325             try {
   1326                 ServiceManager.addService("diskstats", new DiskStatsService(context));
   1327             } catch (Throwable e) {
   1328                 reportWtf("starting DiskStats Service", e);
   1329             }
   1330             traceEnd();
   1331 
   1332             if (!disableSamplingProfiler) {
   1333                 traceBeginAndSlog("StartSamplingProfilerService");
   1334                 try {
   1335                     // need to add this service even if SamplingProfilerIntegration.isEnabled()
   1336                     // is false, because it is this service that detects system property change and
   1337                     // turns on SamplingProfilerIntegration. Plus, when sampling profiler doesn't work,
   1338                     // there is little overhead for running this service.
   1339                     ServiceManager.addService("samplingprofiler",
   1340                                 new SamplingProfilerService(context));
   1341                 } catch (Throwable e) {
   1342                     reportWtf("starting SamplingProfiler Service", e);
   1343                 }
   1344                 traceEnd();
   1345             }
   1346 
   1347             if (!disableNetwork && !disableNetworkTime) {
   1348                 traceBeginAndSlog("StartNetworkTimeUpdateService");
   1349                 try {
   1350                     networkTimeUpdater = new NetworkTimeUpdateService(context);
   1351                     ServiceManager.addService("network_time_update_service", networkTimeUpdater);
   1352                 } catch (Throwable e) {
   1353                     reportWtf("starting NetworkTimeUpdate service", e);
   1354                 }
   1355                 traceEnd();
   1356             }
   1357 
   1358             traceBeginAndSlog("StartCommonTimeManagementService");
   1359             try {
   1360                 commonTimeMgmtService = new CommonTimeManagementService(context);
   1361                 ServiceManager.addService("commontime_management", commonTimeMgmtService);
   1362             } catch (Throwable e) {
   1363                 reportWtf("starting CommonTimeManagementService service", e);
   1364             }
   1365             traceEnd();
   1366 
   1367             if (!disableNetwork) {
   1368                 traceBeginAndSlog("CertBlacklister");
   1369                 try {
   1370                     CertBlacklister blacklister = new CertBlacklister(context);
   1371                 } catch (Throwable e) {
   1372                     reportWtf("starting CertBlacklister", e);
   1373                 }
   1374                 traceEnd();
   1375             }
   1376 
   1377             if (!disableNetwork && !disableNonCoreServices && EmergencyAffordanceManager.ENABLED) {
   1378                 // EmergencyMode service
   1379                 traceBeginAndSlog("StartEmergencyAffordanceService");
   1380                 mSystemServiceManager.startService(EmergencyAffordanceService.class);
   1381                 traceEnd();
   1382             }
   1383 
   1384             if (!disableNonCoreServices) {
   1385                 // Dreams (interactive idle-time views, a/k/a screen savers, and doze mode)
   1386                 traceBeginAndSlog("StartDreamManager");
   1387                 mSystemServiceManager.startService(DreamManagerService.class);
   1388                 traceEnd();
   1389             }
   1390 
   1391             if (!disableNonCoreServices) {
   1392                 traceBeginAndSlog("AddGraphicsStatsService");
   1393                 ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE,
   1394                         new GraphicsStatsService(context));
   1395                 traceEnd();
   1396             }
   1397 
   1398             if (!disableNonCoreServices && CoverageService.ENABLED) {
   1399                 traceBeginAndSlog("AddCoverageService");
   1400                 ServiceManager.addService(CoverageService.COVERAGE_SERVICE, new CoverageService());
   1401                 traceEnd();
   1402             }
   1403 
   1404             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) {
   1405                 traceBeginAndSlog("StartPrintManager");
   1406                 mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS);
   1407                 traceEnd();
   1408             }
   1409 
   1410             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_COMPANION_DEVICE_SETUP)) {
   1411                 traceBeginAndSlog("StartCompanionDeviceManager");
   1412                 mSystemServiceManager.startService(COMPANION_DEVICE_MANAGER_SERVICE_CLASS);
   1413                 traceEnd();
   1414             }
   1415 
   1416             traceBeginAndSlog("StartRestrictionManager");
   1417             mSystemServiceManager.startService(RestrictionsManagerService.class);
   1418             traceEnd();
   1419 
   1420             traceBeginAndSlog("StartMediaSessionService");
   1421             mSystemServiceManager.startService(MediaSessionService.class);
   1422             traceEnd();
   1423 
   1424             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) {
   1425                 traceBeginAndSlog("StartHdmiControlService");
   1426                 mSystemServiceManager.startService(HdmiControlService.class);
   1427                 traceEnd();
   1428             }
   1429 
   1430             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)
   1431                     || mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
   1432                 traceBeginAndSlog("StartTvInputManager");
   1433                 mSystemServiceManager.startService(TvInputManagerService.class);
   1434                 traceEnd();
   1435             }
   1436 
   1437             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
   1438                 traceBeginAndSlog("StartMediaResourceMonitor");
   1439                 mSystemServiceManager.startService(MediaResourceMonitorService.class);
   1440                 traceEnd();
   1441             }
   1442 
   1443             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
   1444                 traceBeginAndSlog("StartTvRemoteService");
   1445                 mSystemServiceManager.startService(TvRemoteService.class);
   1446                 traceEnd();
   1447             }
   1448 
   1449             if (!disableNonCoreServices) {
   1450                 traceBeginAndSlog("StartMediaRouterService");
   1451                 try {
   1452                     mediaRouter = new MediaRouterService(context);
   1453                     ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);
   1454                 } catch (Throwable e) {
   1455                     reportWtf("starting MediaRouterService", e);
   1456                 }
   1457                 traceEnd();
   1458 
   1459                 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
   1460                     traceBeginAndSlog("StartFingerprintSensor");
   1461                     mSystemServiceManager.startService(FingerprintService.class);
   1462                     traceEnd();
   1463                 }
   1464 
   1465                 traceBeginAndSlog("StartBackgroundDexOptService");
   1466                 try {
   1467                     BackgroundDexOptService.schedule(context);
   1468                 } catch (Throwable e) {
   1469                     reportWtf("starting StartBackgroundDexOptService", e);
   1470                 }
   1471                 traceEnd();
   1472 
   1473                 traceBeginAndSlog("StartPruneInstantAppsJobService");
   1474                 try {
   1475                     PruneInstantAppsJobService.schedule(context);
   1476                 } catch (Throwable e) {
   1477                     reportWtf("StartPruneInstantAppsJobService", e);
   1478                 }
   1479                 traceEnd();
   1480             }
   1481             // LauncherAppsService uses ShortcutService.
   1482             traceBeginAndSlog("StartShortcutServiceLifecycle");
   1483             mSystemServiceManager.startService(ShortcutService.Lifecycle.class);
   1484             traceEnd();
   1485 
   1486             traceBeginAndSlog("StartLauncherAppsService");
   1487             mSystemServiceManager.startService(LauncherAppsService.class);
   1488             traceEnd();
   1489         }
   1490 
   1491         if (!disableNonCoreServices && !disableMediaProjection) {
   1492             traceBeginAndSlog("StartMediaProjectionManager");
   1493             mSystemServiceManager.startService(MediaProjectionManagerService.class);
   1494             traceEnd();
   1495         }
   1496 
   1497         if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
   1498             traceBeginAndSlog("StartWearConnectivityService");
   1499             mSystemServiceManager.startService(WEAR_CONNECTIVITY_SERVICE_CLASS);
   1500             traceEnd();
   1501 
   1502             if (!disableNonCoreServices) {
   1503                 traceBeginAndSlog("StartWearTimeService");
   1504                 mSystemServiceManager.startService(WEAR_DISPLAY_SERVICE_CLASS);
   1505                 mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS);
   1506                 traceEnd();
   1507             }
   1508         }
   1509 
   1510         // Before things start rolling, be sure we have decided whether
   1511         // we are in safe mode.
   1512         final boolean safeMode = wm.detectSafeMode();
   1513         if (safeMode) {
   1514             traceBeginAndSlog("EnterSafeModeAndDisableJitCompilation");
   1515             mActivityManagerService.enterSafeMode();
   1516             // Disable the JIT for the system_server process
   1517             VMRuntime.getRuntime().disableJitCompilation();
   1518             traceEnd();
   1519         } else {
   1520             // Enable the JIT for the system_server process
   1521             traceBeginAndSlog("StartJitCompilation");
   1522             VMRuntime.getRuntime().startJitCompilation();
   1523             traceEnd();
   1524         }
   1525 
   1526         // MMS service broker
   1527         traceBeginAndSlog("StartMmsService");
   1528         mmsService = mSystemServiceManager.startService(MmsServiceBroker.class);
   1529         traceEnd();
   1530 
   1531         traceBeginAndSlog("StartRetailDemoModeService");
   1532         mSystemServiceManager.startService(RetailDemoModeService.class);
   1533         traceEnd();
   1534 
   1535         if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOFILL)) {
   1536             traceBeginAndSlog("StartAutoFillService");
   1537             mSystemServiceManager.startService(AUTO_FILL_MANAGER_SERVICE_CLASS);
   1538             traceEnd();
   1539         }
   1540 
   1541         // It is now time to start up the app processes...
   1542 
   1543         traceBeginAndSlog("MakeVibratorServiceReady");
   1544         try {
   1545             vibrator.systemReady();
   1546         } catch (Throwable e) {
   1547             reportWtf("making Vibrator Service ready", e);
   1548         }
   1549         traceEnd();
   1550 
   1551         traceBeginAndSlog("MakeLockSettingsServiceReady");
   1552         if (lockSettings != null) {
   1553             try {
   1554                 lockSettings.systemReady();
   1555             } catch (Throwable e) {
   1556                 reportWtf("making Lock Settings Service ready", e);
   1557             }
   1558         }
   1559         traceEnd();
   1560 
   1561         // Needed by DevicePolicyManager for initialization
   1562         traceBeginAndSlog("StartBootPhaseLockSettingsReady");
   1563         mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
   1564         traceEnd();
   1565 
   1566         traceBeginAndSlog("StartBootPhaseSystemServicesReady");
   1567         mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
   1568         traceEnd();
   1569 
   1570         traceBeginAndSlog("MakeWindowManagerServiceReady");
   1571         try {
   1572             wm.systemReady();
   1573         } catch (Throwable e) {
   1574             reportWtf("making Window Manager Service ready", e);
   1575         }
   1576         traceEnd();
   1577 
   1578         if (safeMode) {
   1579             mActivityManagerService.showSafeModeOverlay();
   1580         }
   1581 
   1582         // Update the configuration for this context by hand, because we're going
   1583         // to start using it before the config change done in wm.systemReady() will
   1584         // propagate to it.
   1585         final Configuration config = wm.computeNewConfiguration(DEFAULT_DISPLAY);
   1586         DisplayMetrics metrics = new DisplayMetrics();
   1587         WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
   1588         w.getDefaultDisplay().getMetrics(metrics);
   1589         context.getResources().updateConfiguration(config, metrics);
   1590 
   1591         // The system context's theme may be configuration-dependent.
   1592         final Theme systemTheme = context.getTheme();
   1593         if (systemTheme.getChangingConfigurations() != 0) {
   1594             systemTheme.rebase();
   1595         }
   1596 
   1597         traceBeginAndSlog("MakePowerManagerServiceReady");
   1598         try {
   1599             // TODO: use boot phase
   1600             mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
   1601         } catch (Throwable e) {
   1602             reportWtf("making Power Manager Service ready", e);
   1603         }
   1604         traceEnd();
   1605 
   1606         traceBeginAndSlog("MakePackageManagerServiceReady");
   1607         try {
   1608             mPackageManagerService.systemReady();
   1609         } catch (Throwable e) {
   1610             reportWtf("making Package Manager Service ready", e);
   1611         }
   1612         traceEnd();
   1613 
   1614         traceBeginAndSlog("MakeDisplayManagerServiceReady");
   1615         try {
   1616             // TODO: use boot phase and communicate these flags some other way
   1617             mDisplayManagerService.systemReady(safeMode, mOnlyCore);
   1618         } catch (Throwable e) {
   1619             reportWtf("making Display Manager Service ready", e);
   1620         }
   1621         traceEnd();
   1622 
   1623         mSystemServiceManager.setSafeMode(safeMode);
   1624 
   1625         // These are needed to propagate to the runnable below.
   1626         final NetworkManagementService networkManagementF = networkManagement;
   1627         final NetworkStatsService networkStatsF = networkStats;
   1628         final NetworkPolicyManagerService networkPolicyF = networkPolicy;
   1629         final ConnectivityService connectivityF = connectivity;
   1630         final NetworkScoreService networkScoreF = networkScore;
   1631         final LocationManagerService locationF = location;
   1632         final CountryDetectorService countryDetectorF = countryDetector;
   1633         final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
   1634         final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService;
   1635         final InputManagerService inputManagerF = inputManager;
   1636         final TelephonyRegistry telephonyRegistryF = telephonyRegistry;
   1637         final MediaRouterService mediaRouterF = mediaRouter;
   1638         final MmsServiceBroker mmsServiceF = mmsService;
   1639         final WindowManagerService windowManagerF = wm;
   1640 
   1641         // We now tell the activity manager it is okay to run third party
   1642         // code.  It will call back into us once it has gotten to the state
   1643         // where third party code can really run (but before it has actually
   1644         // started launching the initial applications), for us to complete our
   1645         // initialization.
   1646         mActivityManagerService.systemReady(() -> {
   1647             Slog.i(TAG, "Making services ready");
   1648             traceBeginAndSlog("StartActivityManagerReadyPhase");
   1649             mSystemServiceManager.startBootPhase(
   1650                     SystemService.PHASE_ACTIVITY_MANAGER_READY);
   1651             traceEnd();
   1652             traceBeginAndSlog("StartObservingNativeCrashes");
   1653             try {
   1654                 mActivityManagerService.startObservingNativeCrashes();
   1655             } catch (Throwable e) {
   1656                 reportWtf("observing native crashes", e);
   1657             }
   1658             traceEnd();
   1659 
   1660             // No dependency on Webview preparation in system server. But this should
   1661             // be completed before allowring 3rd party
   1662             final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
   1663             Future<?> webviewPrep = null;
   1664             if (!mOnlyCore) {
   1665                 webviewPrep = SystemServerInitThreadPool.get().submit(() -> {
   1666                     Slog.i(TAG, WEBVIEW_PREPARATION);
   1667                     BootTimingsTraceLog traceLog = new BootTimingsTraceLog(
   1668                             SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
   1669                     traceLog.traceBegin(WEBVIEW_PREPARATION);
   1670                     ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
   1671                     mZygotePreload = null;
   1672                     mWebViewUpdateService.prepareWebViewInSystemServer();
   1673                     traceLog.traceEnd();
   1674                 }, WEBVIEW_PREPARATION);
   1675             }
   1676 
   1677             traceBeginAndSlog("StartSystemUI");
   1678             try {
   1679                 startSystemUi(context, windowManagerF);
   1680             } catch (Throwable e) {
   1681                 reportWtf("starting System UI", e);
   1682             }
   1683             traceEnd();
   1684             traceBeginAndSlog("MakeNetworkScoreReady");
   1685             try {
   1686                 if (networkScoreF != null) networkScoreF.systemReady();
   1687             } catch (Throwable e) {
   1688                 reportWtf("making Network Score Service ready", e);
   1689             }
   1690             traceEnd();
   1691             traceBeginAndSlog("MakeNetworkManagementServiceReady");
   1692             try {
   1693                 if (networkManagementF != null) networkManagementF.systemReady();
   1694             } catch (Throwable e) {
   1695                 reportWtf("making Network Managment Service ready", e);
   1696             }
   1697             CountDownLatch networkPolicyInitReadySignal = null;
   1698             if (networkPolicyF != null) {
   1699                 networkPolicyInitReadySignal = networkPolicyF
   1700                         .networkScoreAndNetworkManagementServiceReady();
   1701             }
   1702             traceEnd();
   1703             traceBeginAndSlog("MakeNetworkStatsServiceReady");
   1704             try {
   1705                 if (networkStatsF != null) networkStatsF.systemReady();
   1706             } catch (Throwable e) {
   1707                 reportWtf("making Network Stats Service ready", e);
   1708             }
   1709             traceEnd();
   1710             traceBeginAndSlog("MakeConnectivityServiceReady");
   1711             try {
   1712                 if (connectivityF != null) connectivityF.systemReady();
   1713             } catch (Throwable e) {
   1714                 reportWtf("making Connectivity Service ready", e);
   1715             }
   1716             traceEnd();
   1717             traceBeginAndSlog("MakeNetworkPolicyServiceReady");
   1718             try {
   1719                 if (networkPolicyF != null) {
   1720                     networkPolicyF.systemReady(networkPolicyInitReadySignal);
   1721                 }
   1722             } catch (Throwable e) {
   1723                 reportWtf("making Network Policy Service ready", e);
   1724             }
   1725             traceEnd();
   1726 
   1727             traceBeginAndSlog("StartWatchdog");
   1728             Watchdog.getInstance().start();
   1729             traceEnd();
   1730 
   1731             // Wait for all packages to be prepared
   1732             mPackageManagerService.waitForAppDataPrepared();
   1733 
   1734             // It is now okay to let the various system services start their
   1735             // third party code...
   1736             traceBeginAndSlog("PhaseThirdPartyAppsCanStart");
   1737             // confirm webview completion before starting 3rd party
   1738             if (webviewPrep != null) {
   1739                 ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);
   1740             }
   1741             mSystemServiceManager.startBootPhase(
   1742                     SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
   1743             traceEnd();
   1744 
   1745             traceBeginAndSlog("MakeLocationServiceReady");
   1746             try {
   1747                 if (locationF != null) locationF.systemRunning();
   1748             } catch (Throwable e) {
   1749                 reportWtf("Notifying Location Service running", e);
   1750             }
   1751             traceEnd();
   1752             traceBeginAndSlog("MakeCountryDetectionServiceReady");
   1753             try {
   1754                 if (countryDetectorF != null) countryDetectorF.systemRunning();
   1755             } catch (Throwable e) {
   1756                 reportWtf("Notifying CountryDetectorService running", e);
   1757             }
   1758             traceEnd();
   1759             traceBeginAndSlog("MakeNetworkTimeUpdateReady");
   1760             try {
   1761                 if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
   1762             } catch (Throwable e) {
   1763                 reportWtf("Notifying NetworkTimeService running", e);
   1764             }
   1765             traceEnd();
   1766             traceBeginAndSlog("MakeCommonTimeManagementServiceReady");
   1767             try {
   1768                 if (commonTimeMgmtServiceF != null) {
   1769                     commonTimeMgmtServiceF.systemRunning();
   1770                 }
   1771             } catch (Throwable e) {
   1772                 reportWtf("Notifying CommonTimeManagementService running", e);
   1773             }
   1774             traceEnd();
   1775             traceBeginAndSlog("MakeInputManagerServiceReady");
   1776             try {
   1777                 // TODO(BT) Pass parameter to input manager
   1778                 if (inputManagerF != null) inputManagerF.systemRunning();
   1779             } catch (Throwable e) {
   1780                 reportWtf("Notifying InputManagerService running", e);
   1781             }
   1782             traceEnd();
   1783             traceBeginAndSlog("MakeTelephonyRegistryReady");
   1784             try {
   1785                 if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
   1786             } catch (Throwable e) {
   1787                 reportWtf("Notifying TelephonyRegistry running", e);
   1788             }
   1789             traceEnd();
   1790             traceBeginAndSlog("MakeMediaRouterServiceReady");
   1791             try {
   1792                 if (mediaRouterF != null) mediaRouterF.systemRunning();
   1793             } catch (Throwable e) {
   1794                 reportWtf("Notifying MediaRouterService running", e);
   1795             }
   1796             traceEnd();
   1797             traceBeginAndSlog("MakeMmsServiceReady");
   1798             try {
   1799                 if (mmsServiceF != null) mmsServiceF.systemRunning();
   1800             } catch (Throwable e) {
   1801                 reportWtf("Notifying MmsService running", e);
   1802             }
   1803             traceEnd();
   1804 
   1805             traceBeginAndSlog("MakeNetworkScoreServiceReady");
   1806             try {
   1807                 if (networkScoreF != null) networkScoreF.systemRunning();
   1808             } catch (Throwable e) {
   1809                 reportWtf("Notifying NetworkScoreService running", e);
   1810             }
   1811             traceEnd();
   1812             traceBeginAndSlog("IncidentDaemonReady");
   1813             try {
   1814                 // TODO: Switch from checkService to getService once it's always
   1815                 // in the build and should reliably be there.
   1816                 final IIncidentManager incident = IIncidentManager.Stub.asInterface(
   1817                         ServiceManager.checkService("incident"));
   1818                 if (incident != null) incident.systemRunning();
   1819             } catch (Throwable e) {
   1820                 reportWtf("Notifying incident daemon running", e);
   1821             }
   1822             traceEnd();
   1823         }, BOOT_TIMINGS_TRACE_LOG);
   1824     }
   1825 
   1826     static final void startSystemUi(Context context, WindowManagerService windowManager) {
   1827         Intent intent = new Intent();
   1828         intent.setComponent(new ComponentName("com.android.systemui",
   1829                     "com.android.systemui.SystemUIService"));
   1830         intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
   1831         //Slog.d(TAG, "Starting service: " + intent);
   1832         context.startServiceAsUser(intent, UserHandle.SYSTEM);
   1833         windowManager.onSystemUiStarted();
   1834     }
   1835 
   1836     private static void traceBeginAndSlog(String name) {
   1837         Slog.i(TAG, name);
   1838         BOOT_TIMINGS_TRACE_LOG.traceBegin(name);
   1839     }
   1840 
   1841     private static void traceEnd() {
   1842         BOOT_TIMINGS_TRACE_LOG.traceEnd();
   1843     }
   1844 }
   1845