SystemServer.java revision cd0e839a2448deea50f79bddeba782c546b33893
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 com.android.server.am.ActivityManagerService;
20import com.android.internal.app.ShutdownThread;
21import com.android.internal.os.BinderInternal;
22import com.android.internal.os.SamplingProfilerIntegration;
23
24import dalvik.system.VMRuntime;
25import dalvik.system.Zygote;
26
27import android.accounts.AccountManagerService;
28import android.app.ActivityManagerNative;
29import android.bluetooth.BluetoothAdapter;
30import android.content.ContentResolver;
31import android.content.ContentService;
32import android.content.Context;
33import android.content.pm.IPackageManager;
34import android.content.res.Configuration;
35import android.database.ContentObserver;
36import android.media.AudioService;
37import android.os.Build;
38import android.os.Looper;
39import android.os.RemoteException;
40import android.os.ServiceManager;
41import android.os.StrictMode;
42import android.os.SystemClock;
43import android.os.SystemProperties;
44import android.provider.Contacts.People;
45import android.provider.Settings;
46import android.server.BluetoothA2dpService;
47import android.server.BluetoothService;
48import android.server.search.SearchManagerService;
49import android.util.DisplayMetrics;
50import android.util.EventLog;
51import android.util.Log;
52import android.util.Slog;
53import android.view.Display;
54import android.view.WindowManager;
55
56import java.io.File;
57import java.util.Timer;
58import java.util.TimerTask;
59
60class ServerThread extends Thread {
61    private static final String TAG = "SystemServer";
62
63    ContentResolver mContentResolver;
64
65    private class AdbSettingsObserver extends ContentObserver {
66        public AdbSettingsObserver() {
67            super(null);
68        }
69        @Override
70        public void onChange(boolean selfChange) {
71            boolean enableAdb = (Settings.Secure.getInt(mContentResolver,
72                Settings.Secure.ADB_ENABLED, 0) > 0);
73            // setting this secure property will start or stop adbd
74           SystemProperties.set("persist.service.adb.enable", enableAdb ? "1" : "0");
75        }
76    }
77
78    @Override
79    public void run() {
80        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN,
81            SystemClock.uptimeMillis());
82
83        Looper.prepare();
84
85        android.os.Process.setThreadPriority(
86                android.os.Process.THREAD_PRIORITY_FOREGROUND);
87
88        BinderInternal.disableBackgroundScheduling(true);
89        android.os.Process.setCanSelfBackground(false);
90
91        // Check whether we failed to shut down last time we tried.
92        {
93            final String shutdownAction = SystemProperties.get(
94                    ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
95            if (shutdownAction != null && shutdownAction.length() > 0) {
96                boolean reboot = (shutdownAction.charAt(0) == '1');
97
98                final String reason;
99                if (shutdownAction.length() > 1) {
100                    reason = shutdownAction.substring(1, shutdownAction.length());
101                } else {
102                    reason = null;
103                }
104
105                ShutdownThread.rebootOrShutdown(reboot, reason);
106            }
107        }
108
109        String factoryTestStr = SystemProperties.get("ro.factorytest");
110        int factoryTest = "".equals(factoryTestStr) ? SystemServer.FACTORY_TEST_OFF
111                : Integer.parseInt(factoryTestStr);
112
113        LightsService lights = null;
114        PowerManagerService power = null;
115        BatteryService battery = null;
116        ConnectivityService connectivity = null;
117        IPackageManager pm = null;
118        Context context = null;
119        WindowManagerService wm = null;
120        BluetoothService bluetooth = null;
121        BluetoothA2dpService bluetoothA2dp = null;
122        HeadsetObserver headset = null;
123        DockObserver dock = null;
124        UsbObserver usb = null;
125        UiModeManagerService uiMode = null;
126        RecognitionManagerService recognition = null;
127        ThrottleService throttle = null;
128        NetworkTimeUpdateService networkTimeUpdater = null;
129
130        // Critical services...
131        try {
132            Slog.i(TAG, "Entropy Service");
133            ServiceManager.addService("entropy", new EntropyService());
134
135            Slog.i(TAG, "Power Manager");
136            power = new PowerManagerService();
137            ServiceManager.addService(Context.POWER_SERVICE, power);
138
139            Slog.i(TAG, "Activity Manager");
140            context = ActivityManagerService.main(factoryTest);
141
142            Slog.i(TAG, "Telephony Registry");
143            ServiceManager.addService("telephony.registry", new TelephonyRegistry(context));
144
145            AttributeCache.init(context);
146
147            Slog.i(TAG, "Package Manager");
148            pm = PackageManagerService.main(context,
149                    factoryTest != SystemServer.FACTORY_TEST_OFF);
150
151            ActivityManagerService.setSystemProcess();
152
153            mContentResolver = context.getContentResolver();
154
155            // The AccountManager must come before the ContentService
156            try {
157                Slog.i(TAG, "Account Manager");
158                ServiceManager.addService(Context.ACCOUNT_SERVICE,
159                        new AccountManagerService(context));
160            } catch (Throwable e) {
161                Slog.e(TAG, "Failure starting Account Manager", e);
162            }
163
164            Slog.i(TAG, "Content Manager");
165            ContentService.main(context,
166                    factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
167
168            Slog.i(TAG, "System Content Providers");
169            ActivityManagerService.installSystemProviders();
170
171            Slog.i(TAG, "Battery Service");
172            battery = new BatteryService(context);
173            ServiceManager.addService("battery", battery);
174
175            Slog.i(TAG, "Lights Service");
176            lights = new LightsService(context);
177
178            Slog.i(TAG, "Vibrator Service");
179            ServiceManager.addService("vibrator", new VibratorService(context));
180
181            // only initialize the power service after we have started the
182            // lights service, content providers and the battery service.
183            power.init(context, lights, ActivityManagerService.getDefault(), battery);
184
185            Slog.i(TAG, "Alarm Manager");
186            AlarmManagerService alarm = new AlarmManagerService(context);
187            ServiceManager.addService(Context.ALARM_SERVICE, alarm);
188
189            Slog.i(TAG, "Init Watchdog");
190            Watchdog.getInstance().init(context, battery, power, alarm,
191                    ActivityManagerService.self());
192
193            Slog.i(TAG, "Window Manager");
194            wm = WindowManagerService.main(context, power,
195                    factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL);
196            ServiceManager.addService(Context.WINDOW_SERVICE, wm);
197
198            ((ActivityManagerService)ServiceManager.getService("activity"))
199                    .setWindowManager(wm);
200
201            // Skip Bluetooth if we have an emulator kernel
202            // TODO: Use a more reliable check to see if this product should
203            // support Bluetooth - see bug 988521
204            if (SystemProperties.get("ro.kernel.qemu").equals("1")) {
205                Slog.i(TAG, "Registering null Bluetooth Service (emulator)");
206                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);
207            } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
208                Slog.i(TAG, "Registering null Bluetooth Service (factory test)");
209                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);
210            } else {
211                Slog.i(TAG, "Bluetooth Service");
212                bluetooth = new BluetoothService(context);
213                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);
214                bluetooth.initAfterRegistration();
215                bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);
216                ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,
217                                          bluetoothA2dp);
218
219                int bluetoothOn = Settings.Secure.getInt(mContentResolver,
220                    Settings.Secure.BLUETOOTH_ON, 0);
221                if (bluetoothOn > 0) {
222                    bluetooth.enable();
223                }
224            }
225
226        } catch (RuntimeException e) {
227            Slog.e("System", "Failure starting core service", e);
228        }
229
230        DevicePolicyManagerService devicePolicy = null;
231        StatusBarManagerService statusBar = null;
232        InputMethodManagerService imm = null;
233        AppWidgetService appWidget = null;
234        NotificationManagerService notification = null;
235        WallpaperManagerService wallpaper = null;
236        LocationManagerService location = null;
237        CountryDetectorService countryDetector = null;
238
239        if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
240            try {
241                Slog.i(TAG, "Device Policy");
242                devicePolicy = new DevicePolicyManagerService(context);
243                ServiceManager.addService(Context.DEVICE_POLICY_SERVICE, devicePolicy);
244            } catch (Throwable e) {
245                Slog.e(TAG, "Failure starting DevicePolicyService", e);
246            }
247
248            try {
249                Slog.i(TAG, "Status Bar");
250                statusBar = new StatusBarManagerService(context);
251                ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
252            } catch (Throwable e) {
253                Slog.e(TAG, "Failure starting StatusBarManagerService", e);
254            }
255
256            try {
257                Slog.i(TAG, "Clipboard Service");
258                ServiceManager.addService(Context.CLIPBOARD_SERVICE,
259                        new ClipboardService(context));
260            } catch (Throwable e) {
261                Slog.e(TAG, "Failure starting Clipboard Service", e);
262            }
263
264            try {
265                Slog.i(TAG, "Input Method Service");
266                imm = new InputMethodManagerService(context, statusBar);
267                ServiceManager.addService(Context.INPUT_METHOD_SERVICE, imm);
268            } catch (Throwable e) {
269                Slog.e(TAG, "Failure starting Input Manager Service", e);
270            }
271
272            try {
273                Slog.i(TAG, "NetStat Service");
274                ServiceManager.addService("netstat", new NetStatService(context));
275            } catch (Throwable e) {
276                Slog.e(TAG, "Failure starting NetStat Service", e);
277            }
278
279            try {
280                Slog.i(TAG, "NetworkManagement Service");
281                ServiceManager.addService(
282                        Context.NETWORKMANAGEMENT_SERVICE,
283                        NetworkManagementService.create(context));
284            } catch (Throwable e) {
285                Slog.e(TAG, "Failure starting NetworkManagement Service", e);
286            }
287
288            try {
289                Slog.i(TAG, "Connectivity Service");
290                connectivity = ConnectivityService.getInstance(context);
291                ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
292            } catch (Throwable e) {
293                Slog.e(TAG, "Failure starting Connectivity Service", e);
294            }
295
296            try {
297                Slog.i(TAG, "Throttle Service");
298                throttle = new ThrottleService(context);
299                ServiceManager.addService(
300                        Context.THROTTLE_SERVICE, throttle);
301            } catch (Throwable e) {
302                Slog.e(TAG, "Failure starting ThrottleService", e);
303            }
304
305            try {
306              Slog.i(TAG, "Accessibility Manager");
307              ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
308                      new AccessibilityManagerService(context));
309            } catch (Throwable e) {
310              Slog.e(TAG, "Failure starting Accessibility Manager", e);
311            }
312
313            try {
314                /*
315                 * NotificationManagerService is dependant on MountService,
316                 * (for media / usb notifications) so we must start MountService first.
317                 */
318                Slog.i(TAG, "Mount Service");
319                ServiceManager.addService("mount", new MountService(context));
320            } catch (Throwable e) {
321                Slog.e(TAG, "Failure starting Mount Service", e);
322            }
323
324            try {
325                Slog.i(TAG, "Notification Manager");
326                notification = new NotificationManagerService(context, statusBar, lights);
327                ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification);
328            } catch (Throwable e) {
329                Slog.e(TAG, "Failure starting Notification Manager", e);
330            }
331
332            try {
333                Slog.i(TAG, "Device Storage Monitor");
334                ServiceManager.addService(DeviceStorageMonitorService.SERVICE,
335                        new DeviceStorageMonitorService(context));
336            } catch (Throwable e) {
337                Slog.e(TAG, "Failure starting DeviceStorageMonitor service", e);
338            }
339
340            try {
341                Slog.i(TAG, "Location Manager");
342                location = new LocationManagerService(context);
343                ServiceManager.addService(Context.LOCATION_SERVICE, location);
344            } catch (Throwable e) {
345                Slog.e(TAG, "Failure starting Location Manager", e);
346            }
347
348            try {
349                Slog.i(TAG, "Country Detector");
350                countryDetector = new CountryDetectorService(context);
351                ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
352            } catch (Throwable e) {
353                Slog.e(TAG, "Failure starting Country Detector", e);
354            }
355
356            try {
357                Slog.i(TAG, "Search Service");
358                ServiceManager.addService(Context.SEARCH_SERVICE,
359                        new SearchManagerService(context));
360            } catch (Throwable e) {
361                Slog.e(TAG, "Failure starting Search Service", e);
362            }
363
364            try {
365                Slog.i(TAG, "DropBox Service");
366                ServiceManager.addService(Context.DROPBOX_SERVICE,
367                        new DropBoxManagerService(context, new File("/data/system/dropbox")));
368            } catch (Throwable e) {
369                Slog.e(TAG, "Failure starting DropBoxManagerService", e);
370            }
371
372            try {
373                Slog.i(TAG, "Wallpaper Service");
374                wallpaper = new WallpaperManagerService(context);
375                ServiceManager.addService(Context.WALLPAPER_SERVICE, wallpaper);
376            } catch (Throwable e) {
377                Slog.e(TAG, "Failure starting Wallpaper Service", e);
378            }
379
380            try {
381                Slog.i(TAG, "Audio Service");
382                ServiceManager.addService(Context.AUDIO_SERVICE, new AudioService(context));
383            } catch (Throwable e) {
384                Slog.e(TAG, "Failure starting Audio Service", e);
385            }
386
387            try {
388                Slog.i(TAG, "Headset Observer");
389                // Listen for wired headset changes
390                headset = new HeadsetObserver(context);
391            } catch (Throwable e) {
392                Slog.e(TAG, "Failure starting HeadsetObserver", e);
393            }
394
395            try {
396                Slog.i(TAG, "Dock Observer");
397                // Listen for dock station changes
398                dock = new DockObserver(context, power);
399            } catch (Throwable e) {
400                Slog.e(TAG, "Failure starting DockObserver", e);
401            }
402
403            try {
404                Slog.i(TAG, "USB Observer");
405                // Listen for USB changes
406                usb = new UsbObserver(context);
407            } catch (Throwable e) {
408                Slog.e(TAG, "Failure starting UsbObserver", e);
409            }
410
411            try {
412                Slog.i(TAG, "UI Mode Manager Service");
413                // Listen for UI mode changes
414                uiMode = new UiModeManagerService(context);
415            } catch (Throwable e) {
416                Slog.e(TAG, "Failure starting UiModeManagerService", e);
417            }
418
419            try {
420                Slog.i(TAG, "Backup Service");
421                ServiceManager.addService(Context.BACKUP_SERVICE,
422                        new BackupManagerService(context));
423            } catch (Throwable e) {
424                Slog.e(TAG, "Failure starting Backup Service", e);
425            }
426
427            try {
428                Slog.i(TAG, "AppWidget Service");
429                appWidget = new AppWidgetService(context);
430                ServiceManager.addService(Context.APPWIDGET_SERVICE, appWidget);
431            } catch (Throwable e) {
432                Slog.e(TAG, "Failure starting AppWidget Service", e);
433            }
434
435            try {
436                Slog.i(TAG, "Recognition Service");
437                recognition = new RecognitionManagerService(context);
438            } catch (Throwable e) {
439                Slog.e(TAG, "Failure starting Recognition Service", e);
440            }
441
442            try {
443                Slog.i(TAG, "DiskStats Service");
444                ServiceManager.addService("diskstats", new DiskStatsService(context));
445            } catch (Throwable e) {
446                Slog.e(TAG, "Failure starting DiskStats Service", e);
447            }
448
449            try {
450                // need to add this service even if SamplingProfilerIntegration.isEnabled()
451                // is false, because it is this service that detects system property change and
452                // turns on SamplingProfilerIntegration. Plus, when sampling profiler doesn't work,
453                // there is little overhead for running this service.
454                Slog.i(TAG, "SamplingProfiler Service");
455                ServiceManager.addService("samplingprofiler",
456                            new SamplingProfilerService(context));
457            } catch (Throwable e) {
458                Slog.e(TAG, "Failure starting SamplingProfiler Service", e);
459            }
460
461            try {
462                Slog.i(TAG, "NetworkTimeUpdateService");
463                networkTimeUpdater = new NetworkTimeUpdateService(context);
464            } catch (Throwable e) {
465                Slog.e(TAG, "Failure starting NetworkTimeUpdate service");
466            }
467        }
468
469        // make sure the ADB_ENABLED setting value matches the secure property value
470        Settings.Secure.putInt(mContentResolver, Settings.Secure.ADB_ENABLED,
471                "1".equals(SystemProperties.get("persist.service.adb.enable")) ? 1 : 0);
472
473        // register observer to listen for settings changes
474        mContentResolver.registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.ADB_ENABLED),
475                false, new AdbSettingsObserver());
476
477        // Before things start rolling, be sure we have decided whether
478        // we are in safe mode.
479        final boolean safeMode = wm.detectSafeMode();
480        if (safeMode) {
481            try {
482                ActivityManagerNative.getDefault().enterSafeMode();
483                // Post the safe mode state in the Zygote class
484                Zygote.systemInSafeMode = true;
485                // Disable the JIT for the system_server process
486                VMRuntime.getRuntime().disableJitCompilation();
487            } catch (RemoteException e) {
488            }
489        } else {
490            // Enable the JIT for the system_server process
491            VMRuntime.getRuntime().startJitCompilation();
492        }
493
494        // It is now time to start up the app processes...
495
496        if (devicePolicy != null) {
497            devicePolicy.systemReady();
498        }
499
500        if (notification != null) {
501            notification.systemReady();
502        }
503
504        if (statusBar != null) {
505            statusBar.systemReady();
506        }
507        wm.systemReady();
508
509        // Update the configuration for this context by hand, because we're going
510        // to start using it before the config change done in wm.systemReady() will
511        // propagate to it.
512        Configuration config = wm.computeNewConfiguration();
513        DisplayMetrics metrics = new DisplayMetrics();
514        WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
515        w.getDefaultDisplay().getMetrics(metrics);
516        context.getResources().updateConfiguration(config, metrics);
517
518        power.systemReady();
519        try {
520            pm.systemReady();
521        } catch (RemoteException e) {
522        }
523
524        // These are needed to propagate to the runnable below.
525        final StatusBarManagerService statusBarF = statusBar;
526        final BatteryService batteryF = battery;
527        final ConnectivityService connectivityF = connectivity;
528        final DockObserver dockF = dock;
529        final UsbObserver usbF = usb;
530        final ThrottleService throttleF = throttle;
531        final UiModeManagerService uiModeF = uiMode;
532        final AppWidgetService appWidgetF = appWidget;
533        final WallpaperManagerService wallpaperF = wallpaper;
534        final InputMethodManagerService immF = imm;
535        final RecognitionManagerService recognitionF = recognition;
536        final LocationManagerService locationF = location;
537        final CountryDetectorService countryDetectorF = countryDetector;
538        final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
539
540        // We now tell the activity manager it is okay to run third party
541        // code.  It will call back into us once it has gotten to the state
542        // where third party code can really run (but before it has actually
543        // started launching the initial applications), for us to complete our
544        // initialization.
545        ((ActivityManagerService)ActivityManagerNative.getDefault())
546                .systemReady(new Runnable() {
547            public void run() {
548                Slog.i(TAG, "Making services ready");
549
550                if (statusBarF != null) statusBarF.systemReady2();
551                if (batteryF != null) batteryF.systemReady();
552                if (connectivityF != null) connectivityF.systemReady();
553                if (dockF != null) dockF.systemReady();
554                if (usbF != null) usbF.systemReady();
555                if (uiModeF != null) uiModeF.systemReady();
556                if (recognitionF != null) recognitionF.systemReady();
557                Watchdog.getInstance().start();
558
559                // It is now okay to let the various system services start their
560                // third party code...
561
562                if (appWidgetF != null) appWidgetF.systemReady(safeMode);
563                if (wallpaperF != null) wallpaperF.systemReady();
564                if (immF != null) immF.systemReady();
565                if (locationF != null) locationF.systemReady();
566                if (countryDetectorF != null) countryDetectorF.systemReady();
567                if (throttleF != null) throttleF.systemReady();
568                if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemReady();
569            }
570        });
571
572        // For debug builds, log event loop stalls to dropbox for analysis.
573        if (StrictMode.conditionallyEnableDebugLogging()) {
574            Slog.i(TAG, "Enabled StrictMode for system server main thread.");
575        }
576
577        Looper.loop();
578        Slog.d(TAG, "System ServerThread is exiting!");
579    }
580}
581
582public class SystemServer {
583    private static final String TAG = "SystemServer";
584
585    public static final int FACTORY_TEST_OFF = 0;
586    public static final int FACTORY_TEST_LOW_LEVEL = 1;
587    public static final int FACTORY_TEST_HIGH_LEVEL = 2;
588
589    static Timer timer;
590    static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; // 1hr
591
592    // The earliest supported time.  We pick one day into 1970, to
593    // give any timezone code room without going into negative time.
594    private static final long EARLIEST_SUPPORTED_TIME = 86400 * 1000;
595
596    /**
597     * This method is called from Zygote to initialize the system. This will cause the native
598     * services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back
599     * up into init2() to start the Android services.
600     */
601    native public static void init1(String[] args);
602
603    public static void main(String[] args) {
604        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
605            // If a device's clock is before 1970 (before 0), a lot of
606            // APIs crash dealing with negative numbers, notably
607            // java.io.File#setLastModified, so instead we fake it and
608            // hope that time from cell towers or NTP fixes it
609            // shortly.
610            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
611            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
612        }
613
614        if (SamplingProfilerIntegration.isEnabled()) {
615            SamplingProfilerIntegration.start();
616            timer = new Timer();
617            timer.schedule(new TimerTask() {
618                @Override
619                public void run() {
620                    SamplingProfilerIntegration.writeSnapshot("system_server", null);
621                }
622            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
623        }
624
625        // The system server has to run all of the time, so it needs to be
626        // as efficient as possible with its memory usage.
627        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
628
629        System.loadLibrary("android_servers");
630        init1(args);
631    }
632
633    public static final void init2() {
634        Slog.i(TAG, "Entered the Android system server!");
635        Thread thr = new ServerThread();
636        thr.setName("android.server.ServerThread");
637        thr.start();
638    }
639}
640