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.bluetooth.BluetoothAdapter;
     21 import android.content.ComponentName;
     22 import android.content.ContentResolver;
     23 import android.content.Context;
     24 import android.content.Intent;
     25 import android.content.pm.IPackageManager;
     26 import android.content.pm.PackageManager;
     27 import android.content.res.Configuration;
     28 import android.media.AudioService;
     29 import android.net.wifi.p2p.WifiP2pService;
     30 import android.os.Environment;
     31 import android.os.Handler;
     32 import android.os.HandlerThread;
     33 import android.os.Looper;
     34 import android.os.RemoteException;
     35 import android.os.ServiceManager;
     36 import android.os.StrictMode;
     37 import android.os.SystemClock;
     38 import android.os.SystemProperties;
     39 import android.os.UserHandle;
     40 import android.service.dreams.DreamService;
     41 import android.util.DisplayMetrics;
     42 import android.util.EventLog;
     43 import android.util.Log;
     44 import android.util.Slog;
     45 import android.view.WindowManager;
     46 
     47 import com.android.internal.R;
     48 import com.android.internal.os.BinderInternal;
     49 import com.android.internal.os.SamplingProfilerIntegration;
     50 import com.android.server.accessibility.AccessibilityManagerService;
     51 import com.android.server.accounts.AccountManagerService;
     52 import com.android.server.am.ActivityManagerService;
     53 import com.android.server.am.BatteryStatsService;
     54 import com.android.server.content.ContentService;
     55 import com.android.server.display.DisplayManagerService;
     56 import com.android.server.dreams.DreamManagerService;
     57 import com.android.server.input.InputManagerService;
     58 import com.android.server.media.MediaRouterService;
     59 import com.android.server.net.NetworkPolicyManagerService;
     60 import com.android.server.net.NetworkStatsService;
     61 import com.android.server.os.SchedulingPolicyService;
     62 import com.android.server.pm.Installer;
     63 import com.android.server.pm.PackageManagerService;
     64 import com.android.server.pm.UserManagerService;
     65 import com.android.server.power.PowerManagerService;
     66 import com.android.server.power.ShutdownThread;
     67 import com.android.server.print.PrintManagerService;
     68 import com.android.server.search.SearchManagerService;
     69 import com.android.server.usb.UsbService;
     70 import com.android.server.wifi.WifiService;
     71 import com.android.server.wm.WindowManagerService;
     72 
     73 import dalvik.system.VMRuntime;
     74 import dalvik.system.Zygote;
     75 
     76 import java.io.File;
     77 import java.util.Timer;
     78 import java.util.TimerTask;
     79 
     80 class ServerThread {
     81     private static final String TAG = "SystemServer";
     82     private static final String ENCRYPTING_STATE = "trigger_restart_min_framework";
     83     private static final String ENCRYPTED_STATE = "1";
     84 
     85     ContentResolver mContentResolver;
     86 
     87     void reportWtf(String msg, Throwable e) {
     88         Slog.w(TAG, "***********************************************");
     89         Log.wtf(TAG, "BOOT FAILURE " + msg, e);
     90     }
     91 
     92     public void initAndLoop() {
     93         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN,
     94             SystemClock.uptimeMillis());
     95 
     96         Looper.prepareMainLooper();
     97 
     98         android.os.Process.setThreadPriority(
     99                 android.os.Process.THREAD_PRIORITY_FOREGROUND);
    100 
    101         BinderInternal.disableBackgroundScheduling(true);
    102         android.os.Process.setCanSelfBackground(false);
    103 
    104         // Check whether we failed to shut down last time we tried.
    105         {
    106             final String shutdownAction = SystemProperties.get(
    107                     ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
    108             if (shutdownAction != null && shutdownAction.length() > 0) {
    109                 boolean reboot = (shutdownAction.charAt(0) == '1');
    110 
    111                 final String reason;
    112                 if (shutdownAction.length() > 1) {
    113                     reason = shutdownAction.substring(1, shutdownAction.length());
    114                 } else {
    115                     reason = null;
    116                 }
    117 
    118                 ShutdownThread.rebootOrShutdown(reboot, reason);
    119             }
    120         }
    121 
    122         String factoryTestStr = SystemProperties.get("ro.factorytest");
    123         int factoryTest = "".equals(factoryTestStr) ? SystemServer.FACTORY_TEST_OFF
    124                 : Integer.parseInt(factoryTestStr);
    125         final boolean headless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
    126 
    127         Installer installer = null;
    128         AccountManagerService accountManager = null;
    129         ContentService contentService = null;
    130         LightsService lights = null;
    131         PowerManagerService power = null;
    132         DisplayManagerService display = null;
    133         BatteryService battery = null;
    134         VibratorService vibrator = null;
    135         AlarmManagerService alarm = null;
    136         MountService mountService = null;
    137         NetworkManagementService networkManagement = null;
    138         NetworkStatsService networkStats = null;
    139         NetworkPolicyManagerService networkPolicy = null;
    140         ConnectivityService connectivity = null;
    141         WifiP2pService wifiP2p = null;
    142         WifiService wifi = null;
    143         NsdService serviceDiscovery= null;
    144         IPackageManager pm = null;
    145         Context context = null;
    146         WindowManagerService wm = null;
    147         BluetoothManagerService bluetooth = null;
    148         DockObserver dock = null;
    149         UsbService usb = null;
    150         SerialService serial = null;
    151         TwilightService twilight = null;
    152         UiModeManagerService uiMode = null;
    153         RecognitionManagerService recognition = null;
    154         NetworkTimeUpdateService networkTimeUpdater = null;
    155         CommonTimeManagementService commonTimeMgmtService = null;
    156         InputManagerService inputManager = null;
    157         TelephonyRegistry telephonyRegistry = null;
    158         ConsumerIrService consumerIr = null;
    159 
    160         // Create a handler thread just for the window manager to enjoy.
    161         HandlerThread wmHandlerThread = new HandlerThread("WindowManager");
    162         wmHandlerThread.start();
    163         Handler wmHandler = new Handler(wmHandlerThread.getLooper());
    164         wmHandler.post(new Runnable() {
    165             @Override
    166             public void run() {
    167                 //Looper.myLooper().setMessageLogging(new LogPrinter(
    168                 //        android.util.Log.DEBUG, TAG, android.util.Log.LOG_ID_SYSTEM));
    169                 android.os.Process.setThreadPriority(
    170                         android.os.Process.THREAD_PRIORITY_DISPLAY);
    171                 android.os.Process.setCanSelfBackground(false);
    172 
    173                 // For debug builds, log event loop stalls to dropbox for analysis.
    174                 if (StrictMode.conditionallyEnableDebugLogging()) {
    175                     Slog.i(TAG, "Enabled StrictMode logging for WM Looper");
    176                 }
    177             }
    178         });
    179 
    180         // bootstrap services
    181         boolean onlyCore = false;
    182         boolean firstBoot = false;
    183         try {
    184             // Wait for installd to finished starting up so that it has a chance to
    185             // create critical directories such as /data/user with the appropriate
    186             // permissions.  We need this to complete before we initialize other services.
    187             Slog.i(TAG, "Waiting for installd to be ready.");
    188             installer = new Installer();
    189             installer.ping();
    190 
    191             Slog.i(TAG, "Power Manager");
    192             power = new PowerManagerService();
    193             ServiceManager.addService(Context.POWER_SERVICE, power);
    194 
    195             Slog.i(TAG, "Activity Manager");
    196             context = ActivityManagerService.main(factoryTest);
    197         } catch (RuntimeException e) {
    198             Slog.e("System", "******************************************");
    199             Slog.e("System", "************ Failure starting bootstrap service", e);
    200         }
    201 
    202         boolean disableStorage = SystemProperties.getBoolean("config.disable_storage", false);
    203         boolean disableMedia = SystemProperties.getBoolean("config.disable_media", false);
    204         boolean disableBluetooth = SystemProperties.getBoolean("config.disable_bluetooth", false);
    205         boolean disableTelephony = SystemProperties.getBoolean("config.disable_telephony", false);
    206         boolean disableLocation = SystemProperties.getBoolean("config.disable_location", false);
    207         boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui", false);
    208         boolean disableNonCoreServices = SystemProperties.getBoolean("config.disable_noncore", false);
    209         boolean disableNetwork = SystemProperties.getBoolean("config.disable_network", false);
    210 
    211         try {
    212             Slog.i(TAG, "Display Manager");
    213             display = new DisplayManagerService(context, wmHandler);
    214             ServiceManager.addService(Context.DISPLAY_SERVICE, display, true);
    215 
    216             Slog.i(TAG, "Telephony Registry");
    217             telephonyRegistry = new TelephonyRegistry(context);
    218             ServiceManager.addService("telephony.registry", telephonyRegistry);
    219 
    220             Slog.i(TAG, "Scheduling Policy");
    221             ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
    222 
    223             AttributeCache.init(context);
    224 
    225             if (!display.waitForDefaultDisplay()) {
    226                 reportWtf("Timeout waiting for default display to be initialized.",
    227                         new Throwable());
    228             }
    229 
    230             Slog.i(TAG, "Package Manager");
    231             // Only run "core" apps if we're encrypting the device.
    232             String cryptState = SystemProperties.get("vold.decrypt");
    233             if (ENCRYPTING_STATE.equals(cryptState)) {
    234                 Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
    235                 onlyCore = true;
    236             } else if (ENCRYPTED_STATE.equals(cryptState)) {
    237                 Slog.w(TAG, "Device encrypted - only parsing core apps");
    238                 onlyCore = true;
    239             }
    240 
    241             pm = PackageManagerService.main(context, installer,
    242                     factoryTest != SystemServer.FACTORY_TEST_OFF,
    243                     onlyCore);
    244             try {
    245                 firstBoot = pm.isFirstBoot();
    246             } catch (RemoteException e) {
    247             }
    248 
    249             ActivityManagerService.setSystemProcess();
    250 
    251             Slog.i(TAG, "Entropy Mixer");
    252             ServiceManager.addService("entropy", new EntropyMixer(context));
    253 
    254             Slog.i(TAG, "User Service");
    255             ServiceManager.addService(Context.USER_SERVICE,
    256                     UserManagerService.getInstance());
    257 
    258             mContentResolver = context.getContentResolver();
    259 
    260             // The AccountManager must come before the ContentService
    261             try {
    262                 // TODO: seems like this should be disable-able, but req'd by ContentService
    263                 Slog.i(TAG, "Account Manager");
    264                 accountManager = new AccountManagerService(context);
    265                 ServiceManager.addService(Context.ACCOUNT_SERVICE, accountManager);
    266             } catch (Throwable e) {
    267                 Slog.e(TAG, "Failure starting Account Manager", e);
    268             }
    269 
    270             Slog.i(TAG, "Content Manager");
    271             contentService = ContentService.main(context,
    272                     factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
    273 
    274             Slog.i(TAG, "System Content Providers");
    275             ActivityManagerService.installSystemProviders();
    276 
    277             Slog.i(TAG, "Lights Service");
    278             lights = new LightsService(context);
    279 
    280             Slog.i(TAG, "Battery Service");
    281             battery = new BatteryService(context, lights);
    282             ServiceManager.addService("battery", battery);
    283 
    284             Slog.i(TAG, "Vibrator Service");
    285             vibrator = new VibratorService(context);
    286             ServiceManager.addService("vibrator", vibrator);
    287 
    288             Slog.i(TAG, "Consumer IR Service");
    289             consumerIr = new ConsumerIrService(context);
    290             ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);
    291 
    292             // only initialize the power service after we have started the
    293             // lights service, content providers and the battery service.
    294             power.init(context, lights, ActivityManagerService.self(), battery,
    295                     BatteryStatsService.getService(),
    296                     ActivityManagerService.self().getAppOpsService(), display);
    297 
    298             Slog.i(TAG, "Alarm Manager");
    299             alarm = new AlarmManagerService(context);
    300             ServiceManager.addService(Context.ALARM_SERVICE, alarm);
    301 
    302             Slog.i(TAG, "Init Watchdog");
    303             Watchdog.getInstance().init(context, battery, power, alarm,
    304                     ActivityManagerService.self());
    305             Watchdog.getInstance().addThread(wmHandler, "WindowManager thread");
    306 
    307             Slog.i(TAG, "Input Manager");
    308             inputManager = new InputManagerService(context, wmHandler);
    309 
    310             Slog.i(TAG, "Window Manager");
    311             wm = WindowManagerService.main(context, power, display, inputManager,
    312                     wmHandler, factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL,
    313                     !firstBoot, onlyCore);
    314             ServiceManager.addService(Context.WINDOW_SERVICE, wm);
    315             ServiceManager.addService(Context.INPUT_SERVICE, inputManager);
    316 
    317             ActivityManagerService.self().setWindowManager(wm);
    318 
    319             inputManager.setWindowManagerCallbacks(wm.getInputMonitor());
    320             inputManager.start();
    321 
    322             display.setWindowManager(wm);
    323             display.setInputManager(inputManager);
    324 
    325             // Skip Bluetooth if we have an emulator kernel
    326             // TODO: Use a more reliable check to see if this product should
    327             // support Bluetooth - see bug 988521
    328             if (SystemProperties.get("ro.kernel.qemu").equals("1")) {
    329                 Slog.i(TAG, "No Bluetooh Service (emulator)");
    330             } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
    331                 Slog.i(TAG, "No Bluetooth Service (factory test)");
    332             } else if (!context.getPackageManager().hasSystemFeature
    333                        (PackageManager.FEATURE_BLUETOOTH)) {
    334                 Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");
    335             } else if (disableBluetooth) {
    336                 Slog.i(TAG, "Bluetooth Service disabled by config");
    337             } else {
    338                 Slog.i(TAG, "Bluetooth Manager Service");
    339                 bluetooth = new BluetoothManagerService(context);
    340                 ServiceManager.addService(BluetoothAdapter.BLUETOOTH_MANAGER_SERVICE, bluetooth);
    341             }
    342         } catch (RuntimeException e) {
    343             Slog.e("System", "******************************************");
    344             Slog.e("System", "************ Failure starting core service", e);
    345         }
    346 
    347         DevicePolicyManagerService devicePolicy = null;
    348         StatusBarManagerService statusBar = null;
    349         InputMethodManagerService imm = null;
    350         AppWidgetService appWidget = null;
    351         NotificationManagerService notification = null;
    352         WallpaperManagerService wallpaper = null;
    353         LocationManagerService location = null;
    354         CountryDetectorService countryDetector = null;
    355         TextServicesManagerService tsms = null;
    356         LockSettingsService lockSettings = null;
    357         DreamManagerService dreamy = null;
    358         AssetAtlasService atlas = null;
    359         PrintManagerService printManager = null;
    360         MediaRouterService mediaRouter = null;
    361 
    362         // Bring up services needed for UI.
    363         if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
    364             //if (!disableNonCoreServices) { // TODO: View depends on these; mock them?
    365             if (true) {
    366                 try {
    367                     Slog.i(TAG, "Input Method Service");
    368                     imm = new InputMethodManagerService(context, wm);
    369                     ServiceManager.addService(Context.INPUT_METHOD_SERVICE, imm);
    370                 } catch (Throwable e) {
    371                     reportWtf("starting Input Manager Service", e);
    372                 }
    373 
    374                 try {
    375                     Slog.i(TAG, "Accessibility Manager");
    376                     ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
    377                             new AccessibilityManagerService(context));
    378                 } catch (Throwable e) {
    379                     reportWtf("starting Accessibility Manager", e);
    380                 }
    381             }
    382         }
    383 
    384         try {
    385             wm.displayReady();
    386         } catch (Throwable e) {
    387             reportWtf("making display ready", e);
    388         }
    389 
    390         try {
    391             pm.performBootDexOpt();
    392         } catch (Throwable e) {
    393             reportWtf("performing boot dexopt", e);
    394         }
    395 
    396         try {
    397             ActivityManagerNative.getDefault().showBootMessage(
    398                     context.getResources().getText(
    399                             com.android.internal.R.string.android_upgrading_starting_apps),
    400                             false);
    401         } catch (RemoteException e) {
    402         }
    403 
    404         if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
    405             if (!disableStorage &&
    406                 !"0".equals(SystemProperties.get("system_init.startmountservice"))) {
    407                 try {
    408                     /*
    409                      * NotificationManagerService is dependant on MountService,
    410                      * (for media / usb notifications) so we must start MountService first.
    411                      */
    412                     Slog.i(TAG, "Mount Service");
    413                     mountService = new MountService(context);
    414                     ServiceManager.addService("mount", mountService);
    415                 } catch (Throwable e) {
    416                     reportWtf("starting Mount Service", e);
    417                 }
    418             }
    419 
    420             if (!disableNonCoreServices) {
    421                 try {
    422                     Slog.i(TAG,  "LockSettingsService");
    423                     lockSettings = new LockSettingsService(context);
    424                     ServiceManager.addService("lock_settings", lockSettings);
    425                 } catch (Throwable e) {
    426                     reportWtf("starting LockSettingsService service", e);
    427                 }
    428 
    429                 try {
    430                     Slog.i(TAG, "Device Policy");
    431                     devicePolicy = new DevicePolicyManagerService(context);
    432                     ServiceManager.addService(Context.DEVICE_POLICY_SERVICE, devicePolicy);
    433                 } catch (Throwable e) {
    434                     reportWtf("starting DevicePolicyService", e);
    435                 }
    436             }
    437 
    438             if (!disableSystemUI) {
    439                 try {
    440                     Slog.i(TAG, "Status Bar");
    441                     statusBar = new StatusBarManagerService(context, wm);
    442                     ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
    443                 } catch (Throwable e) {
    444                     reportWtf("starting StatusBarManagerService", e);
    445                 }
    446             }
    447 
    448             if (!disableNonCoreServices) {
    449                 try {
    450                     Slog.i(TAG, "Clipboard Service");
    451                     ServiceManager.addService(Context.CLIPBOARD_SERVICE,
    452                             new ClipboardService(context));
    453                 } catch (Throwable e) {
    454                     reportWtf("starting Clipboard Service", e);
    455                 }
    456             }
    457 
    458             if (!disableNetwork) {
    459                 try {
    460                     Slog.i(TAG, "NetworkManagement Service");
    461                     networkManagement = NetworkManagementService.create(context);
    462                     ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
    463                 } catch (Throwable e) {
    464                     reportWtf("starting NetworkManagement Service", e);
    465                 }
    466             }
    467 
    468             if (!disableNonCoreServices) {
    469                 try {
    470                     Slog.i(TAG, "Text Service Manager Service");
    471                     tsms = new TextServicesManagerService(context);
    472                     ServiceManager.addService(Context.TEXT_SERVICES_MANAGER_SERVICE, tsms);
    473                 } catch (Throwable e) {
    474                     reportWtf("starting Text Service Manager Service", e);
    475                 }
    476             }
    477 
    478             if (!disableNetwork) {
    479                 try {
    480                     Slog.i(TAG, "NetworkStats Service");
    481                     networkStats = new NetworkStatsService(context, networkManagement, alarm);
    482                     ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);
    483                 } catch (Throwable e) {
    484                     reportWtf("starting NetworkStats Service", e);
    485                 }
    486 
    487                 try {
    488                     Slog.i(TAG, "NetworkPolicy Service");
    489                     networkPolicy = new NetworkPolicyManagerService(
    490                             context, ActivityManagerService.self(), power,
    491                             networkStats, networkManagement);
    492                     ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
    493                 } catch (Throwable e) {
    494                     reportWtf("starting NetworkPolicy Service", e);
    495                 }
    496 
    497                try {
    498                     Slog.i(TAG, "Wi-Fi P2pService");
    499                     wifiP2p = new WifiP2pService(context);
    500                     ServiceManager.addService(Context.WIFI_P2P_SERVICE, wifiP2p);
    501                 } catch (Throwable e) {
    502                     reportWtf("starting Wi-Fi P2pService", e);
    503                 }
    504 
    505                try {
    506                     Slog.i(TAG, "Wi-Fi Service");
    507                     wifi = new WifiService(context);
    508                     ServiceManager.addService(Context.WIFI_SERVICE, wifi);
    509                 } catch (Throwable e) {
    510                     reportWtf("starting Wi-Fi Service", e);
    511                 }
    512 
    513                 try {
    514                     Slog.i(TAG, "Connectivity Service");
    515                     connectivity = new ConnectivityService(
    516                             context, networkManagement, networkStats, networkPolicy);
    517                     ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
    518                     networkStats.bindConnectivityManager(connectivity);
    519                     networkPolicy.bindConnectivityManager(connectivity);
    520 
    521                     wifiP2p.connectivityServiceReady();
    522                     wifi.checkAndStartWifi();
    523                 } catch (Throwable e) {
    524                     reportWtf("starting Connectivity Service", e);
    525                 }
    526 
    527                 try {
    528                     Slog.i(TAG, "Network Service Discovery Service");
    529                     serviceDiscovery = NsdService.create(context);
    530                     ServiceManager.addService(
    531                             Context.NSD_SERVICE, serviceDiscovery);
    532                 } catch (Throwable e) {
    533                     reportWtf("starting Service Discovery Service", e);
    534                 }
    535             }
    536 
    537             if (!disableNonCoreServices) {
    538                 try {
    539                     Slog.i(TAG, "UpdateLock Service");
    540                     ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
    541                             new UpdateLockService(context));
    542                 } catch (Throwable e) {
    543                     reportWtf("starting UpdateLockService", e);
    544                 }
    545             }
    546 
    547             /*
    548              * MountService has a few dependencies: Notification Manager and
    549              * AppWidget Provider. Make sure MountService is completely started
    550              * first before continuing.
    551              */
    552             if (mountService != null && !onlyCore) {
    553                 mountService.waitForAsecScan();
    554             }
    555 
    556             try {
    557                 if (accountManager != null)
    558                     accountManager.systemReady();
    559             } catch (Throwable e) {
    560                 reportWtf("making Account Manager Service ready", e);
    561             }
    562 
    563             try {
    564                 if (contentService != null)
    565                     contentService.systemReady();
    566             } catch (Throwable e) {
    567                 reportWtf("making Content Service ready", e);
    568             }
    569 
    570             try {
    571                 Slog.i(TAG, "Notification Manager");
    572                 notification = new NotificationManagerService(context, statusBar, lights);
    573                 ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification);
    574                 networkPolicy.bindNotificationManager(notification);
    575             } catch (Throwable e) {
    576                 reportWtf("starting Notification Manager", e);
    577             }
    578 
    579             try {
    580                 Slog.i(TAG, "Device Storage Monitor");
    581                 ServiceManager.addService(DeviceStorageMonitorService.SERVICE,
    582                         new DeviceStorageMonitorService(context));
    583             } catch (Throwable e) {
    584                 reportWtf("starting DeviceStorageMonitor service", e);
    585             }
    586 
    587             if (!disableLocation) {
    588                 try {
    589                     Slog.i(TAG, "Location Manager");
    590                     location = new LocationManagerService(context);
    591                     ServiceManager.addService(Context.LOCATION_SERVICE, location);
    592                 } catch (Throwable e) {
    593                     reportWtf("starting Location Manager", e);
    594                 }
    595 
    596                 try {
    597                     Slog.i(TAG, "Country Detector");
    598                     countryDetector = new CountryDetectorService(context);
    599                     ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
    600                 } catch (Throwable e) {
    601                     reportWtf("starting Country Detector", e);
    602                 }
    603             }
    604 
    605             if (!disableNonCoreServices) {
    606                 try {
    607                     Slog.i(TAG, "Search Service");
    608                     ServiceManager.addService(Context.SEARCH_SERVICE,
    609                             new SearchManagerService(context));
    610                 } catch (Throwable e) {
    611                     reportWtf("starting Search Service", e);
    612                 }
    613             }
    614 
    615             try {
    616                 Slog.i(TAG, "DropBox Service");
    617                 ServiceManager.addService(Context.DROPBOX_SERVICE,
    618                         new DropBoxManagerService(context, new File("/data/system/dropbox")));
    619             } catch (Throwable e) {
    620                 reportWtf("starting DropBoxManagerService", e);
    621             }
    622 
    623             if (!disableNonCoreServices && context.getResources().getBoolean(
    624                         R.bool.config_enableWallpaperService)) {
    625                 try {
    626                     Slog.i(TAG, "Wallpaper Service");
    627                     if (!headless) {
    628                         wallpaper = new WallpaperManagerService(context);
    629                         ServiceManager.addService(Context.WALLPAPER_SERVICE, wallpaper);
    630                     }
    631                 } catch (Throwable e) {
    632                     reportWtf("starting Wallpaper Service", e);
    633                 }
    634             }
    635 
    636             if (!disableMedia && !"0".equals(SystemProperties.get("system_init.startaudioservice"))) {
    637                 try {
    638                     Slog.i(TAG, "Audio Service");
    639                     ServiceManager.addService(Context.AUDIO_SERVICE, new AudioService(context));
    640                 } catch (Throwable e) {
    641                     reportWtf("starting Audio Service", e);
    642                 }
    643             }
    644 
    645             if (!disableNonCoreServices) {
    646                 try {
    647                     Slog.i(TAG, "Dock Observer");
    648                     // Listen for dock station changes
    649                     dock = new DockObserver(context);
    650                 } catch (Throwable e) {
    651                     reportWtf("starting DockObserver", e);
    652                 }
    653             }
    654 
    655             if (!disableMedia) {
    656                 try {
    657                     Slog.i(TAG, "Wired Accessory Manager");
    658                     // Listen for wired headset changes
    659                     inputManager.setWiredAccessoryCallbacks(
    660                             new WiredAccessoryManager(context, inputManager));
    661                 } catch (Throwable e) {
    662                     reportWtf("starting WiredAccessoryManager", e);
    663                 }
    664             }
    665 
    666             if (!disableNonCoreServices) {
    667                 try {
    668                     Slog.i(TAG, "USB Service");
    669                     // Manage USB host and device support
    670                     usb = new UsbService(context);
    671                     ServiceManager.addService(Context.USB_SERVICE, usb);
    672                 } catch (Throwable e) {
    673                     reportWtf("starting UsbService", e);
    674                 }
    675 
    676                 try {
    677                     Slog.i(TAG, "Serial Service");
    678                     // Serial port support
    679                     serial = new SerialService(context);
    680                     ServiceManager.addService(Context.SERIAL_SERVICE, serial);
    681                 } catch (Throwable e) {
    682                     Slog.e(TAG, "Failure starting SerialService", e);
    683                 }
    684             }
    685 
    686             try {
    687                 Slog.i(TAG, "Twilight Service");
    688                 twilight = new TwilightService(context);
    689             } catch (Throwable e) {
    690                 reportWtf("starting TwilightService", e);
    691             }
    692 
    693             try {
    694                 Slog.i(TAG, "UI Mode Manager Service");
    695                 // Listen for UI mode changes
    696                 uiMode = new UiModeManagerService(context, twilight);
    697             } catch (Throwable e) {
    698                 reportWtf("starting UiModeManagerService", e);
    699             }
    700 
    701             if (!disableNonCoreServices) {
    702                 try {
    703                     Slog.i(TAG, "Backup Service");
    704                     ServiceManager.addService(Context.BACKUP_SERVICE,
    705                             new BackupManagerService(context));
    706                 } catch (Throwable e) {
    707                     Slog.e(TAG, "Failure starting Backup Service", e);
    708                 }
    709 
    710                 try {
    711                     Slog.i(TAG, "AppWidget Service");
    712                     appWidget = new AppWidgetService(context);
    713                     ServiceManager.addService(Context.APPWIDGET_SERVICE, appWidget);
    714                 } catch (Throwable e) {
    715                     reportWtf("starting AppWidget Service", e);
    716                 }
    717 
    718                 try {
    719                     Slog.i(TAG, "Recognition Service");
    720                     recognition = new RecognitionManagerService(context);
    721                 } catch (Throwable e) {
    722                     reportWtf("starting Recognition Service", e);
    723                 }
    724             }
    725 
    726             try {
    727                 Slog.i(TAG, "DiskStats Service");
    728                 ServiceManager.addService("diskstats", new DiskStatsService(context));
    729             } catch (Throwable e) {
    730                 reportWtf("starting DiskStats Service", e);
    731             }
    732 
    733             try {
    734                 // need to add this service even if SamplingProfilerIntegration.isEnabled()
    735                 // is false, because it is this service that detects system property change and
    736                 // turns on SamplingProfilerIntegration. Plus, when sampling profiler doesn't work,
    737                 // there is little overhead for running this service.
    738                 Slog.i(TAG, "SamplingProfiler Service");
    739                 ServiceManager.addService("samplingprofiler",
    740                             new SamplingProfilerService(context));
    741             } catch (Throwable e) {
    742                 reportWtf("starting SamplingProfiler Service", e);
    743             }
    744 
    745             if (!disableNetwork) {
    746                 try {
    747                     Slog.i(TAG, "NetworkTimeUpdateService");
    748                     networkTimeUpdater = new NetworkTimeUpdateService(context);
    749                 } catch (Throwable e) {
    750                     reportWtf("starting NetworkTimeUpdate service", e);
    751                 }
    752             }
    753 
    754             if (!disableMedia) {
    755                 try {
    756                     Slog.i(TAG, "CommonTimeManagementService");
    757                     commonTimeMgmtService = new CommonTimeManagementService(context);
    758                     ServiceManager.addService("commontime_management", commonTimeMgmtService);
    759                 } catch (Throwable e) {
    760                     reportWtf("starting CommonTimeManagementService service", e);
    761                 }
    762             }
    763 
    764             if (!disableNetwork) {
    765                 try {
    766                     Slog.i(TAG, "CertBlacklister");
    767                     CertBlacklister blacklister = new CertBlacklister(context);
    768                 } catch (Throwable e) {
    769                     reportWtf("starting CertBlacklister", e);
    770                 }
    771             }
    772 
    773             if (!disableNonCoreServices &&
    774                 context.getResources().getBoolean(R.bool.config_dreamsSupported)) {
    775                 try {
    776                     Slog.i(TAG, "Dreams Service");
    777                     // Dreams (interactive idle-time views, a/k/a screen savers)
    778                     dreamy = new DreamManagerService(context, wmHandler);
    779                     ServiceManager.addService(DreamService.DREAM_SERVICE, dreamy);
    780                 } catch (Throwable e) {
    781                     reportWtf("starting DreamManagerService", e);
    782                 }
    783             }
    784 
    785             if (!disableNonCoreServices) {
    786                 try {
    787                     Slog.i(TAG, "Assets Atlas Service");
    788                     atlas = new AssetAtlasService(context);
    789                     ServiceManager.addService(AssetAtlasService.ASSET_ATLAS_SERVICE, atlas);
    790                 } catch (Throwable e) {
    791                     reportWtf("starting AssetAtlasService", e);
    792                 }
    793             }
    794 
    795             try {
    796                 Slog.i(TAG, "IdleMaintenanceService");
    797                 new IdleMaintenanceService(context, battery);
    798             } catch (Throwable e) {
    799                 reportWtf("starting IdleMaintenanceService", e);
    800             }
    801 
    802             try {
    803                 Slog.i(TAG, "Print Service");
    804                 printManager = new PrintManagerService(context);
    805                 ServiceManager.addService(Context.PRINT_SERVICE, printManager);
    806             } catch (Throwable e) {
    807                 reportWtf("starting Print Service", e);
    808             }
    809 
    810             if (!disableNonCoreServices) {
    811                 try {
    812                     Slog.i(TAG, "Media Router Service");
    813                     mediaRouter = new MediaRouterService(context);
    814                     ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);
    815                 } catch (Throwable e) {
    816                     reportWtf("starting MediaRouterService", e);
    817                 }
    818             }
    819         }
    820 
    821         // Before things start rolling, be sure we have decided whether
    822         // we are in safe mode.
    823         final boolean safeMode = wm.detectSafeMode();
    824         if (safeMode) {
    825             ActivityManagerService.self().enterSafeMode();
    826             // Post the safe mode state in the Zygote class
    827             Zygote.systemInSafeMode = true;
    828             // Disable the JIT for the system_server process
    829             VMRuntime.getRuntime().disableJitCompilation();
    830         } else {
    831             // Enable the JIT for the system_server process
    832             VMRuntime.getRuntime().startJitCompilation();
    833         }
    834 
    835         // It is now time to start up the app processes...
    836 
    837         try {
    838             vibrator.systemReady();
    839         } catch (Throwable e) {
    840             reportWtf("making Vibrator Service ready", e);
    841         }
    842 
    843         if (lockSettings != null) {
    844             try {
    845                 lockSettings.systemReady();
    846             } catch (Throwable e) {
    847                 reportWtf("making Lock Settings Service ready", e);
    848             }
    849         }
    850 
    851         if (devicePolicy != null) {
    852             try {
    853                 devicePolicy.systemReady();
    854             } catch (Throwable e) {
    855                 reportWtf("making Device Policy Service ready", e);
    856             }
    857         }
    858 
    859         if (notification != null) {
    860             try {
    861                 notification.systemReady();
    862             } catch (Throwable e) {
    863                 reportWtf("making Notification Service ready", e);
    864             }
    865         }
    866 
    867         try {
    868             wm.systemReady();
    869         } catch (Throwable e) {
    870             reportWtf("making Window Manager Service ready", e);
    871         }
    872 
    873         if (safeMode) {
    874             ActivityManagerService.self().showSafeModeOverlay();
    875         }
    876 
    877         // Update the configuration for this context by hand, because we're going
    878         // to start using it before the config change done in wm.systemReady() will
    879         // propagate to it.
    880         Configuration config = wm.computeNewConfiguration();
    881         DisplayMetrics metrics = new DisplayMetrics();
    882         WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
    883         w.getDefaultDisplay().getMetrics(metrics);
    884         context.getResources().updateConfiguration(config, metrics);
    885 
    886         try {
    887             power.systemReady(twilight, dreamy);
    888         } catch (Throwable e) {
    889             reportWtf("making Power Manager Service ready", e);
    890         }
    891 
    892         try {
    893             pm.systemReady();
    894         } catch (Throwable e) {
    895             reportWtf("making Package Manager Service ready", e);
    896         }
    897 
    898         try {
    899             display.systemReady(safeMode, onlyCore);
    900         } catch (Throwable e) {
    901             reportWtf("making Display Manager Service ready", e);
    902         }
    903 
    904         // These are needed to propagate to the runnable below.
    905         final Context contextF = context;
    906         final MountService mountServiceF = mountService;
    907         final BatteryService batteryF = battery;
    908         final NetworkManagementService networkManagementF = networkManagement;
    909         final NetworkStatsService networkStatsF = networkStats;
    910         final NetworkPolicyManagerService networkPolicyF = networkPolicy;
    911         final ConnectivityService connectivityF = connectivity;
    912         final DockObserver dockF = dock;
    913         final UsbService usbF = usb;
    914         final TwilightService twilightF = twilight;
    915         final UiModeManagerService uiModeF = uiMode;
    916         final AppWidgetService appWidgetF = appWidget;
    917         final WallpaperManagerService wallpaperF = wallpaper;
    918         final InputMethodManagerService immF = imm;
    919         final RecognitionManagerService recognitionF = recognition;
    920         final LocationManagerService locationF = location;
    921         final CountryDetectorService countryDetectorF = countryDetector;
    922         final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
    923         final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService;
    924         final TextServicesManagerService textServiceManagerServiceF = tsms;
    925         final StatusBarManagerService statusBarF = statusBar;
    926         final DreamManagerService dreamyF = dreamy;
    927         final AssetAtlasService atlasF = atlas;
    928         final InputManagerService inputManagerF = inputManager;
    929         final TelephonyRegistry telephonyRegistryF = telephonyRegistry;
    930         final PrintManagerService printManagerF = printManager;
    931         final MediaRouterService mediaRouterF = mediaRouter;
    932 
    933         // We now tell the activity manager it is okay to run third party
    934         // code.  It will call back into us once it has gotten to the state
    935         // where third party code can really run (but before it has actually
    936         // started launching the initial applications), for us to complete our
    937         // initialization.
    938         ActivityManagerService.self().systemReady(new Runnable() {
    939             public void run() {
    940                 Slog.i(TAG, "Making services ready");
    941 
    942                 try {
    943                     ActivityManagerService.self().startObservingNativeCrashes();
    944                 } catch (Throwable e) {
    945                     reportWtf("observing native crashes", e);
    946                 }
    947                 if (!headless) {
    948                     startSystemUi(contextF);
    949                 }
    950                 try {
    951                     if (mountServiceF != null) mountServiceF.systemReady();
    952                 } catch (Throwable e) {
    953                     reportWtf("making Mount Service ready", e);
    954                 }
    955                 try {
    956                     if (batteryF != null) batteryF.systemReady();
    957                 } catch (Throwable e) {
    958                     reportWtf("making Battery Service ready", e);
    959                 }
    960                 try {
    961                     if (networkManagementF != null) networkManagementF.systemReady();
    962                 } catch (Throwable e) {
    963                     reportWtf("making Network Managment Service ready", e);
    964                 }
    965                 try {
    966                     if (networkStatsF != null) networkStatsF.systemReady();
    967                 } catch (Throwable e) {
    968                     reportWtf("making Network Stats Service ready", e);
    969                 }
    970                 try {
    971                     if (networkPolicyF != null) networkPolicyF.systemReady();
    972                 } catch (Throwable e) {
    973                     reportWtf("making Network Policy Service ready", e);
    974                 }
    975                 try {
    976                     if (connectivityF != null) connectivityF.systemReady();
    977                 } catch (Throwable e) {
    978                     reportWtf("making Connectivity Service ready", e);
    979                 }
    980                 try {
    981                     if (dockF != null) dockF.systemReady();
    982                 } catch (Throwable e) {
    983                     reportWtf("making Dock Service ready", e);
    984                 }
    985                 try {
    986                     if (usbF != null) usbF.systemReady();
    987                 } catch (Throwable e) {
    988                     reportWtf("making USB Service ready", e);
    989                 }
    990                 try {
    991                     if (twilightF != null) twilightF.systemReady();
    992                 } catch (Throwable e) {
    993                     reportWtf("makin Twilight Service ready", e);
    994                 }
    995                 try {
    996                     if (uiModeF != null) uiModeF.systemReady();
    997                 } catch (Throwable e) {
    998                     reportWtf("making UI Mode Service ready", e);
    999                 }
   1000                 try {
   1001                     if (recognitionF != null) recognitionF.systemReady();
   1002                 } catch (Throwable e) {
   1003                     reportWtf("making Recognition Service ready", e);
   1004                 }
   1005                 Watchdog.getInstance().start();
   1006 
   1007                 // It is now okay to let the various system services start their
   1008                 // third party code...
   1009 
   1010                 try {
   1011                     if (appWidgetF != null) appWidgetF.systemRunning(safeMode);
   1012                 } catch (Throwable e) {
   1013                     reportWtf("Notifying AppWidgetService running", e);
   1014                 }
   1015                 try {
   1016                     if (wallpaperF != null) wallpaperF.systemRunning();
   1017                 } catch (Throwable e) {
   1018                     reportWtf("Notifying WallpaperService running", e);
   1019                 }
   1020                 try {
   1021                     if (immF != null) immF.systemRunning(statusBarF);
   1022                 } catch (Throwable e) {
   1023                     reportWtf("Notifying InputMethodService running", e);
   1024                 }
   1025                 try {
   1026                     if (locationF != null) locationF.systemRunning();
   1027                 } catch (Throwable e) {
   1028                     reportWtf("Notifying Location Service running", e);
   1029                 }
   1030                 try {
   1031                     if (countryDetectorF != null) countryDetectorF.systemRunning();
   1032                 } catch (Throwable e) {
   1033                     reportWtf("Notifying CountryDetectorService running", e);
   1034                 }
   1035                 try {
   1036                     if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
   1037                 } catch (Throwable e) {
   1038                     reportWtf("Notifying NetworkTimeService running", e);
   1039                 }
   1040                 try {
   1041                     if (commonTimeMgmtServiceF != null) commonTimeMgmtServiceF.systemRunning();
   1042                 } catch (Throwable e) {
   1043                     reportWtf("Notifying CommonTimeManagementService running", e);
   1044                 }
   1045                 try {
   1046                     if (textServiceManagerServiceF != null)
   1047                         textServiceManagerServiceF.systemRunning();
   1048                 } catch (Throwable e) {
   1049                     reportWtf("Notifying TextServicesManagerService running", e);
   1050                 }
   1051                 try {
   1052                     if (dreamyF != null) dreamyF.systemRunning();
   1053                 } catch (Throwable e) {
   1054                     reportWtf("Notifying DreamManagerService running", e);
   1055                 }
   1056                 try {
   1057                     if (atlasF != null) atlasF.systemRunning();
   1058                 } catch (Throwable e) {
   1059                     reportWtf("Notifying AssetAtlasService running", e);
   1060                 }
   1061                 try {
   1062                     // TODO(BT) Pass parameter to input manager
   1063                     if (inputManagerF != null) inputManagerF.systemRunning();
   1064                 } catch (Throwable e) {
   1065                     reportWtf("Notifying InputManagerService running", e);
   1066                 }
   1067 
   1068                 try {
   1069                     if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
   1070                 } catch (Throwable e) {
   1071                     reportWtf("Notifying TelephonyRegistry running", e);
   1072                 }
   1073 
   1074                 try {
   1075                     if (printManagerF != null) printManagerF.systemRuning();
   1076                 } catch (Throwable e) {
   1077                     reportWtf("Notifying PrintManagerService running", e);
   1078                 }
   1079 
   1080                 try {
   1081                     if (mediaRouterF != null) mediaRouterF.systemRunning();
   1082                 } catch (Throwable e) {
   1083                     reportWtf("Notifying MediaRouterService running", e);
   1084                 }
   1085             }
   1086         });
   1087 
   1088         // For debug builds, log event loop stalls to dropbox for analysis.
   1089         if (StrictMode.conditionallyEnableDebugLogging()) {
   1090             Slog.i(TAG, "Enabled StrictMode for system server main thread.");
   1091         }
   1092 
   1093         Looper.loop();
   1094         Slog.d(TAG, "System ServerThread is exiting!");
   1095     }
   1096 
   1097     static final void startSystemUi(Context context) {
   1098         Intent intent = new Intent();
   1099         intent.setComponent(new ComponentName("com.android.systemui",
   1100                     "com.android.systemui.SystemUIService"));
   1101         //Slog.d(TAG, "Starting service: " + intent);
   1102         context.startServiceAsUser(intent, UserHandle.OWNER);
   1103     }
   1104 }
   1105 
   1106 public class SystemServer {
   1107     private static final String TAG = "SystemServer";
   1108 
   1109     public static final int FACTORY_TEST_OFF = 0;
   1110     public static final int FACTORY_TEST_LOW_LEVEL = 1;
   1111     public static final int FACTORY_TEST_HIGH_LEVEL = 2;
   1112 
   1113     static Timer timer;
   1114     static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; // 1hr
   1115 
   1116     // The earliest supported time.  We pick one day into 1970, to
   1117     // give any timezone code room without going into negative time.
   1118     private static final long EARLIEST_SUPPORTED_TIME = 86400 * 1000;
   1119 
   1120     /**
   1121      * Called to initialize native system services.
   1122      */
   1123     private static native void nativeInit();
   1124 
   1125     public static void main(String[] args) {
   1126 
   1127         /*
   1128          * In case the runtime switched since last boot (such as when
   1129          * the old runtime was removed in an OTA), set the system
   1130          * property so that it is in sync. We can't do this in
   1131          * libnativehelper's JniInvocation::Init code where we already
   1132          * had to fallback to a different runtime because it is
   1133          * running as root and we need to be the system user to set
   1134          * the property. http://b/11463182
   1135          */
   1136         SystemProperties.set("persist.sys.dalvik.vm.lib",
   1137                              VMRuntime.getRuntime().vmLibrary());
   1138 
   1139         if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
   1140             // If a device's clock is before 1970 (before 0), a lot of
   1141             // APIs crash dealing with negative numbers, notably
   1142             // java.io.File#setLastModified, so instead we fake it and
   1143             // hope that time from cell towers or NTP fixes it
   1144             // shortly.
   1145             Slog.w(TAG, "System clock is before 1970; setting to 1970.");
   1146             SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
   1147         }
   1148 
   1149         if (SamplingProfilerIntegration.isEnabled()) {
   1150             SamplingProfilerIntegration.start();
   1151             timer = new Timer();
   1152             timer.schedule(new TimerTask() {
   1153                 @Override
   1154                 public void run() {
   1155                     SamplingProfilerIntegration.writeSnapshot("system_server", null);
   1156                 }
   1157             }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
   1158         }
   1159 
   1160         // Mmmmmm... more memory!
   1161         dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
   1162 
   1163         // The system server has to run all of the time, so it needs to be
   1164         // as efficient as possible with its memory usage.
   1165         VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
   1166 
   1167         Environment.setUserRequired(true);
   1168 
   1169         System.loadLibrary("android_servers");
   1170 
   1171         Slog.i(TAG, "Entered the Android system server!");
   1172 
   1173         // Initialize native services.
   1174         nativeInit();
   1175 
   1176         // This used to be its own separate thread, but now it is
   1177         // just the loop we run on the main thread.
   1178         ServerThread thr = new ServerThread();
   1179         thr.initAndLoop();
   1180     }
   1181 }
   1182