SystemServer.java revision 62c82e4d92cc0b856059f905d81885f7808a0e7d
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.Dream;
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 Observer");
635                // Listen for wired headset changes
636                new WiredAccessoryObserver(context);
637            } catch (Throwable e) {
638                reportWtf("starting WiredAccessoryObserver", e);
639            }
640
641            try {
642                Slog.i(TAG, "USB Service");
643                // Manage USB host and device support
644                usb = new UsbService(context);
645                ServiceManager.addService(Context.USB_SERVICE, usb);
646            } catch (Throwable e) {
647                reportWtf("starting UsbService", e);
648            }
649
650            try {
651                Slog.i(TAG, "Serial Service");
652                // Serial port support
653                serial = new SerialService(context);
654                ServiceManager.addService(Context.SERIAL_SERVICE, serial);
655            } catch (Throwable e) {
656                Slog.e(TAG, "Failure starting SerialService", e);
657            }
658
659            try {
660                Slog.i(TAG, "Twilight Service");
661                twilight = new TwilightService(context);
662            } catch (Throwable e) {
663                reportWtf("starting TwilightService", e);
664            }
665
666            try {
667                Slog.i(TAG, "UI Mode Manager Service");
668                // Listen for UI mode changes
669                uiMode = new UiModeManagerService(context, twilight);
670            } catch (Throwable e) {
671                reportWtf("starting UiModeManagerService", e);
672            }
673
674            try {
675                Slog.i(TAG, "Backup Service");
676                ServiceManager.addService(Context.BACKUP_SERVICE,
677                        new BackupManagerService(context));
678            } catch (Throwable e) {
679                Slog.e(TAG, "Failure starting Backup Service", e);
680            }
681
682            try {
683                Slog.i(TAG, "AppWidget Service");
684                appWidget = new AppWidgetService(context);
685                ServiceManager.addService(Context.APPWIDGET_SERVICE, appWidget);
686            } catch (Throwable e) {
687                reportWtf("starting AppWidget Service", e);
688            }
689
690            try {
691                Slog.i(TAG, "Recognition Service");
692                recognition = new RecognitionManagerService(context);
693            } catch (Throwable e) {
694                reportWtf("starting Recognition Service", e);
695            }
696
697            try {
698                Slog.i(TAG, "DiskStats Service");
699                ServiceManager.addService("diskstats", new DiskStatsService(context));
700            } catch (Throwable e) {
701                reportWtf("starting DiskStats Service", e);
702            }
703
704            try {
705                // need to add this service even if SamplingProfilerIntegration.isEnabled()
706                // is false, because it is this service that detects system property change and
707                // turns on SamplingProfilerIntegration. Plus, when sampling profiler doesn't work,
708                // there is little overhead for running this service.
709                Slog.i(TAG, "SamplingProfiler Service");
710                ServiceManager.addService("samplingprofiler",
711                            new SamplingProfilerService(context));
712            } catch (Throwable e) {
713                reportWtf("starting SamplingProfiler Service", e);
714            }
715
716            try {
717                Slog.i(TAG, "NetworkTimeUpdateService");
718                networkTimeUpdater = new NetworkTimeUpdateService(context);
719            } catch (Throwable e) {
720                reportWtf("starting NetworkTimeUpdate service", e);
721            }
722
723            try {
724                Slog.i(TAG, "CommonTimeManagementService");
725                commonTimeMgmtService = new CommonTimeManagementService(context);
726                ServiceManager.addService("commontime_management", commonTimeMgmtService);
727            } catch (Throwable e) {
728                reportWtf("starting CommonTimeManagementService service", e);
729            }
730
731            try {
732                Slog.i(TAG, "CertBlacklister");
733                CertBlacklister blacklister = new CertBlacklister(context);
734            } catch (Throwable e) {
735                reportWtf("starting CertBlacklister", e);
736            }
737
738            if (context.getResources().getBoolean(
739                    com.android.internal.R.bool.config_enableDreams)) {
740                try {
741                    Slog.i(TAG, "Dreams Service");
742                    // Dreams (interactive idle-time views, a/k/a screen savers)
743                    dreamy = new DreamManagerService(context, wmHandler);
744                    ServiceManager.addService(Dream.DREAM_SERVICE, dreamy);
745                } catch (Throwable e) {
746                    reportWtf("starting DreamManagerService", e);
747                }
748            }
749        }
750
751        // Before things start rolling, be sure we have decided whether
752        // we are in safe mode.
753        final boolean safeMode = wm.detectSafeMode();
754        if (safeMode) {
755            ActivityManagerService.self().enterSafeMode();
756            // Post the safe mode state in the Zygote class
757            Zygote.systemInSafeMode = true;
758            // Disable the JIT for the system_server process
759            VMRuntime.getRuntime().disableJitCompilation();
760        } else {
761            // Enable the JIT for the system_server process
762            VMRuntime.getRuntime().startJitCompilation();
763        }
764
765        // It is now time to start up the app processes...
766
767        try {
768            vibrator.systemReady();
769        } catch (Throwable e) {
770            reportWtf("making Vibrator Service ready", e);
771        }
772
773        try {
774            lockSettings.systemReady();
775        } catch (Throwable e) {
776            reportWtf("making Lock Settings Service ready", e);
777        }
778
779        if (devicePolicy != null) {
780            try {
781                devicePolicy.systemReady();
782            } catch (Throwable e) {
783                reportWtf("making Device Policy Service ready", e);
784            }
785        }
786
787        if (notification != null) {
788            try {
789                notification.systemReady();
790            } catch (Throwable e) {
791                reportWtf("making Notification Service ready", e);
792            }
793        }
794
795        try {
796            wm.systemReady();
797        } catch (Throwable e) {
798            reportWtf("making Window Manager Service ready", e);
799        }
800
801        if (safeMode) {
802            ActivityManagerService.self().showSafeModeOverlay();
803        }
804
805        // Update the configuration for this context by hand, because we're going
806        // to start using it before the config change done in wm.systemReady() will
807        // propagate to it.
808        Configuration config = wm.computeNewConfiguration();
809        DisplayMetrics metrics = new DisplayMetrics();
810        WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
811        w.getDefaultDisplay().getMetrics(metrics);
812        context.getResources().updateConfiguration(config, metrics);
813
814        try {
815            power.systemReady(twilight, dreamy);
816        } catch (Throwable e) {
817            reportWtf("making Power Manager Service ready", e);
818        }
819
820        try {
821            pm.systemReady();
822        } catch (Throwable e) {
823            reportWtf("making Package Manager Service ready", e);
824        }
825
826        try {
827            display.systemReady(safeMode, onlyCore);
828        } catch (Throwable e) {
829            reportWtf("making Display Manager Service ready", e);
830        }
831
832        // These are needed to propagate to the runnable below.
833        final Context contextF = context;
834        final MountService mountServiceF = mountService;
835        final BatteryService batteryF = battery;
836        final NetworkManagementService networkManagementF = networkManagement;
837        final NetworkStatsService networkStatsF = networkStats;
838        final NetworkPolicyManagerService networkPolicyF = networkPolicy;
839        final ConnectivityService connectivityF = connectivity;
840        final DockObserver dockF = dock;
841        final UsbService usbF = usb;
842        final ThrottleService throttleF = throttle;
843        final TwilightService twilightF = twilight;
844        final UiModeManagerService uiModeF = uiMode;
845        final AppWidgetService appWidgetF = appWidget;
846        final WallpaperManagerService wallpaperF = wallpaper;
847        final InputMethodManagerService immF = imm;
848        final RecognitionManagerService recognitionF = recognition;
849        final LocationManagerService locationF = location;
850        final CountryDetectorService countryDetectorF = countryDetector;
851        final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
852        final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService;
853        final TextServicesManagerService textServiceManagerServiceF = tsms;
854        final StatusBarManagerService statusBarF = statusBar;
855        final DreamManagerService dreamyF = dreamy;
856        final InputManagerService inputManagerF = inputManager;
857        final TelephonyRegistry telephonyRegistryF = telephonyRegistry;
858
859        // We now tell the activity manager it is okay to run third party
860        // code.  It will call back into us once it has gotten to the state
861        // where third party code can really run (but before it has actually
862        // started launching the initial applications), for us to complete our
863        // initialization.
864        ActivityManagerService.self().systemReady(new Runnable() {
865            public void run() {
866                Slog.i(TAG, "Making services ready");
867
868                if (!headless) startSystemUi(contextF);
869                try {
870                    if (mountServiceF != null) mountServiceF.systemReady();
871                } catch (Throwable e) {
872                    reportWtf("making Mount Service ready", e);
873                }
874                try {
875                    if (batteryF != null) batteryF.systemReady();
876                } catch (Throwable e) {
877                    reportWtf("making Battery Service ready", e);
878                }
879                try {
880                    if (networkManagementF != null) networkManagementF.systemReady();
881                } catch (Throwable e) {
882                    reportWtf("making Network Managment Service ready", e);
883                }
884                try {
885                    if (networkStatsF != null) networkStatsF.systemReady();
886                } catch (Throwable e) {
887                    reportWtf("making Network Stats Service ready", e);
888                }
889                try {
890                    if (networkPolicyF != null) networkPolicyF.systemReady();
891                } catch (Throwable e) {
892                    reportWtf("making Network Policy Service ready", e);
893                }
894                try {
895                    if (connectivityF != null) connectivityF.systemReady();
896                } catch (Throwable e) {
897                    reportWtf("making Connectivity Service ready", e);
898                }
899                try {
900                    if (dockF != null) dockF.systemReady();
901                } catch (Throwable e) {
902                    reportWtf("making Dock Service ready", e);
903                }
904                try {
905                    if (usbF != null) usbF.systemReady();
906                } catch (Throwable e) {
907                    reportWtf("making USB Service ready", e);
908                }
909                try {
910                    if (twilightF != null) twilightF.systemReady();
911                } catch (Throwable e) {
912                    reportWtf("makin Twilight Service ready", e);
913                }
914                try {
915                    if (uiModeF != null) uiModeF.systemReady();
916                } catch (Throwable e) {
917                    reportWtf("making UI Mode Service ready", e);
918                }
919                try {
920                    if (recognitionF != null) recognitionF.systemReady();
921                } catch (Throwable e) {
922                    reportWtf("making Recognition Service ready", e);
923                }
924                Watchdog.getInstance().start();
925
926                // It is now okay to let the various system services start their
927                // third party code...
928
929                try {
930                    if (appWidgetF != null) appWidgetF.systemReady(safeMode);
931                } catch (Throwable e) {
932                    reportWtf("making App Widget Service ready", e);
933                }
934                try {
935                    if (wallpaperF != null) wallpaperF.systemReady();
936                } catch (Throwable e) {
937                    reportWtf("making Wallpaper Service ready", e);
938                }
939                try {
940                    if (immF != null) immF.systemReady(statusBarF);
941                } catch (Throwable e) {
942                    reportWtf("making Input Method Service ready", e);
943                }
944                try {
945                    if (locationF != null) locationF.systemReady();
946                } catch (Throwable e) {
947                    reportWtf("making Location Service ready", e);
948                }
949                try {
950                    if (countryDetectorF != null) countryDetectorF.systemReady();
951                } catch (Throwable e) {
952                    reportWtf("making Country Detector Service ready", e);
953                }
954                try {
955                    if (throttleF != null) throttleF.systemReady();
956                } catch (Throwable e) {
957                    reportWtf("making Throttle Service ready", e);
958                }
959                try {
960                    if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemReady();
961                } catch (Throwable e) {
962                    reportWtf("making Network Time Service ready", e);
963                }
964                try {
965                    if (commonTimeMgmtServiceF != null) commonTimeMgmtServiceF.systemReady();
966                } catch (Throwable e) {
967                    reportWtf("making Common time management service ready", e);
968                }
969                try {
970                    if (textServiceManagerServiceF != null) textServiceManagerServiceF.systemReady();
971                } catch (Throwable e) {
972                    reportWtf("making Text Services Manager Service ready", e);
973                }
974                try {
975                    if (dreamyF != null) dreamyF.systemReady();
976                } catch (Throwable e) {
977                    reportWtf("making DreamManagerService ready", e);
978                }
979                try {
980                    // TODO(BT) Pass parameter to input manager
981                    if (inputManagerF != null) inputManagerF.systemReady();
982                } catch (Throwable e) {
983                    reportWtf("making InputManagerService ready", e);
984                }
985                try {
986                    if (telephonyRegistryF != null) telephonyRegistryF.systemReady();
987                } catch (Throwable e) {
988                    reportWtf("making TelephonyRegistry ready", e);
989                }
990            }
991        });
992
993        // For debug builds, log event loop stalls to dropbox for analysis.
994        if (StrictMode.conditionallyEnableDebugLogging()) {
995            Slog.i(TAG, "Enabled StrictMode for system server main thread.");
996        }
997
998        Looper.loop();
999        Slog.d(TAG, "System ServerThread is exiting!");
1000    }
1001
1002    static final void startSystemUi(Context context) {
1003        Intent intent = new Intent();
1004        intent.setComponent(new ComponentName("com.android.systemui",
1005                    "com.android.systemui.SystemUIService"));
1006        Slog.d(TAG, "Starting service: " + intent);
1007        context.startService(intent);
1008    }
1009}
1010
1011public class SystemServer {
1012    private static final String TAG = "SystemServer";
1013
1014    public static final int FACTORY_TEST_OFF = 0;
1015    public static final int FACTORY_TEST_LOW_LEVEL = 1;
1016    public static final int FACTORY_TEST_HIGH_LEVEL = 2;
1017
1018    static Timer timer;
1019    static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; // 1hr
1020
1021    // The earliest supported time.  We pick one day into 1970, to
1022    // give any timezone code room without going into negative time.
1023    private static final long EARLIEST_SUPPORTED_TIME = 86400 * 1000;
1024
1025    /**
1026     * This method is called from Zygote to initialize the system. This will cause the native
1027     * services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back
1028     * up into init2() to start the Android services.
1029     */
1030    native public static void init1(String[] args);
1031
1032    public static void main(String[] args) {
1033        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
1034            // If a device's clock is before 1970 (before 0), a lot of
1035            // APIs crash dealing with negative numbers, notably
1036            // java.io.File#setLastModified, so instead we fake it and
1037            // hope that time from cell towers or NTP fixes it
1038            // shortly.
1039            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
1040            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
1041        }
1042
1043        if (SamplingProfilerIntegration.isEnabled()) {
1044            SamplingProfilerIntegration.start();
1045            timer = new Timer();
1046            timer.schedule(new TimerTask() {
1047                @Override
1048                public void run() {
1049                    SamplingProfilerIntegration.writeSnapshot("system_server", null);
1050                }
1051            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
1052        }
1053
1054        // Mmmmmm... more memory!
1055        dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
1056
1057        // The system server has to run all of the time, so it needs to be
1058        // as efficient as possible with its memory usage.
1059        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
1060
1061        System.loadLibrary("android_servers");
1062        init1(args);
1063    }
1064
1065    public static final void init2() {
1066        Slog.i(TAG, "Entered the Android system server!");
1067        Thread thr = new ServerThread();
1068        thr.setName("android.server.ServerThread");
1069        thr.start();
1070    }
1071}
1072