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