SystemServer.java revision 2992ea782fa61780d8e0de7a36a2a84622f8694b
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, "No Bluetooh Service (emulator)");
208            } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
209                Slog.i(TAG, "No Bluetooth Service (factory test)");
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                bluetooth.initAfterA2dpRegistration();
219
220                int bluetoothOn = Settings.Secure.getInt(mContentResolver,
221                    Settings.Secure.BLUETOOTH_ON, 0);
222                if (bluetoothOn > 0) {
223                    bluetooth.enable();
224                }
225            }
226
227        } catch (RuntimeException e) {
228            Slog.e("System", "Failure starting core service", e);
229        }
230
231        DevicePolicyManagerService devicePolicy = null;
232        StatusBarManagerService statusBar = null;
233        InputMethodManagerService imm = null;
234        AppWidgetService appWidget = null;
235        NotificationManagerService notification = null;
236        WallpaperManagerService wallpaper = null;
237        LocationManagerService location = null;
238        CountryDetectorService countryDetector = null;
239
240        if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
241            try {
242                Slog.i(TAG, "Device Policy");
243                devicePolicy = new DevicePolicyManagerService(context);
244                ServiceManager.addService(Context.DEVICE_POLICY_SERVICE, devicePolicy);
245            } catch (Throwable e) {
246                Slog.e(TAG, "Failure starting DevicePolicyService", e);
247            }
248
249            try {
250                Slog.i(TAG, "Status Bar");
251                statusBar = new StatusBarManagerService(context, wm);
252                ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
253            } catch (Throwable e) {
254                Slog.e(TAG, "Failure starting StatusBarManagerService", e);
255            }
256
257            try {
258                Slog.i(TAG, "Clipboard Service");
259                ServiceManager.addService(Context.CLIPBOARD_SERVICE,
260                        new ClipboardService(context));
261            } catch (Throwable e) {
262                Slog.e(TAG, "Failure starting Clipboard Service", e);
263            }
264
265            try {
266                Slog.i(TAG, "Input Method Service");
267                imm = new InputMethodManagerService(context, statusBar);
268                ServiceManager.addService(Context.INPUT_METHOD_SERVICE, imm);
269            } catch (Throwable e) {
270                Slog.e(TAG, "Failure starting Input Manager Service", e);
271            }
272
273            try {
274                Slog.i(TAG, "NetStat Service");
275                ServiceManager.addService("netstat", new NetStatService(context));
276            } catch (Throwable e) {
277                Slog.e(TAG, "Failure starting NetStat Service", e);
278            }
279
280            try {
281                Slog.i(TAG, "NetworkManagement Service");
282                ServiceManager.addService(
283                        Context.NETWORKMANAGEMENT_SERVICE,
284                        NetworkManagementService.create(context));
285            } catch (Throwable e) {
286                Slog.e(TAG, "Failure starting NetworkManagement Service", e);
287            }
288
289            try {
290                Slog.i(TAG, "Connectivity Service");
291                connectivity = ConnectivityService.getInstance(context);
292                ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
293            } catch (Throwable e) {
294                Slog.e(TAG, "Failure starting Connectivity Service", e);
295            }
296
297            try {
298                Slog.i(TAG, "Throttle Service");
299                throttle = new ThrottleService(context);
300                ServiceManager.addService(
301                        Context.THROTTLE_SERVICE, throttle);
302            } catch (Throwable e) {
303                Slog.e(TAG, "Failure starting ThrottleService", e);
304            }
305
306            try {
307              Slog.i(TAG, "Accessibility Manager");
308              ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
309                      new AccessibilityManagerService(context));
310            } catch (Throwable e) {
311              Slog.e(TAG, "Failure starting Accessibility Manager", e);
312            }
313
314            try {
315                /*
316                 * NotificationManagerService is dependant on MountService,
317                 * (for media / usb notifications) so we must start MountService first.
318                 */
319                Slog.i(TAG, "Mount Service");
320                ServiceManager.addService("mount", new MountService(context));
321            } catch (Throwable e) {
322                Slog.e(TAG, "Failure starting Mount Service", e);
323            }
324
325            try {
326                Slog.i(TAG, "Notification Manager");
327                notification = new NotificationManagerService(context, statusBar, lights);
328                ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification);
329            } catch (Throwable e) {
330                Slog.e(TAG, "Failure starting Notification Manager", e);
331            }
332
333            try {
334                Slog.i(TAG, "Device Storage Monitor");
335                ServiceManager.addService(DeviceStorageMonitorService.SERVICE,
336                        new DeviceStorageMonitorService(context));
337            } catch (Throwable e) {
338                Slog.e(TAG, "Failure starting DeviceStorageMonitor service", e);
339            }
340
341            try {
342                Slog.i(TAG, "Location Manager");
343                location = new LocationManagerService(context);
344                ServiceManager.addService(Context.LOCATION_SERVICE, location);
345            } catch (Throwable e) {
346                Slog.e(TAG, "Failure starting Location Manager", e);
347            }
348
349            try {
350                Slog.i(TAG, "Country Detector");
351                countryDetector = new CountryDetectorService(context);
352                ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
353            } catch (Throwable e) {
354                Slog.e(TAG, "Failure starting Country Detector", e);
355            }
356
357            try {
358                Slog.i(TAG, "Search Service");
359                ServiceManager.addService(Context.SEARCH_SERVICE,
360                        new SearchManagerService(context));
361            } catch (Throwable e) {
362                Slog.e(TAG, "Failure starting Search Service", e);
363            }
364
365            try {
366                Slog.i(TAG, "DropBox Service");
367                ServiceManager.addService(Context.DROPBOX_SERVICE,
368                        new DropBoxManagerService(context, new File("/data/system/dropbox")));
369            } catch (Throwable e) {
370                Slog.e(TAG, "Failure starting DropBoxManagerService", e);
371            }
372
373            try {
374                Slog.i(TAG, "Wallpaper Service");
375                wallpaper = new WallpaperManagerService(context);
376                ServiceManager.addService(Context.WALLPAPER_SERVICE, wallpaper);
377            } catch (Throwable e) {
378                Slog.e(TAG, "Failure starting Wallpaper Service", e);
379            }
380
381            try {
382                Slog.i(TAG, "Audio Service");
383                ServiceManager.addService(Context.AUDIO_SERVICE, new AudioService(context));
384            } catch (Throwable e) {
385                Slog.e(TAG, "Failure starting Audio Service", e);
386            }
387
388            try {
389                Slog.i(TAG, "Dock Observer");
390                // Listen for dock station changes
391                dock = new DockObserver(context, power);
392            } catch (Throwable e) {
393                Slog.e(TAG, "Failure starting DockObserver", e);
394            }
395
396            try {
397                Slog.i(TAG, "Wired Accessory Observer");
398                // Listen for wired headset changes
399                wiredAccessory = new WiredAccessoryObserver(context);
400            } catch (Throwable e) {
401                Slog.e(TAG, "Failure starting WiredAccessoryObserver", e);
402            }
403
404            try {
405                Slog.i(TAG, "USB Observer");
406                // Listen for USB changes
407                usb = new UsbService(context);
408            } catch (Throwable e) {
409                Slog.e(TAG, "Failure starting UsbService", e);
410            }
411
412            try {
413                Slog.i(TAG, "UI Mode Manager Service");
414                // Listen for UI mode changes
415                uiMode = new UiModeManagerService(context);
416            } catch (Throwable e) {
417                Slog.e(TAG, "Failure starting UiModeManagerService", e);
418            }
419
420            try {
421                Slog.i(TAG, "Backup Service");
422                ServiceManager.addService(Context.BACKUP_SERVICE,
423                        new BackupManagerService(context));
424            } catch (Throwable e) {
425                Slog.e(TAG, "Failure starting Backup Service", e);
426            }
427
428            try {
429                Slog.i(TAG, "AppWidget Service");
430                appWidget = new AppWidgetService(context);
431                ServiceManager.addService(Context.APPWIDGET_SERVICE, appWidget);
432            } catch (Throwable e) {
433                Slog.e(TAG, "Failure starting AppWidget Service", e);
434            }
435
436            try {
437                Slog.i(TAG, "Recognition Service");
438                recognition = new RecognitionManagerService(context);
439            } catch (Throwable e) {
440                Slog.e(TAG, "Failure starting Recognition Service", e);
441            }
442
443            try {
444                Slog.i(TAG, "DiskStats Service");
445                ServiceManager.addService("diskstats", new DiskStatsService(context));
446            } catch (Throwable e) {
447                Slog.e(TAG, "Failure starting DiskStats Service", e);
448            }
449
450            try {
451                // need to add this service even if SamplingProfilerIntegration.isEnabled()
452                // is false, because it is this service that detects system property change and
453                // turns on SamplingProfilerIntegration. Plus, when sampling profiler doesn't work,
454                // there is little overhead for running this service.
455                Slog.i(TAG, "SamplingProfiler Service");
456                ServiceManager.addService("samplingprofiler",
457                            new SamplingProfilerService(context));
458            } catch (Throwable e) {
459                Slog.e(TAG, "Failure starting SamplingProfiler Service", e);
460            }
461
462            try {
463                Slog.i(TAG, "NetworkTimeUpdateService");
464                networkTimeUpdater = new NetworkTimeUpdateService(context);
465            } catch (Throwable e) {
466                Slog.e(TAG, "Failure starting NetworkTimeUpdate service");
467            }
468        }
469
470        // make sure the ADB_ENABLED setting value matches the secure property value
471        Settings.Secure.putInt(mContentResolver, Settings.Secure.ADB_ENABLED,
472                "1".equals(SystemProperties.get("persist.service.adb.enable")) ? 1 : 0);
473
474        // register observer to listen for settings changes
475        mContentResolver.registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.ADB_ENABLED),
476                false, new AdbSettingsObserver());
477
478        // Before things start rolling, be sure we have decided whether
479        // we are in safe mode.
480        final boolean safeMode = wm.detectSafeMode();
481        if (safeMode) {
482            ActivityManagerService.self().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        } else {
488            // Enable the JIT for the system_server process
489            VMRuntime.getRuntime().startJitCompilation();
490        }
491
492        // It is now time to start up the app processes...
493
494        if (devicePolicy != null) {
495            devicePolicy.systemReady();
496        }
497
498        if (notification != null) {
499            notification.systemReady();
500        }
501
502        wm.systemReady();
503
504        if (safeMode) {
505            ActivityManagerService.self().showSafeModeOverlay();
506        }
507
508        // Update the configuration for this context by hand, because we're going
509        // to start using it before the config change done in wm.systemReady() will
510        // propagate to it.
511        Configuration config = wm.computeNewConfiguration();
512        DisplayMetrics metrics = new DisplayMetrics();
513        WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
514        w.getDefaultDisplay().getMetrics(metrics);
515        context.getResources().updateConfiguration(config, metrics);
516
517        power.systemReady();
518        try {
519            pm.systemReady();
520        } catch (RemoteException e) {
521        }
522
523        // These are needed to propagate to the runnable below.
524        final Context contextF = context;
525        final BatteryService batteryF = battery;
526        final ConnectivityService connectivityF = connectivity;
527        final DockObserver dockF = dock;
528        final UsbService usbF = usb;
529        final ThrottleService throttleF = throttle;
530        final UiModeManagerService uiModeF = uiMode;
531        final AppWidgetService appWidgetF = appWidget;
532        final WallpaperManagerService wallpaperF = wallpaper;
533        final InputMethodManagerService immF = imm;
534        final RecognitionManagerService recognitionF = recognition;
535        final LocationManagerService locationF = location;
536        final CountryDetectorService countryDetectorF = countryDetector;
537        final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
538
539        // We now tell the activity manager it is okay to run third party
540        // code.  It will call back into us once it has gotten to the state
541        // where third party code can really run (but before it has actually
542        // started launching the initial applications), for us to complete our
543        // initialization.
544        ((ActivityManagerService)ActivityManagerNative.getDefault())
545                .systemReady(new Runnable() {
546            public void run() {
547                Slog.i(TAG, "Making services ready");
548
549                startSystemUi(contextF);
550                if (batteryF != null) batteryF.systemReady();
551                if (connectivityF != null) connectivityF.systemReady();
552                if (dockF != null) dockF.systemReady();
553                if (usbF != null) usbF.systemReady();
554                if (uiModeF != null) uiModeF.systemReady();
555                if (recognitionF != null) recognitionF.systemReady();
556                Watchdog.getInstance().start();
557
558                // It is now okay to let the various system services start their
559                // third party code...
560
561                if (appWidgetF != null) appWidgetF.systemReady(safeMode);
562                if (wallpaperF != null) wallpaperF.systemReady();
563                if (immF != null) immF.systemReady();
564                if (locationF != null) locationF.systemReady();
565                if (countryDetectorF != null) countryDetectorF.systemReady();
566                if (throttleF != null) throttleF.systemReady();
567                if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemReady();
568            }
569        });
570
571        // For debug builds, log event loop stalls to dropbox for analysis.
572        if (StrictMode.conditionallyEnableDebugLogging()) {
573            Slog.i(TAG, "Enabled StrictMode for system server main thread.");
574        }
575
576        Looper.loop();
577        Slog.d(TAG, "System ServerThread is exiting!");
578    }
579
580    static final void startSystemUi(Context context) {
581        Intent intent = new Intent();
582        intent.setComponent(new ComponentName("com.android.systemui",
583                    "com.android.systemui.SystemUIService"));
584        Slog.d(TAG, "Starting service: " + intent);
585        context.startService(intent);
586    }
587}
588
589public class SystemServer {
590    private static final String TAG = "SystemServer";
591
592    public static final int FACTORY_TEST_OFF = 0;
593    public static final int FACTORY_TEST_LOW_LEVEL = 1;
594    public static final int FACTORY_TEST_HIGH_LEVEL = 2;
595
596    static Timer timer;
597    static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; // 1hr
598
599    // The earliest supported time.  We pick one day into 1970, to
600    // give any timezone code room without going into negative time.
601    private static final long EARLIEST_SUPPORTED_TIME = 86400 * 1000;
602
603    /**
604     * This method is called from Zygote to initialize the system. This will cause the native
605     * services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back
606     * up into init2() to start the Android services.
607     */
608    native public static void init1(String[] args);
609
610    public static void main(String[] args) {
611        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
612            // If a device's clock is before 1970 (before 0), a lot of
613            // APIs crash dealing with negative numbers, notably
614            // java.io.File#setLastModified, so instead we fake it and
615            // hope that time from cell towers or NTP fixes it
616            // shortly.
617            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
618            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
619        }
620
621        if (SamplingProfilerIntegration.isEnabled()) {
622            SamplingProfilerIntegration.start();
623            timer = new Timer();
624            timer.schedule(new TimerTask() {
625                @Override
626                public void run() {
627                    SamplingProfilerIntegration.writeSnapshot("system_server", null);
628                }
629            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
630        }
631
632        // The system server has to run all of the time, so it needs to be
633        // as efficient as possible with its memory usage.
634        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
635
636        System.loadLibrary("android_servers");
637        init1(args);
638    }
639
640    public static final void init2() {
641        Slog.i(TAG, "Entered the Android system server!");
642        Thread thr = new ServerThread();
643        thr.setName("android.server.ServerThread");
644        thr.start();
645    }
646}
647