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