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