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