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