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