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.ActivityManagerNative;
     20 import android.app.ActivityThread;
     21 import android.app.INotificationManager;
     22 import android.app.usage.UsageStatsManagerInternal;
     23 import android.content.ComponentName;
     24 import android.content.ContentResolver;
     25 import android.content.Context;
     26 import android.content.Intent;
     27 import android.content.pm.PackageManager;
     28 import android.content.res.Configuration;
     29 import android.content.res.Resources.Theme;
     30 import android.os.BaseBundle;
     31 import android.os.Build;
     32 import android.os.Environment;
     33 import android.os.FactoryTest;
     34 import android.os.FileUtils;
     35 import android.os.IPowerManager;
     36 import android.os.Looper;
     37 import android.os.PowerManager;
     38 import android.os.RemoteException;
     39 import android.os.ServiceManager;
     40 import android.os.StrictMode;
     41 import android.os.SystemClock;
     42 import android.os.SystemProperties;
     43 import android.os.Trace;
     44 import android.os.UserHandle;
     45 import android.os.UserManager;
     46 import android.os.storage.IMountService;
     47 import android.provider.Settings;
     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.os.BinderInternal;
     56 import com.android.internal.os.SamplingProfilerIntegration;
     57 import com.android.internal.os.ZygoteInit;
     58 import com.android.internal.widget.ILockSettings;
     59 import com.android.server.accessibility.AccessibilityManagerService;
     60 import com.android.server.am.ActivityManagerService;
     61 import com.android.server.audio.AudioService;
     62 import com.android.server.camera.CameraService;
     63 import com.android.server.clipboard.ClipboardService;
     64 import com.android.server.connectivity.MetricsLoggerService;
     65 import com.android.server.devicepolicy.DevicePolicyManagerService;
     66 import com.android.server.display.DisplayManagerService;
     67 import com.android.server.display.NightDisplayService;
     68 import com.android.server.dreams.DreamManagerService;
     69 import com.android.server.fingerprint.FingerprintService;
     70 import com.android.server.hdmi.HdmiControlService;
     71 import com.android.server.input.InputManagerService;
     72 import com.android.server.job.JobSchedulerService;
     73 import com.android.server.lights.LightsService;
     74 import com.android.server.media.MediaResourceMonitorService;
     75 import com.android.server.media.MediaRouterService;
     76 import com.android.server.media.MediaSessionService;
     77 import com.android.server.media.projection.MediaProjectionManagerService;
     78 import com.android.server.net.NetworkPolicyManagerService;
     79 import com.android.server.net.NetworkStatsService;
     80 import com.android.server.notification.NotificationManagerService;
     81 import com.android.server.os.SchedulingPolicyService;
     82 import com.android.server.pm.BackgroundDexOptService;
     83 import com.android.server.pm.Installer;
     84 import com.android.server.pm.LauncherAppsService;
     85 import com.android.server.pm.OtaDexoptService;
     86 import com.android.server.pm.PackageManagerService;
     87 import com.android.server.pm.ShortcutService;
     88 import com.android.server.pm.UserManagerService;
     89 import com.android.server.power.PowerManagerService;
     90 import com.android.server.power.ShutdownThread;
     91 import com.android.server.restrictions.RestrictionsManagerService;
     92 import com.android.server.retaildemo.RetailDemoModeService;
     93 import com.android.server.soundtrigger.SoundTriggerService;
     94 import com.android.server.statusbar.StatusBarManagerService;
     95 import com.android.server.storage.DeviceStorageMonitorService;
     96 import com.android.server.telecom.TelecomLoaderService;
     97 import com.android.server.trust.TrustManagerService;
     98 import com.android.server.tv.TvRemoteService;
     99 import com.android.server.tv.TvInputManagerService;
    100 import com.android.server.twilight.TwilightService;
    101 import com.android.server.usage.UsageStatsService;
    102 import com.android.server.vr.VrManagerService;
    103 import com.android.server.webkit.WebViewUpdateService;
    104 import com.android.server.wm.WindowManagerService;
    105 
    106 import dalvik.system.VMRuntime;
    107 
    108 import java.io.File;
    109 import java.io.IOException;
    110 import java.util.Locale;
    111 import java.util.Timer;
    112 import java.util.TimerTask;
    113 
    114 public final class SystemServer {
    115     private static final String TAG = "SystemServer";
    116 
    117     private static final String ENCRYPTING_STATE = "trigger_restart_min_framework";
    118     private static final String ENCRYPTED_STATE = "1";
    119 
    120     private static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; // 1hr
    121 
    122     // The earliest supported time.  We pick one day into 1970, to
    123     // give any timezone code room without going into negative time.
    124     private static final long EARLIEST_SUPPORTED_TIME = 86400 * 1000;
    125 
    126     /*
    127      * Implementation class names. TODO: Move them to a codegen class or load
    128      * them from the build system somehow.
    129      */
    130     private static final String BACKUP_MANAGER_SERVICE_CLASS =
    131             "com.android.server.backup.BackupManagerService$Lifecycle";
    132     private static final String APPWIDGET_SERVICE_CLASS =
    133             "com.android.server.appwidget.AppWidgetService";
    134     private static final String VOICE_RECOGNITION_MANAGER_SERVICE_CLASS =
    135             "com.android.server.voiceinteraction.VoiceInteractionManagerService";
    136     private static final String PRINT_MANAGER_SERVICE_CLASS =
    137             "com.android.server.print.PrintManagerService";
    138     private static final String USB_SERVICE_CLASS =
    139             "com.android.server.usb.UsbService$Lifecycle";
    140     private static final String MIDI_SERVICE_CLASS =
    141             "com.android.server.midi.MidiService$Lifecycle";
    142     private static final String WIFI_SERVICE_CLASS =
    143             "com.android.server.wifi.WifiService";
    144     private static final String WIFI_NAN_SERVICE_CLASS =
    145             "com.android.server.wifi.nan.WifiNanService";
    146     private static final String WIFI_P2P_SERVICE_CLASS =
    147             "com.android.server.wifi.p2p.WifiP2pService";
    148     private static final String ETHERNET_SERVICE_CLASS =
    149             "com.android.server.ethernet.EthernetService";
    150     private static final String JOB_SCHEDULER_SERVICE_CLASS =
    151             "com.android.server.job.JobSchedulerService";
    152     private static final String LOCK_SETTINGS_SERVICE_CLASS =
    153             "com.android.server.LockSettingsService$Lifecycle";
    154     private static final String MOUNT_SERVICE_CLASS =
    155             "com.android.server.MountService$Lifecycle";
    156     private static final String SEARCH_MANAGER_SERVICE_CLASS =
    157             "com.android.server.search.SearchManagerService$Lifecycle";
    158     private static final String THERMAL_OBSERVER_CLASS =
    159             "com.google.android.clockwork.ThermalObserver";
    160     private static final String WEAR_BLUETOOTH_SERVICE_CLASS =
    161             "com.google.android.clockwork.bluetooth.WearBluetoothService";
    162     private static final String WEAR_WIFI_MEDIATOR_SERVICE_CLASS =
    163             "com.google.android.clockwork.wifi.WearWifiMediatorService";
    164     private static final String WEAR_TIME_SERVICE_CLASS =
    165             "com.google.android.clockwork.time.WearTimeService";
    166     private static final String ACCOUNT_SERVICE_CLASS =
    167             "com.android.server.accounts.AccountManagerService$Lifecycle";
    168     private static final String CONTENT_SERVICE_CLASS =
    169             "com.android.server.content.ContentService$Lifecycle";
    170     private static final String WALLPAPER_SERVICE_CLASS =
    171             "com.android.server.wallpaper.WallpaperManagerService$Lifecycle";
    172 
    173     private static final String PERSISTENT_DATA_BLOCK_PROP = "ro.frp.pst";
    174 
    175     private static final String UNCRYPT_PACKAGE_FILE = "/cache/recovery/uncrypt_file";
    176     private static final String BLOCK_MAP_FILE = "/cache/recovery/block.map";
    177 
    178     // maximum number of binder threads used for system_server
    179     // will be higher than the system default
    180     private static final int sMaxBinderThreads = 31;
    181 
    182     /**
    183      * Default theme used by the system context. This is used to style
    184      * system-provided dialogs, such as the Power Off dialog, and other
    185      * visual content.
    186      */
    187     private static final int DEFAULT_SYSTEM_THEME =
    188             com.android.internal.R.style.Theme_DeviceDefault_System;
    189 
    190     private final int mFactoryTestMode;
    191     private Timer mProfilerSnapshotTimer;
    192 
    193     private Context mSystemContext;
    194     private SystemServiceManager mSystemServiceManager;
    195 
    196     // TODO: remove all of these references by improving dependency resolution and boot phases
    197     private PowerManagerService mPowerManagerService;
    198     private ActivityManagerService mActivityManagerService;
    199     private WebViewUpdateService mWebViewUpdateService;
    200     private DisplayManagerService mDisplayManagerService;
    201     private PackageManagerService mPackageManagerService;
    202     private PackageManager mPackageManager;
    203     private ContentResolver mContentResolver;
    204     private EntropyMixer mEntropyMixer;
    205 
    206     private boolean mOnlyCore;
    207     private boolean mFirstBoot;
    208 
    209     /**
    210      * Start the sensor service.
    211      */
    212     private static native void startSensorService();
    213 
    214     /**
    215      * The main entry point from zygote.
    216      */
    217     public static void main(String[] args) {
    218         new SystemServer().run();
    219     }
    220 
    221     public SystemServer() {
    222         // Check for factory test mode.
    223         mFactoryTestMode = FactoryTest.getMode();
    224     }
    225 
    226     private void run() {
    227         try {
    228             Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitBeforeStartServices");
    229             // If a device's clock is before 1970 (before 0), a lot of
    230             // APIs crash dealing with negative numbers, notably
    231             // java.io.File#setLastModified, so instead we fake it and
    232             // hope that time from cell towers or NTP fixes it shortly.
    233             if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
    234                 Slog.w(TAG, "System clock is before 1970; setting to 1970.");
    235                 SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
    236             }
    237 
    238             // If the system has "persist.sys.language" and friends set, replace them with
    239             // "persist.sys.locale". Note that the default locale at this point is calculated
    240             // using the "-Duser.locale" command line flag. That flag is usually populated by
    241             // AndroidRuntime using the same set of system properties, but only the system_server
    242             // and system apps are allowed to set them.
    243             //
    244             // NOTE: Most changes made here will need an equivalent change to
    245             // core/jni/AndroidRuntime.cpp
    246             if (!SystemProperties.get("persist.sys.language").isEmpty()) {
    247                 final String languageTag = Locale.getDefault().toLanguageTag();
    248 
    249                 SystemProperties.set("persist.sys.locale", languageTag);
    250                 SystemProperties.set("persist.sys.language", "");
    251                 SystemProperties.set("persist.sys.country", "");
    252                 SystemProperties.set("persist.sys.localevar", "");
    253             }
    254 
    255             // Here we go!
    256             Slog.i(TAG, "Entered the Android system server!");
    257             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis());
    258 
    259             // In case the runtime switched since last boot (such as when
    260             // the old runtime was removed in an OTA), set the system
    261             // property so that it is in sync. We can't do this in
    262             // libnativehelper's JniInvocation::Init code where we already
    263             // had to fallback to a different runtime because it is
    264             // running as root and we need to be the system user to set
    265             // the property. http://b/11463182
    266             SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
    267 
    268             // Enable the sampling profiler.
    269             if (SamplingProfilerIntegration.isEnabled()) {
    270                 SamplingProfilerIntegration.start();
    271                 mProfilerSnapshotTimer = new Timer();
    272                 mProfilerSnapshotTimer.schedule(new TimerTask() {
    273                         @Override
    274                         public void run() {
    275                             SamplingProfilerIntegration.writeSnapshot("system_server", null);
    276                         }
    277                     }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
    278             }
    279 
    280             // Mmmmmm... more memory!
    281             VMRuntime.getRuntime().clearGrowthLimit();
    282 
    283             // The system server has to run all of the time, so it needs to be
    284             // as efficient as possible with its memory usage.
    285             VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
    286 
    287             // Some devices rely on runtime fingerprint generation, so make sure
    288             // we've defined it before booting further.
    289             Build.ensureFingerprintProperty();
    290 
    291             // Within the system server, it is an error to access Environment paths without
    292             // explicitly specifying a user.
    293             Environment.setUserRequired(true);
    294 
    295             // Within the system server, any incoming Bundles should be defused
    296             // to avoid throwing BadParcelableException.
    297             BaseBundle.setShouldDefuse(true);
    298 
    299             // Ensure binder calls into the system always run at foreground priority.
    300             BinderInternal.disableBackgroundScheduling(true);
    301 
    302             // Increase the number of binder threads in system_server
    303             BinderInternal.setMaxThreads(sMaxBinderThreads);
    304 
    305             // Prepare the main looper thread (this thread).
    306             android.os.Process.setThreadPriority(
    307                 android.os.Process.THREAD_PRIORITY_FOREGROUND);
    308             android.os.Process.setCanSelfBackground(false);
    309             Looper.prepareMainLooper();
    310 
    311             // Initialize native services.
    312             System.loadLibrary("android_servers");
    313 
    314             // Check whether we failed to shut down last time we tried.
    315             // This call may not return.
    316             performPendingShutdown();
    317 
    318             // Initialize the system context.
    319             createSystemContext();
    320 
    321             // Create the system service manager.
    322             mSystemServiceManager = new SystemServiceManager(mSystemContext);
    323             LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    324         } finally {
    325             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    326         }
    327 
    328         // Start services.
    329         try {
    330             Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
    331             startBootstrapServices();
    332             startCoreServices();
    333             startOtherServices();
    334         } catch (Throwable ex) {
    335             Slog.e("System", "******************************************");
    336             Slog.e("System", "************ Failure starting system services", ex);
    337             throw ex;
    338         } finally {
    339             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    340         }
    341 
    342         // For debug builds, log event loop stalls to dropbox for analysis.
    343         if (StrictMode.conditionallyEnableDebugLogging()) {
    344             Slog.i(TAG, "Enabled StrictMode for system server main thread.");
    345         }
    346 
    347         // Loop forever.
    348         Looper.loop();
    349         throw new RuntimeException("Main thread loop unexpectedly exited");
    350     }
    351 
    352     private void reportWtf(String msg, Throwable e) {
    353         Slog.w(TAG, "***********************************************");
    354         Slog.wtf(TAG, "BOOT FAILURE " + msg, e);
    355     }
    356 
    357     private void performPendingShutdown() {
    358         final String shutdownAction = SystemProperties.get(
    359                 ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
    360         if (shutdownAction != null && shutdownAction.length() > 0) {
    361             boolean reboot = (shutdownAction.charAt(0) == '1');
    362 
    363             final String reason;
    364             if (shutdownAction.length() > 1) {
    365                 reason = shutdownAction.substring(1, shutdownAction.length());
    366             } else {
    367                 reason = null;
    368             }
    369 
    370             // If it's a pending reboot into recovery to apply an update,
    371             // always make sure uncrypt gets executed properly when needed.
    372             // If '/cache/recovery/block.map' hasn't been created, stop the
    373             // reboot which will fail for sure, and get a chance to capture a
    374             // bugreport when that's still feasible. (Bug: 26444951)
    375             if (PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
    376                 File packageFile = new File(UNCRYPT_PACKAGE_FILE);
    377                 if (packageFile.exists()) {
    378                     String filename = null;
    379                     try {
    380                         filename = FileUtils.readTextFile(packageFile, 0, null);
    381                     } catch (IOException e) {
    382                         Slog.e(TAG, "Error reading uncrypt package file", e);
    383                     }
    384 
    385                     if (filename != null && filename.startsWith("/data")) {
    386                         if (!new File(BLOCK_MAP_FILE).exists()) {
    387                             Slog.e(TAG, "Can't find block map file, uncrypt failed or " +
    388                                        "unexpected runtime restart?");
    389                             return;
    390                         }
    391                     }
    392                 }
    393             }
    394             ShutdownThread.rebootOrShutdown(null, reboot, reason);
    395         }
    396     }
    397 
    398     private void createSystemContext() {
    399         ActivityThread activityThread = ActivityThread.systemMain();
    400         mSystemContext = activityThread.getSystemContext();
    401         mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
    402     }
    403 
    404     /**
    405      * Starts the small tangle of critical services that are needed to get
    406      * the system off the ground.  These services have complex mutual dependencies
    407      * which is why we initialize them all in one place here.  Unless your service
    408      * is also entwined in these dependencies, it should be initialized in one of
    409      * the other functions.
    410      */
    411     private void startBootstrapServices() {
    412         // Wait for installd to finish starting up so that it has a chance to
    413         // create critical directories such as /data/user with the appropriate
    414         // permissions.  We need this to complete before we initialize other services.
    415         Installer installer = mSystemServiceManager.startService(Installer.class);
    416 
    417         // Activity manager runs the show.
    418         mActivityManagerService = mSystemServiceManager.startService(
    419                 ActivityManagerService.Lifecycle.class).getService();
    420         mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    421         mActivityManagerService.setInstaller(installer);
    422 
    423         // Power manager needs to be started early because other services need it.
    424         // Native daemons may be watching for it to be registered so it must be ready
    425         // to handle incoming binder calls immediately (including being able to verify
    426         // the permissions for those calls).
    427         mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
    428 
    429         // Now that the power manager has been started, let the activity manager
    430         // initialize power management features.
    431         Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitPowerManagement");
    432         mActivityManagerService.initPowerManagement();
    433         Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    434 
    435         // Manages LEDs and display backlight so we need it to bring up the display.
    436         mSystemServiceManager.startService(LightsService.class);
    437 
    438         // Display manager is needed to provide display metrics before package manager
    439         // starts up.
    440         mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
    441 
    442         // We need the default display before we can initialize the package manager.
    443         mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
    444 
    445         // Only run "core" apps if we're encrypting the device.
    446         String cryptState = SystemProperties.get("vold.decrypt");
    447         if (ENCRYPTING_STATE.equals(cryptState)) {
    448             Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
    449             mOnlyCore = true;
    450         } else if (ENCRYPTED_STATE.equals(cryptState)) {
    451             Slog.w(TAG, "Device encrypted - only parsing core apps");
    452             mOnlyCore = true;
    453         }
    454 
    455         // Start the package manager.
    456         traceBeginAndSlog("StartPackageManagerService");
    457         mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
    458                 mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    459         mFirstBoot = mPackageManagerService.isFirstBoot();
    460         mPackageManager = mSystemContext.getPackageManager();
    461         Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    462 
    463         // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
    464         // A/B artifacts after boot, before anything else might touch/need them.
    465         // Note: this isn't needed during decryption (we don't have /data anyways).
    466         if (!mOnlyCore) {
    467             boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
    468                     false);
    469             if (!disableOtaDexopt) {
    470                 traceBeginAndSlog("StartOtaDexOptService");
    471                 try {
    472                     OtaDexoptService.main(mSystemContext, mPackageManagerService);
    473                 } catch (Throwable e) {
    474                     reportWtf("starting OtaDexOptService", e);
    475                 } finally {
    476                     Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    477                 }
    478             }
    479         }
    480 
    481         traceBeginAndSlog("StartUserManagerService");
    482         mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
    483         Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    484 
    485         // Initialize attribute cache used to cache resources from packages.
    486         AttributeCache.init(mSystemContext);
    487 
    488         // Set up the Application instance for the system process and get started.
    489         mActivityManagerService.setSystemProcess();
    490 
    491         // The sensor service needs access to package manager service, app ops
    492         // service, and permissions service, therefore we start it after them.
    493         startSensorService();
    494     }
    495 
    496     /**
    497      * Starts some essential services that are not tangled up in the bootstrap process.
    498      */
    499     private void startCoreServices() {
    500         // Tracks the battery level.  Requires LightService.
    501         mSystemServiceManager.startService(BatteryService.class);
    502 
    503         // Tracks application usage stats.
    504         mSystemServiceManager.startService(UsageStatsService.class);
    505         mActivityManagerService.setUsageStatsManager(
    506                 LocalServices.getService(UsageStatsManagerInternal.class));
    507 
    508         // Tracks whether the updatable WebView is in a ready state and watches for update installs.
    509         mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
    510     }
    511 
    512     /**
    513      * Starts a miscellaneous grab bag of stuff that has yet to be refactored
    514      * and organized.
    515      */
    516     private void startOtherServices() {
    517         final Context context = mSystemContext;
    518         VibratorService vibrator = null;
    519         IMountService mountService = null;
    520         NetworkManagementService networkManagement = null;
    521         NetworkStatsService networkStats = null;
    522         NetworkPolicyManagerService networkPolicy = null;
    523         ConnectivityService connectivity = null;
    524         NetworkScoreService networkScore = null;
    525         NsdService serviceDiscovery= null;
    526         WindowManagerService wm = null;
    527         SerialService serial = null;
    528         NetworkTimeUpdateService networkTimeUpdater = null;
    529         CommonTimeManagementService commonTimeMgmtService = null;
    530         InputManagerService inputManager = null;
    531         TelephonyRegistry telephonyRegistry = null;
    532         ConsumerIrService consumerIr = null;
    533         MmsServiceBroker mmsService = null;
    534         HardwarePropertiesManagerService hardwarePropertiesService = null;
    535 
    536         boolean disableStorage = SystemProperties.getBoolean("config.disable_storage", false);
    537         boolean disableBluetooth = SystemProperties.getBoolean("config.disable_bluetooth", false);
    538         boolean disableLocation = SystemProperties.getBoolean("config.disable_location", false);
    539         boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui", false);
    540         boolean disableNonCoreServices = SystemProperties.getBoolean("config.disable_noncore", false);
    541         boolean disableNetwork = SystemProperties.getBoolean("config.disable_network", false);
    542         boolean disableNetworkTime = SystemProperties.getBoolean("config.disable_networktime", false);
    543         boolean disableRtt = SystemProperties.getBoolean("config.disable_rtt", false);
    544         boolean disableMediaProjection = SystemProperties.getBoolean("config.disable_mediaproj",
    545                 false);
    546         boolean disableSerial = SystemProperties.getBoolean("config.disable_serial", false);
    547         boolean disableSearchManager = SystemProperties.getBoolean("config.disable_searchmanager",
    548                 false);
    549         boolean disableTrustManager = SystemProperties.getBoolean("config.disable_trustmanager",
    550                 false);
    551         boolean disableTextServices = SystemProperties.getBoolean("config.disable_textservices", false);
    552         boolean disableSamplingProfiler = SystemProperties.getBoolean("config.disable_samplingprof",
    553                 false);
    554         boolean isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1");
    555 
    556         try {
    557             Slog.i(TAG, "Reading configuration...");
    558             SystemConfig.getInstance();
    559 
    560             traceBeginAndSlog("StartSchedulingPolicyService");
    561             ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
    562             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    563 
    564             mSystemServiceManager.startService(TelecomLoaderService.class);
    565 
    566             traceBeginAndSlog("StartTelephonyRegistry");
    567             telephonyRegistry = new TelephonyRegistry(context);
    568             ServiceManager.addService("telephony.registry", telephonyRegistry);
    569             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    570 
    571             traceBeginAndSlog("StartEntropyMixer");
    572             mEntropyMixer = new EntropyMixer(context);
    573             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    574 
    575             mContentResolver = context.getContentResolver();
    576 
    577             Slog.i(TAG, "Camera Service");
    578             mSystemServiceManager.startService(CameraService.class);
    579 
    580             // The AccountManager must come before the ContentService
    581             traceBeginAndSlog("StartAccountManagerService");
    582             mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
    583             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    584 
    585             traceBeginAndSlog("StartContentService");
    586             mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);
    587             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    588 
    589             traceBeginAndSlog("InstallSystemProviders");
    590             mActivityManagerService.installSystemProviders();
    591             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    592 
    593             traceBeginAndSlog("StartVibratorService");
    594             vibrator = new VibratorService(context);
    595             ServiceManager.addService("vibrator", vibrator);
    596             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    597 
    598             traceBeginAndSlog("StartConsumerIrService");
    599             consumerIr = new ConsumerIrService(context);
    600             ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);
    601             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    602 
    603             traceBeginAndSlog("StartAlarmManagerService");
    604             mSystemServiceManager.startService(AlarmManagerService.class);
    605             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    606 
    607             traceBeginAndSlog("InitWatchdog");
    608             final Watchdog watchdog = Watchdog.getInstance();
    609             watchdog.init(context, mActivityManagerService);
    610             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    611 
    612             traceBeginAndSlog("StartInputManagerService");
    613             inputManager = new InputManagerService(context);
    614             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    615 
    616             traceBeginAndSlog("StartWindowManagerService");
    617             wm = WindowManagerService.main(context, inputManager,
    618                     mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
    619                     !mFirstBoot, mOnlyCore);
    620             ServiceManager.addService(Context.WINDOW_SERVICE, wm);
    621             ServiceManager.addService(Context.INPUT_SERVICE, inputManager);
    622             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    623 
    624             traceBeginAndSlog("StartVrManagerService");
    625             mSystemServiceManager.startService(VrManagerService.class);
    626             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    627 
    628             mActivityManagerService.setWindowManager(wm);
    629 
    630             inputManager.setWindowManagerCallbacks(wm.getInputMonitor());
    631             inputManager.start();
    632 
    633             // TODO: Use service dependencies instead.
    634             mDisplayManagerService.windowManagerAndInputReady();
    635 
    636             // Skip Bluetooth if we have an emulator kernel
    637             // TODO: Use a more reliable check to see if this product should
    638             // support Bluetooth - see bug 988521
    639             if (isEmulator) {
    640                 Slog.i(TAG, "No Bluetooth Service (emulator)");
    641             } else if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
    642                 Slog.i(TAG, "No Bluetooth Service (factory test)");
    643             } else if (!context.getPackageManager().hasSystemFeature
    644                        (PackageManager.FEATURE_BLUETOOTH)) {
    645                 Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");
    646             } else if (disableBluetooth) {
    647                 Slog.i(TAG, "Bluetooth Service disabled by config");
    648             } else {
    649                 mSystemServiceManager.startService(BluetoothService.class);
    650             }
    651 
    652             traceBeginAndSlog("ConnectivityMetricsLoggerService");
    653             mSystemServiceManager.startService(MetricsLoggerService.class);
    654             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    655 
    656             traceBeginAndSlog("PinnerService");
    657             mSystemServiceManager.startService(PinnerService.class);
    658             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    659         } catch (RuntimeException e) {
    660             Slog.e("System", "******************************************");
    661             Slog.e("System", "************ Failure starting core service", e);
    662         }
    663 
    664         StatusBarManagerService statusBar = null;
    665         INotificationManager notification = null;
    666         LocationManagerService location = null;
    667         CountryDetectorService countryDetector = null;
    668         ILockSettings lockSettings = null;
    669         AssetAtlasService atlas = null;
    670         MediaRouterService mediaRouter = null;
    671 
    672         // Bring up services needed for UI.
    673         if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
    674             mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);
    675 
    676             traceBeginAndSlog("StartAccessibilityManagerService");
    677             try {
    678                 ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
    679                         new AccessibilityManagerService(context));
    680             } catch (Throwable e) {
    681                 reportWtf("starting Accessibility Manager", e);
    682             }
    683             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    684         }
    685 
    686         try {
    687             wm.displayReady();
    688         } catch (Throwable e) {
    689             reportWtf("making display ready", e);
    690         }
    691 
    692         if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
    693             if (!disableStorage &&
    694                 !"0".equals(SystemProperties.get("system_init.startmountservice"))) {
    695                 try {
    696                     /*
    697                      * NotificationManagerService is dependant on MountService,
    698                      * (for media / usb notifications) so we must start MountService first.
    699                      */
    700                     mSystemServiceManager.startService(MOUNT_SERVICE_CLASS);
    701                     mountService = IMountService.Stub.asInterface(
    702                             ServiceManager.getService("mount"));
    703                 } catch (Throwable e) {
    704                     reportWtf("starting Mount Service", e);
    705                 }
    706             }
    707         }
    708 
    709         // We start this here so that we update our configuration to set watch or television
    710         // as appropriate.
    711         mSystemServiceManager.startService(UiModeManagerService.class);
    712 
    713         if (!mOnlyCore) {
    714             Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "UpdatePackagesIfNeeded");
    715             try {
    716                 mPackageManagerService.updatePackagesIfNeeded();
    717             } catch (Throwable e) {
    718                 reportWtf("update packages", e);
    719             }
    720             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    721         }
    722 
    723         Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PerformFstrimIfNeeded");
    724         try {
    725             mPackageManagerService.performFstrimIfNeeded();
    726         } catch (Throwable e) {
    727             reportWtf("performing fstrim", e);
    728         }
    729         Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    730 
    731         if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
    732             if (!disableNonCoreServices) {
    733                 traceBeginAndSlog("StartLockSettingsService");
    734                 try {
    735                     mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);
    736                     lockSettings = ILockSettings.Stub.asInterface(
    737                             ServiceManager.getService("lock_settings"));
    738                 } catch (Throwable e) {
    739                     reportWtf("starting LockSettingsService service", e);
    740                 }
    741                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    742 
    743                 if (!SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("")) {
    744                     mSystemServiceManager.startService(PersistentDataBlockService.class);
    745                 }
    746 
    747                 mSystemServiceManager.startService(DeviceIdleController.class);
    748 
    749                 // Always start the Device Policy Manager, so that the API is compatible with
    750                 // API8.
    751                 mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class);
    752             }
    753 
    754             if (!disableSystemUI) {
    755                 traceBeginAndSlog("StartStatusBarManagerService");
    756                 try {
    757                     statusBar = new StatusBarManagerService(context, wm);
    758                     ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
    759                 } catch (Throwable e) {
    760                     reportWtf("starting StatusBarManagerService", e);
    761                 }
    762                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    763             }
    764 
    765             if (!disableNonCoreServices) {
    766                 traceBeginAndSlog("StartClipboardService");
    767                 try {
    768                     ServiceManager.addService(Context.CLIPBOARD_SERVICE,
    769                             new ClipboardService(context));
    770                 } catch (Throwable e) {
    771                     reportWtf("starting Clipboard Service", e);
    772                 }
    773                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    774             }
    775 
    776             if (!disableNetwork) {
    777                 traceBeginAndSlog("StartNetworkManagementService");
    778                 try {
    779                     networkManagement = NetworkManagementService.create(context);
    780                     ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
    781                 } catch (Throwable e) {
    782                     reportWtf("starting NetworkManagement Service", e);
    783                 }
    784                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    785             }
    786 
    787             if (!disableNonCoreServices && !disableTextServices) {
    788                 mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);
    789             }
    790 
    791             if (!disableNetwork) {
    792                 traceBeginAndSlog("StartNetworkScoreService");
    793                 try {
    794                     networkScore = new NetworkScoreService(context);
    795                     ServiceManager.addService(Context.NETWORK_SCORE_SERVICE, networkScore);
    796                 } catch (Throwable e) {
    797                     reportWtf("starting Network Score Service", e);
    798                 }
    799                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    800 
    801                 traceBeginAndSlog("StartNetworkStatsService");
    802                 try {
    803                     networkStats = NetworkStatsService.create(context, networkManagement);
    804                     ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);
    805                 } catch (Throwable e) {
    806                     reportWtf("starting NetworkStats Service", e);
    807                 }
    808                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    809 
    810                 traceBeginAndSlog("StartNetworkPolicyManagerService");
    811                 try {
    812                     networkPolicy = new NetworkPolicyManagerService(context,
    813                             mActivityManagerService, networkStats, networkManagement);
    814                     ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
    815                 } catch (Throwable e) {
    816                     reportWtf("starting NetworkPolicy Service", e);
    817                 }
    818                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    819 
    820                 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_NAN)) {
    821                     mSystemServiceManager.startService(WIFI_NAN_SERVICE_CLASS);
    822                 } else {
    823                     Slog.i(TAG, "No Wi-Fi NAN Service (NAN support Not Present)");
    824                 }
    825                 mSystemServiceManager.startService(WIFI_P2P_SERVICE_CLASS);
    826                 mSystemServiceManager.startService(WIFI_SERVICE_CLASS);
    827                 mSystemServiceManager.startService(
    828                             "com.android.server.wifi.scanner.WifiScanningService");
    829 
    830                 if (!disableRtt) {
    831                     mSystemServiceManager.startService("com.android.server.wifi.RttService");
    832                 }
    833 
    834                 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) ||
    835                     mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) {
    836                     mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS);
    837                 }
    838 
    839                 traceBeginAndSlog("StartConnectivityService");
    840                 try {
    841                     connectivity = new ConnectivityService(
    842                             context, networkManagement, networkStats, networkPolicy);
    843                     ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
    844                     networkStats.bindConnectivityManager(connectivity);
    845                     networkPolicy.bindConnectivityManager(connectivity);
    846                 } catch (Throwable e) {
    847                     reportWtf("starting Connectivity Service", e);
    848                 }
    849                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    850 
    851                 traceBeginAndSlog("StartNsdService");
    852                 try {
    853                     serviceDiscovery = NsdService.create(context);
    854                     ServiceManager.addService(
    855                             Context.NSD_SERVICE, serviceDiscovery);
    856                 } catch (Throwable e) {
    857                     reportWtf("starting Service Discovery Service", e);
    858                 }
    859                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    860             }
    861 
    862             if (!disableNonCoreServices) {
    863                 traceBeginAndSlog("StartUpdateLockService");
    864                 try {
    865                     ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
    866                             new UpdateLockService(context));
    867                 } catch (Throwable e) {
    868                     reportWtf("starting UpdateLockService", e);
    869                 }
    870                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    871             }
    872 
    873             if (!disableNonCoreServices) {
    874                 mSystemServiceManager.startService(RecoverySystemService.class);
    875             }
    876 
    877             /*
    878              * MountService has a few dependencies: Notification Manager and
    879              * AppWidget Provider. Make sure MountService is completely started
    880              * first before continuing.
    881              */
    882             if (mountService != null && !mOnlyCore) {
    883                 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "WaitForAsecScan");
    884                 try {
    885                     mountService.waitForAsecScan();
    886                 } catch (RemoteException ignored) {
    887                 }
    888                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    889             }
    890 
    891             mSystemServiceManager.startService(NotificationManagerService.class);
    892             notification = INotificationManager.Stub.asInterface(
    893                     ServiceManager.getService(Context.NOTIFICATION_SERVICE));
    894             networkPolicy.bindNotificationManager(notification);
    895 
    896             mSystemServiceManager.startService(DeviceStorageMonitorService.class);
    897 
    898             if (!disableLocation) {
    899                 traceBeginAndSlog("StartLocationManagerService");
    900                 try {
    901                     location = new LocationManagerService(context);
    902                     ServiceManager.addService(Context.LOCATION_SERVICE, location);
    903                 } catch (Throwable e) {
    904                     reportWtf("starting Location Manager", e);
    905                 }
    906                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    907 
    908                 traceBeginAndSlog("StartCountryDetectorService");
    909                 try {
    910                     countryDetector = new CountryDetectorService(context);
    911                     ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
    912                 } catch (Throwable e) {
    913                     reportWtf("starting Country Detector", e);
    914                 }
    915                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    916             }
    917 
    918             if (!disableNonCoreServices && !disableSearchManager) {
    919                 traceBeginAndSlog("StartSearchManagerService");
    920                 try {
    921                     mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS);
    922                 } catch (Throwable e) {
    923                     reportWtf("starting Search Service", e);
    924                 }
    925                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    926             }
    927 
    928             mSystemServiceManager.startService(DropBoxManagerService.class);
    929 
    930             if (!disableNonCoreServices && context.getResources().getBoolean(
    931                         R.bool.config_enableWallpaperService)) {
    932                 traceBeginAndSlog("StartWallpaperManagerService");
    933                 mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
    934                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    935             }
    936 
    937             traceBeginAndSlog("StartAudioService");
    938             mSystemServiceManager.startService(AudioService.Lifecycle.class);
    939             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    940 
    941             if (!disableNonCoreServices) {
    942                 mSystemServiceManager.startService(DockObserver.class);
    943 
    944                 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
    945                     mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS);
    946                 }
    947             }
    948 
    949             traceBeginAndSlog("StartWiredAccessoryManager");
    950             try {
    951                 // Listen for wired headset changes
    952                 inputManager.setWiredAccessoryCallbacks(
    953                         new WiredAccessoryManager(context, inputManager));
    954             } catch (Throwable e) {
    955                 reportWtf("starting WiredAccessoryManager", e);
    956             }
    957             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    958 
    959             if (!disableNonCoreServices) {
    960                 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) {
    961                     // Start MIDI Manager service
    962                     mSystemServiceManager.startService(MIDI_SERVICE_CLASS);
    963                 }
    964 
    965                 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)
    966                         || mPackageManager.hasSystemFeature(
    967                                 PackageManager.FEATURE_USB_ACCESSORY)) {
    968                     // Manage USB host and device support
    969                     Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartUsbService");
    970                     mSystemServiceManager.startService(USB_SERVICE_CLASS);
    971                     Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    972                 }
    973 
    974                 if (!disableSerial) {
    975                     traceBeginAndSlog("StartSerialService");
    976                     try {
    977                         // Serial port support
    978                         serial = new SerialService(context);
    979                         ServiceManager.addService(Context.SERIAL_SERVICE, serial);
    980                     } catch (Throwable e) {
    981                         Slog.e(TAG, "Failure starting SerialService", e);
    982                     }
    983                     Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    984                 }
    985 
    986                 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER,
    987                         "StartHardwarePropertiesManagerService");
    988                 try {
    989                     hardwarePropertiesService = new HardwarePropertiesManagerService(context);
    990                     ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE,
    991                             hardwarePropertiesService);
    992                 } catch (Throwable e) {
    993                     Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e);
    994                 }
    995                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    996             }
    997 
    998             mSystemServiceManager.startService(TwilightService.class);
    999 
   1000             if (NightDisplayController.isAvailable(context)) {
   1001                 mSystemServiceManager.startService(NightDisplayService.class);
   1002             }
   1003 
   1004             mSystemServiceManager.startService(JobSchedulerService.class);
   1005 
   1006             mSystemServiceManager.startService(SoundTriggerService.class);
   1007 
   1008             if (!disableNonCoreServices) {
   1009                 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) {
   1010                     mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS);
   1011                 }
   1012 
   1013                 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)
   1014                     || context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {
   1015                     mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS);
   1016                 }
   1017 
   1018                 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_VOICE_RECOGNIZERS)) {
   1019                     mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS);
   1020                 }
   1021 
   1022                 if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) {
   1023                     Slog.i(TAG, "Gesture Launcher Service");
   1024                     mSystemServiceManager.startService(GestureLauncherService.class);
   1025                 }
   1026                 mSystemServiceManager.startService(SensorNotificationService.class);
   1027                 mSystemServiceManager.startService(ContextHubSystemService.class);
   1028             }
   1029 
   1030             traceBeginAndSlog("StartDiskStatsService");
   1031             try {
   1032                 ServiceManager.addService("diskstats", new DiskStatsService(context));
   1033             } catch (Throwable e) {
   1034                 reportWtf("starting DiskStats Service", e);
   1035             }
   1036             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1037 
   1038             if (!disableSamplingProfiler) {
   1039                 traceBeginAndSlog("StartSamplingProfilerService");
   1040                 try {
   1041                     // need to add this service even if SamplingProfilerIntegration.isEnabled()
   1042                     // is false, because it is this service that detects system property change and
   1043                     // turns on SamplingProfilerIntegration. Plus, when sampling profiler doesn't work,
   1044                     // there is little overhead for running this service.
   1045                     ServiceManager.addService("samplingprofiler",
   1046                                 new SamplingProfilerService(context));
   1047                 } catch (Throwable e) {
   1048                     reportWtf("starting SamplingProfiler Service", e);
   1049                 }
   1050                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1051             }
   1052 
   1053             if (!disableNetwork && !disableNetworkTime) {
   1054                 traceBeginAndSlog("StartNetworkTimeUpdateService");
   1055                 try {
   1056                     networkTimeUpdater = new NetworkTimeUpdateService(context);
   1057                     ServiceManager.addService("network_time_update_service", networkTimeUpdater);
   1058                 } catch (Throwable e) {
   1059                     reportWtf("starting NetworkTimeUpdate service", e);
   1060                 }
   1061                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1062             }
   1063 
   1064             traceBeginAndSlog("StartCommonTimeManagementService");
   1065             try {
   1066                 commonTimeMgmtService = new CommonTimeManagementService(context);
   1067                 ServiceManager.addService("commontime_management", commonTimeMgmtService);
   1068             } catch (Throwable e) {
   1069                 reportWtf("starting CommonTimeManagementService service", e);
   1070             }
   1071             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1072 
   1073             if (!disableNetwork) {
   1074                 traceBeginAndSlog("CertBlacklister");
   1075                 try {
   1076                     CertBlacklister blacklister = new CertBlacklister(context);
   1077                 } catch (Throwable e) {
   1078                     reportWtf("starting CertBlacklister", e);
   1079                 }
   1080                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1081             }
   1082 
   1083             if (!disableNonCoreServices) {
   1084                 // Dreams (interactive idle-time views, a/k/a screen savers, and doze mode)
   1085                 mSystemServiceManager.startService(DreamManagerService.class);
   1086             }
   1087 
   1088             if (!disableNonCoreServices && ZygoteInit.PRELOAD_RESOURCES) {
   1089                 traceBeginAndSlog("StartAssetAtlasService");
   1090                 try {
   1091                     atlas = new AssetAtlasService(context);
   1092                     ServiceManager.addService(AssetAtlasService.ASSET_ATLAS_SERVICE, atlas);
   1093                 } catch (Throwable e) {
   1094                     reportWtf("starting AssetAtlasService", e);
   1095                 }
   1096                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1097             }
   1098 
   1099             if (!disableNonCoreServices) {
   1100                 ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE,
   1101                         new GraphicsStatsService(context));
   1102             }
   1103 
   1104             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) {
   1105                 mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS);
   1106             }
   1107 
   1108             mSystemServiceManager.startService(RestrictionsManagerService.class);
   1109 
   1110             mSystemServiceManager.startService(MediaSessionService.class);
   1111 
   1112             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) {
   1113                 mSystemServiceManager.startService(HdmiControlService.class);
   1114             }
   1115 
   1116             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)) {
   1117                 mSystemServiceManager.startService(TvInputManagerService.class);
   1118             }
   1119 
   1120             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
   1121                 mSystemServiceManager.startService(MediaResourceMonitorService.class);
   1122             }
   1123 
   1124             if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
   1125                 mSystemServiceManager.startService(TvRemoteService.class);
   1126             }
   1127 
   1128             if (!disableNonCoreServices) {
   1129                 traceBeginAndSlog("StartMediaRouterService");
   1130                 try {
   1131                     mediaRouter = new MediaRouterService(context);
   1132                     ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);
   1133                 } catch (Throwable e) {
   1134                     reportWtf("starting MediaRouterService", e);
   1135                 }
   1136                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1137 
   1138                 if (!disableTrustManager) {
   1139                     mSystemServiceManager.startService(TrustManagerService.class);
   1140                 }
   1141 
   1142                 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
   1143                     mSystemServiceManager.startService(FingerprintService.class);
   1144                 }
   1145 
   1146                 traceBeginAndSlog("StartBackgroundDexOptService");
   1147                 try {
   1148                     BackgroundDexOptService.schedule(context);
   1149                 } catch (Throwable e) {
   1150                     reportWtf("starting BackgroundDexOptService", e);
   1151                 }
   1152                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1153             }
   1154             // LauncherAppsService uses ShortcutService.
   1155             mSystemServiceManager.startService(ShortcutService.Lifecycle.class);
   1156 
   1157             mSystemServiceManager.startService(LauncherAppsService.class);
   1158         }
   1159 
   1160         if (!disableNonCoreServices && !disableMediaProjection) {
   1161             mSystemServiceManager.startService(MediaProjectionManagerService.class);
   1162         }
   1163 
   1164         if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
   1165             mSystemServiceManager.startService(WEAR_BLUETOOTH_SERVICE_CLASS);
   1166             mSystemServiceManager.startService(WEAR_WIFI_MEDIATOR_SERVICE_CLASS);
   1167           if (!disableNonCoreServices) {
   1168               mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS);
   1169           }
   1170         }
   1171 
   1172         // Before things start rolling, be sure we have decided whether
   1173         // we are in safe mode.
   1174         final boolean safeMode = wm.detectSafeMode();
   1175         if (safeMode) {
   1176             mActivityManagerService.enterSafeMode();
   1177             // Disable the JIT for the system_server process
   1178             VMRuntime.getRuntime().disableJitCompilation();
   1179         } else {
   1180             // Enable the JIT for the system_server process
   1181             VMRuntime.getRuntime().startJitCompilation();
   1182         }
   1183 
   1184         // MMS service broker
   1185         mmsService = mSystemServiceManager.startService(MmsServiceBroker.class);
   1186 
   1187         if (Settings.Global.getInt(mContentResolver, Settings.Global.DEVICE_PROVISIONED, 0) == 0 ||
   1188                 UserManager.isDeviceInDemoMode(mSystemContext)) {
   1189             mSystemServiceManager.startService(RetailDemoModeService.class);
   1190         }
   1191 
   1192         // It is now time to start up the app processes...
   1193 
   1194         Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeVibratorServiceReady");
   1195         try {
   1196             vibrator.systemReady();
   1197         } catch (Throwable e) {
   1198             reportWtf("making Vibrator Service ready", e);
   1199         }
   1200         Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1201 
   1202         Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeLockSettingsServiceReady");
   1203         if (lockSettings != null) {
   1204             try {
   1205                 lockSettings.systemReady();
   1206             } catch (Throwable e) {
   1207                 reportWtf("making Lock Settings Service ready", e);
   1208             }
   1209         }
   1210         Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1211 
   1212         // Needed by DevicePolicyManager for initialization
   1213         mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
   1214 
   1215         mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
   1216 
   1217         Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeWindowManagerServiceReady");
   1218         try {
   1219             wm.systemReady();
   1220         } catch (Throwable e) {
   1221             reportWtf("making Window Manager Service ready", e);
   1222         }
   1223         Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1224 
   1225         if (safeMode) {
   1226             mActivityManagerService.showSafeModeOverlay();
   1227         }
   1228 
   1229         // Update the configuration for this context by hand, because we're going
   1230         // to start using it before the config change done in wm.systemReady() will
   1231         // propagate to it.
   1232         Configuration config = wm.computeNewConfiguration();
   1233         DisplayMetrics metrics = new DisplayMetrics();
   1234         WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
   1235         w.getDefaultDisplay().getMetrics(metrics);
   1236         context.getResources().updateConfiguration(config, metrics);
   1237 
   1238         // The system context's theme may be configuration-dependent.
   1239         final Theme systemTheme = context.getTheme();
   1240         if (systemTheme.getChangingConfigurations() != 0) {
   1241             systemTheme.rebase();
   1242         }
   1243 
   1244         Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakePowerManagerServiceReady");
   1245         try {
   1246             // TODO: use boot phase
   1247             mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
   1248             Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1249         } catch (Throwable e) {
   1250             reportWtf("making Power Manager Service ready", e);
   1251         }
   1252         Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1253 
   1254         Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakePackageManagerServiceReady");
   1255         try {
   1256             mPackageManagerService.systemReady();
   1257         } catch (Throwable e) {
   1258             reportWtf("making Package Manager Service ready", e);
   1259         }
   1260         Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1261 
   1262         Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeDisplayManagerServiceReady");
   1263         try {
   1264             // TODO: use boot phase and communicate these flags some other way
   1265             mDisplayManagerService.systemReady(safeMode, mOnlyCore);
   1266         } catch (Throwable e) {
   1267             reportWtf("making Display Manager Service ready", e);
   1268         }
   1269         Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1270 
   1271         // These are needed to propagate to the runnable below.
   1272         final NetworkManagementService networkManagementF = networkManagement;
   1273         final NetworkStatsService networkStatsF = networkStats;
   1274         final NetworkPolicyManagerService networkPolicyF = networkPolicy;
   1275         final ConnectivityService connectivityF = connectivity;
   1276         final NetworkScoreService networkScoreF = networkScore;
   1277         final LocationManagerService locationF = location;
   1278         final CountryDetectorService countryDetectorF = countryDetector;
   1279         final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
   1280         final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService;
   1281         final AssetAtlasService atlasF = atlas;
   1282         final InputManagerService inputManagerF = inputManager;
   1283         final TelephonyRegistry telephonyRegistryF = telephonyRegistry;
   1284         final MediaRouterService mediaRouterF = mediaRouter;
   1285         final MmsServiceBroker mmsServiceF = mmsService;
   1286 
   1287         // We now tell the activity manager it is okay to run third party
   1288         // code.  It will call back into us once it has gotten to the state
   1289         // where third party code can really run (but before it has actually
   1290         // started launching the initial applications), for us to complete our
   1291         // initialization.
   1292         mActivityManagerService.systemReady(new Runnable() {
   1293             @Override
   1294             public void run() {
   1295                 Slog.i(TAG, "Making services ready");
   1296                 mSystemServiceManager.startBootPhase(
   1297                         SystemService.PHASE_ACTIVITY_MANAGER_READY);
   1298                 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseActivityManagerReady");
   1299 
   1300                 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartObservingNativeCrashes");
   1301                 try {
   1302                     mActivityManagerService.startObservingNativeCrashes();
   1303                 } catch (Throwable e) {
   1304                     reportWtf("observing native crashes", e);
   1305                 }
   1306                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1307 
   1308                 if (!mOnlyCore) {
   1309                     Slog.i(TAG, "WebViewFactory preparation");
   1310                     Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "WebViewFactoryPreparation");
   1311                     mWebViewUpdateService.prepareWebViewInSystemServer();
   1312                     Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1313                 }
   1314 
   1315                 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartSystemUI");
   1316                 try {
   1317                     startSystemUi(context);
   1318                 } catch (Throwable e) {
   1319                     reportWtf("starting System UI", e);
   1320                 }
   1321                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1322                 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkScoreReady");
   1323                 try {
   1324                     if (networkScoreF != null) networkScoreF.systemReady();
   1325                 } catch (Throwable e) {
   1326                     reportWtf("making Network Score Service ready", e);
   1327                 }
   1328                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1329                 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkManagementServiceReady");
   1330                 try {
   1331                     if (networkManagementF != null) networkManagementF.systemReady();
   1332                 } catch (Throwable e) {
   1333                     reportWtf("making Network Managment Service ready", e);
   1334                 }
   1335                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1336                 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkStatsServiceReady");
   1337                 try {
   1338                     if (networkStatsF != null) networkStatsF.systemReady();
   1339                 } catch (Throwable e) {
   1340                     reportWtf("making Network Stats Service ready", e);
   1341                 }
   1342                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1343                 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkPolicyServiceReady");
   1344                 try {
   1345                     if (networkPolicyF != null) networkPolicyF.systemReady();
   1346                 } catch (Throwable e) {
   1347                     reportWtf("making Network Policy Service ready", e);
   1348                 }
   1349                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1350                 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeConnectivityServiceReady");
   1351                 try {
   1352                     if (connectivityF != null) connectivityF.systemReady();
   1353                 } catch (Throwable e) {
   1354                     reportWtf("making Connectivity Service ready", e);
   1355                 }
   1356                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1357 
   1358                 Watchdog.getInstance().start();
   1359 
   1360                 // It is now okay to let the various system services start their
   1361                 // third party code...
   1362                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1363                 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseThirdPartyAppsCanStart");
   1364                 mSystemServiceManager.startBootPhase(
   1365                         SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
   1366 
   1367                 try {
   1368                     if (locationF != null) locationF.systemRunning();
   1369                 } catch (Throwable e) {
   1370                     reportWtf("Notifying Location Service running", e);
   1371                 }
   1372                 try {
   1373                     if (countryDetectorF != null) countryDetectorF.systemRunning();
   1374                 } catch (Throwable e) {
   1375                     reportWtf("Notifying CountryDetectorService running", e);
   1376                 }
   1377                 try {
   1378                     if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
   1379                 } catch (Throwable e) {
   1380                     reportWtf("Notifying NetworkTimeService running", e);
   1381                 }
   1382                 try {
   1383                     if (commonTimeMgmtServiceF != null) {
   1384                         commonTimeMgmtServiceF.systemRunning();
   1385                     }
   1386                 } catch (Throwable e) {
   1387                     reportWtf("Notifying CommonTimeManagementService running", e);
   1388                 }
   1389                 try {
   1390                     if (atlasF != null) atlasF.systemRunning();
   1391                 } catch (Throwable e) {
   1392                     reportWtf("Notifying AssetAtlasService running", e);
   1393                 }
   1394                 try {
   1395                     // TODO(BT) Pass parameter to input manager
   1396                     if (inputManagerF != null) inputManagerF.systemRunning();
   1397                 } catch (Throwable e) {
   1398                     reportWtf("Notifying InputManagerService running", e);
   1399                 }
   1400                 try {
   1401                     if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
   1402                 } catch (Throwable e) {
   1403                     reportWtf("Notifying TelephonyRegistry running", e);
   1404                 }
   1405                 try {
   1406                     if (mediaRouterF != null) mediaRouterF.systemRunning();
   1407                 } catch (Throwable e) {
   1408                     reportWtf("Notifying MediaRouterService running", e);
   1409                 }
   1410 
   1411                 try {
   1412                     if (mmsServiceF != null) mmsServiceF.systemRunning();
   1413                 } catch (Throwable e) {
   1414                     reportWtf("Notifying MmsService running", e);
   1415                 }
   1416 
   1417                 try {
   1418                     if (networkScoreF != null) networkScoreF.systemRunning();
   1419                 } catch (Throwable e) {
   1420                     reportWtf("Notifying NetworkScoreService running", e);
   1421                 }
   1422                 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
   1423             }
   1424         });
   1425     }
   1426 
   1427     static final void startSystemUi(Context context) {
   1428         Intent intent = new Intent();
   1429         intent.setComponent(new ComponentName("com.android.systemui",
   1430                     "com.android.systemui.SystemUIService"));
   1431         intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
   1432         //Slog.d(TAG, "Starting service: " + intent);
   1433         context.startServiceAsUser(intent, UserHandle.SYSTEM);
   1434     }
   1435 
   1436     private static void traceBeginAndSlog(String name) {
   1437         Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, name);
   1438         Slog.i(TAG, name);
   1439     }
   1440 }
   1441