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