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