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