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