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