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