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