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