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