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