SystemServer.java revision 2ea983a567bf536f71dd620e1b215d5aeebce531
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 android.app.ActivityManagerNative;
20import android.app.ActivityThread;
21import android.app.IAlarmManager;
22import android.app.INotificationManager;
23import android.bluetooth.BluetoothAdapter;
24import android.content.ComponentName;
25import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.IPackageManager;
29import android.content.pm.PackageManager;
30import android.content.res.Configuration;
31import android.media.AudioService;
32import android.net.wifi.p2p.WifiP2pService;
33import android.os.Environment;
34import android.os.FactoryTest;
35import android.os.Handler;
36import android.os.IBinder;
37import android.os.IPowerManager;
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.os.UserHandle;
45import android.service.dreams.DreamService;
46import android.util.DisplayMetrics;
47import android.util.EventLog;
48import android.util.Log;
49import android.util.Slog;
50import android.view.WindowManager;
51
52import com.android.internal.R;
53import com.android.internal.os.BinderInternal;
54import com.android.internal.os.SamplingProfilerIntegration;
55import com.android.server.accounts.AccountManagerService;
56import com.android.server.am.ActivityManagerService;
57import com.android.server.am.BatteryStatsService;
58import com.android.server.clipboard.ClipboardService;
59import com.android.server.content.ContentService;
60import com.android.server.display.DisplayManagerService;
61import com.android.server.dreams.DreamManagerService;
62import com.android.server.input.InputManagerService;
63import com.android.server.lights.LightsManager;
64import com.android.server.lights.LightsService;
65import com.android.server.media.MediaRouterService;
66import com.android.server.net.NetworkPolicyManagerService;
67import com.android.server.net.NetworkStatsService;
68import com.android.server.notification.NotificationManagerService;
69import com.android.server.os.SchedulingPolicyService;
70import com.android.server.pm.Installer;
71import com.android.server.pm.PackageManagerService;
72import com.android.server.pm.UserManagerService;
73import com.android.server.power.PowerManagerService;
74import com.android.server.power.ShutdownThread;
75import com.android.server.search.SearchManagerService;
76import com.android.server.statusbar.StatusBarManagerService;
77import com.android.server.storage.DeviceStorageMonitorService;
78import com.android.server.twilight.TwilightService;
79import com.android.server.usb.UsbService;
80import com.android.server.wallpaper.WallpaperManagerService;
81import com.android.server.wifi.WifiService;
82import com.android.server.wm.WindowManagerService;
83
84import dalvik.system.VMRuntime;
85import dalvik.system.Zygote;
86
87import java.io.File;
88import java.util.Timer;
89import java.util.TimerTask;
90
91public final class SystemServer {
92    private static final String TAG = "SystemServer";
93
94    private static final String ENCRYPTING_STATE = "trigger_restart_min_framework";
95    private static final String ENCRYPTED_STATE = "1";
96
97    private static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; // 1hr
98
99    // The earliest supported time.  We pick one day into 1970, to
100    // give any timezone code room without going into negative time.
101    private static final long EARLIEST_SUPPORTED_TIME = 86400 * 1000;
102
103    /*
104     * Implementation class names. TODO: Move them to a codegen class or load
105     * them from the build system somehow.
106     */
107    private static final String BACKUP_MANAGER_SERVICE_CLASS =
108            "com.android.server.backup.BackupManagerService$Lifecycle";
109    private static final String DEVICE_POLICY_MANAGER_SERVICE_CLASS =
110            "com.android.server.devicepolicy.DevicePolicyManagerService$Lifecycle";
111    private static final String APPWIDGET_SERVICE_CLASS =
112            "com.android.server.appwidget.AppWidgetService";
113    private static final String PRINT_MANAGER_SERVICE_CLASS =
114            "com.android.server.print.PrintManagerService";
115
116    private final int mFactoryTestMode;
117    private Timer mProfilerSnapshotTimer;
118
119    private Context mSystemContext;
120    private SystemServiceManager mSystemServiceManager;
121
122    // TODO: remove all of these references by improving dependency resolution and boot phases
123    private Installer mInstaller;
124    private PowerManagerService mPowerManagerService;
125    private ActivityManagerService mActivityManagerService;
126    private DisplayManagerService mDisplayManagerService;
127    private ContentResolver mContentResolver;
128
129    /**
130     * Called to initialize native system services.
131     */
132    private static native void nativeInit();
133
134    /**
135     * The main entry point from zygote.
136     */
137    public static void main(String[] args) {
138        new SystemServer().run();
139    }
140
141    public SystemServer() {
142        mFactoryTestMode = FactoryTest.getMode();
143    }
144
145    private void run() {
146        // If a device's clock is before 1970 (before 0), a lot of
147        // APIs crash dealing with negative numbers, notably
148        // java.io.File#setLastModified, so instead we fake it and
149        // hope that time from cell towers or NTP fixes it shortly.
150        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
151            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
152            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
153        }
154
155        // Here we go!
156        Slog.i(TAG, "Entered the Android system server!");
157        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis());
158
159        // In case the runtime switched since last boot (such as when
160        // the old runtime was removed in an OTA), set the system
161        // property so that it is in sync. We can't do this in
162        // libnativehelper's JniInvocation::Init code where we already
163        // had to fallback to a different runtime because it is
164        // running as root and we need to be the system user to set
165        // the property. http://b/11463182
166        SystemProperties.set("persist.sys.dalvik.vm.lib.1", VMRuntime.getRuntime().vmLibrary());
167
168        // Enable the sampling profiler.
169        if (SamplingProfilerIntegration.isEnabled()) {
170            SamplingProfilerIntegration.start();
171            mProfilerSnapshotTimer = new Timer();
172            mProfilerSnapshotTimer.schedule(new TimerTask() {
173                @Override
174                public void run() {
175                    SamplingProfilerIntegration.writeSnapshot("system_server", null);
176                }
177            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
178        }
179
180        // Mmmmmm... more memory!
181        VMRuntime.getRuntime().clearGrowthLimit();
182
183        // The system server has to run all of the time, so it needs to be
184        // as efficient as possible with its memory usage.
185        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
186
187        // Within the system server, it is an error to access Environment paths without
188        // explicitly specifying a user.
189        Environment.setUserRequired(true);
190
191        // Ensure binder calls into the system always run at foreground priority.
192        BinderInternal.disableBackgroundScheduling(true);
193
194        // Prepare the main looper thread (this thread).
195        android.os.Process.setThreadPriority(
196                android.os.Process.THREAD_PRIORITY_FOREGROUND);
197        android.os.Process.setCanSelfBackground(false);
198        Looper.prepareMainLooper();
199
200        // Initialize native services.
201        System.loadLibrary("android_servers");
202        nativeInit();
203
204        // Check whether we failed to shut down last time we tried.
205        // This call may not return.
206        performPendingShutdown();
207
208        // Initialize the system context.
209        createSystemContext();
210
211        // Create the system service manager.
212        mSystemServiceManager = new SystemServiceManager(mSystemContext);
213        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
214
215        // Start services.
216        try {
217            startBootstrapServices();
218            startCoreServices();
219            startOtherServices();
220        } catch (RuntimeException ex) {
221            Slog.e("System", "******************************************");
222            Slog.e("System", "************ Failure starting system services", ex);
223            throw ex;
224        }
225
226        // For debug builds, log event loop stalls to dropbox for analysis.
227        if (StrictMode.conditionallyEnableDebugLogging()) {
228            Slog.i(TAG, "Enabled StrictMode for system server main thread.");
229        }
230
231        // Loop forever.
232        Looper.loop();
233        throw new RuntimeException("Main thread loop unexpectedly exited");
234    }
235
236    private void reportWtf(String msg, Throwable e) {
237        Slog.w(TAG, "***********************************************");
238        Log.wtf(TAG, "BOOT FAILURE " + msg, e);
239    }
240
241    private void performPendingShutdown() {
242        final String shutdownAction = SystemProperties.get(
243                ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
244        if (shutdownAction != null && shutdownAction.length() > 0) {
245            boolean reboot = (shutdownAction.charAt(0) == '1');
246
247            final String reason;
248            if (shutdownAction.length() > 1) {
249                reason = shutdownAction.substring(1, shutdownAction.length());
250            } else {
251                reason = null;
252            }
253
254            ShutdownThread.rebootOrShutdown(reboot, reason);
255        }
256    }
257
258    private void createSystemContext() {
259        ActivityThread activityThread = ActivityThread.systemMain();
260        mSystemContext = activityThread.getSystemContext();
261        mSystemContext.setTheme(android.R.style.Theme_Holo);
262    }
263
264    private void startBootstrapServices() {
265        // Wait for installd to finish starting up so that it has a chance to
266        // create critical directories such as /data/user with the appropriate
267        // permissions.  We need this to complete before we initialize other services.
268        mInstaller = mSystemServiceManager.startService(Installer.class);
269
270        // Power manager needs to be started early because other services need it.
271        // TODO: The conversion to the new pattern is incomplete.  We need to switch
272        // the power manager's dependencies over then we can use boot phases to arrange
273        // initialization order and remove the mPowerManagerService field.
274        mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
275
276        // Activity manager runs the show.
277        mActivityManagerService = mSystemServiceManager.startService(
278                ActivityManagerService.Lifecycle.class).getService();
279    }
280
281    private void startCoreServices() {
282        // Display manager is needed to provide display metrics before package manager
283        // starts up.
284        mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
285    }
286
287    private void startOtherServices() {
288        final Context context = mSystemContext;
289        AccountManagerService accountManager = null;
290        ContentService contentService = null;
291        LightsManager lights = null;
292        BatteryService battery = null;
293        VibratorService vibrator = null;
294        IAlarmManager alarm = null;
295        MountService mountService = null;
296        NetworkManagementService networkManagement = null;
297        NetworkStatsService networkStats = null;
298        NetworkPolicyManagerService networkPolicy = null;
299        ConnectivityService connectivity = null;
300        WifiP2pService wifiP2p = null;
301        WifiService wifi = null;
302        NsdService serviceDiscovery= null;
303        IPackageManager pm = null;
304        WindowManagerService wm = null;
305        BluetoothManagerService bluetooth = null;
306        DockObserver dock = null;
307        UsbService usb = null;
308        SerialService serial = null;
309        RecognitionManagerService recognition = null;
310        NetworkTimeUpdateService networkTimeUpdater = null;
311        CommonTimeManagementService commonTimeMgmtService = null;
312        InputManagerService inputManager = null;
313        TelephonyRegistry telephonyRegistry = null;
314        ConsumerIrService consumerIr = null;
315
316        boolean onlyCore = false;
317        boolean firstBoot = false;
318        boolean disableStorage = SystemProperties.getBoolean("config.disable_storage", false);
319        boolean disableMedia = SystemProperties.getBoolean("config.disable_media", false);
320        boolean disableBluetooth = SystemProperties.getBoolean("config.disable_bluetooth", false);
321        boolean disableTelephony = SystemProperties.getBoolean("config.disable_telephony", false);
322        boolean disableLocation = SystemProperties.getBoolean("config.disable_location", false);
323        boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui", false);
324        boolean disableNonCoreServices = SystemProperties.getBoolean("config.disable_noncore", false);
325        boolean disableNetwork = SystemProperties.getBoolean("config.disable_network", false);
326
327        try {
328            Slog.i(TAG, "Telephony Registry");
329            telephonyRegistry = new TelephonyRegistry(context);
330            ServiceManager.addService("telephony.registry", telephonyRegistry);
331
332            Slog.i(TAG, "Scheduling Policy");
333            ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
334
335            AttributeCache.init(context);
336
337            // We need the default display before we can initialize the package manager.
338            mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
339
340            Slog.i(TAG, "Package Manager");
341            // Only run "core" apps if we're encrypting the device.
342            String cryptState = SystemProperties.get("vold.decrypt");
343            if (ENCRYPTING_STATE.equals(cryptState)) {
344                Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
345                onlyCore = true;
346            } else if (ENCRYPTED_STATE.equals(cryptState)) {
347                Slog.w(TAG, "Device encrypted - only parsing core apps");
348                onlyCore = true;
349            }
350
351            pm = PackageManagerService.main(context, mInstaller,
352                    mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF,
353                    onlyCore);
354            try {
355                firstBoot = pm.isFirstBoot();
356            } catch (RemoteException e) {
357            }
358
359            mActivityManagerService.setSystemProcess();
360
361            Slog.i(TAG, "Entropy Mixer");
362            ServiceManager.addService("entropy", new EntropyMixer(context));
363
364            Slog.i(TAG, "User Service");
365            ServiceManager.addService(Context.USER_SERVICE,
366                    UserManagerService.getInstance());
367
368            mContentResolver = context.getContentResolver();
369
370            // The AccountManager must come before the ContentService
371            try {
372                // TODO: seems like this should be disable-able, but req'd by ContentService
373                Slog.i(TAG, "Account Manager");
374                accountManager = new AccountManagerService(context);
375                ServiceManager.addService(Context.ACCOUNT_SERVICE, accountManager);
376            } catch (Throwable e) {
377                Slog.e(TAG, "Failure starting Account Manager", e);
378            }
379
380            Slog.i(TAG, "Content Manager");
381            contentService = ContentService.main(context,
382                    mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL);
383
384            Slog.i(TAG, "System Content Providers");
385            mActivityManagerService.installSystemProviders();
386
387            mSystemServiceManager.startService(LightsService.class);
388            lights = LocalServices.getService(LightsManager.class);
389
390            Slog.i(TAG, "Battery Service");
391            battery = new BatteryService(context, lights);
392            ServiceManager.addService("battery", battery);
393
394            Slog.i(TAG, "Vibrator Service");
395            vibrator = new VibratorService(context);
396            ServiceManager.addService("vibrator", vibrator);
397
398            // TODO: use boot phase
399            // only initialize the power service after we have started the
400            // lights service, content providers and the battery service.
401            mPowerManagerService.init(lights, battery,
402                    BatteryStatsService.getService(),
403                    mActivityManagerService.getAppOpsService());
404
405            Slog.i(TAG, "Consumer IR Service");
406            consumerIr = new ConsumerIrService(context);
407            ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);
408
409            mSystemServiceManager.startService(AlarmManagerService.class);
410            alarm = IAlarmManager.Stub.asInterface(
411                    ServiceManager.getService(Context.ALARM_SERVICE));
412
413            Slog.i(TAG, "Init Watchdog");
414            final Watchdog watchdog = Watchdog.getInstance();
415            watchdog.init(context, mActivityManagerService);
416
417            Slog.i(TAG, "Input Manager");
418            inputManager = new InputManagerService(context);
419
420            Slog.i(TAG, "Window Manager");
421            wm = WindowManagerService.main(context, inputManager,
422                    mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
423                    !firstBoot, onlyCore);
424            ServiceManager.addService(Context.WINDOW_SERVICE, wm);
425            ServiceManager.addService(Context.INPUT_SERVICE, inputManager);
426
427            mActivityManagerService.setWindowManager(wm);
428
429            inputManager.setWindowManagerCallbacks(wm.getInputMonitor());
430            inputManager.start();
431
432            // TODO: Use service dependencies instead.
433            mDisplayManagerService.windowManagerAndInputReady();
434
435            // Skip Bluetooth if we have an emulator kernel
436            // TODO: Use a more reliable check to see if this product should
437            // support Bluetooth - see bug 988521
438            if (SystemProperties.get("ro.kernel.qemu").equals("1")) {
439                Slog.i(TAG, "No Bluetooh Service (emulator)");
440            } else if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
441                Slog.i(TAG, "No Bluetooth Service (factory test)");
442            } else if (!context.getPackageManager().hasSystemFeature
443                       (PackageManager.FEATURE_BLUETOOTH)) {
444                Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");
445            } else if (disableBluetooth) {
446                Slog.i(TAG, "Bluetooth Service disabled by config");
447            } else {
448                Slog.i(TAG, "Bluetooth Manager Service");
449                bluetooth = new BluetoothManagerService(context);
450                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_MANAGER_SERVICE, bluetooth);
451            }
452        } catch (RuntimeException e) {
453            Slog.e("System", "******************************************");
454            Slog.e("System", "************ Failure starting core service", e);
455        }
456
457        StatusBarManagerService statusBar = null;
458        INotificationManager notification = null;
459        InputMethodManagerService imm = null;
460        WallpaperManagerService wallpaper = null;
461        LocationManagerService location = null;
462        CountryDetectorService countryDetector = null;
463        TextServicesManagerService tsms = null;
464        LockSettingsService lockSettings = null;
465        AssetAtlasService atlas = null;
466        MediaRouterService mediaRouter = null;
467
468        // Bring up services needed for UI.
469        if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
470            //if (!disableNonCoreServices) { // TODO: View depends on these; mock them?
471            if (true) {
472                try {
473                    Slog.i(TAG, "Input Method Service");
474                    imm = new InputMethodManagerService(context, wm);
475                    ServiceManager.addService(Context.INPUT_METHOD_SERVICE, imm);
476                } catch (Throwable e) {
477                    reportWtf("starting Input Manager Service", e);
478                }
479
480                try {
481                    Slog.i(TAG, "Accessibility Manager");
482                    ServiceManager.addService(Context.ACCESSIBILITY_SERVICE, (IBinder)
483                            getClass().getClassLoader().loadClass("com.android.server.accessibility.AccessibilityManagerService").getConstructor(Context.class).newInstance(context));
484                } catch (Throwable e) {
485                    reportWtf("starting Accessibility Manager", e);
486                }
487            }
488        }
489
490        try {
491            wm.displayReady();
492        } catch (Throwable e) {
493            reportWtf("making display ready", e);
494        }
495
496        try {
497            pm.performBootDexOpt();
498        } catch (Throwable e) {
499            reportWtf("performing boot dexopt", e);
500        }
501
502        try {
503            ActivityManagerNative.getDefault().showBootMessage(
504                    context.getResources().getText(
505                            com.android.internal.R.string.android_upgrading_starting_apps),
506                    false);
507        } catch (RemoteException e) {
508        }
509
510        if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
511            if (!disableStorage &&
512                !"0".equals(SystemProperties.get("system_init.startmountservice"))) {
513                try {
514                    /*
515                     * NotificationManagerService is dependant on MountService,
516                     * (for media / usb notifications) so we must start MountService first.
517                     */
518                    Slog.i(TAG, "Mount Service");
519                    mountService = new MountService(context);
520                    ServiceManager.addService("mount", mountService);
521                } catch (Throwable e) {
522                    reportWtf("starting Mount Service", e);
523                }
524            }
525
526            if (!disableNonCoreServices) {
527                try {
528                    Slog.i(TAG,  "LockSettingsService");
529                    lockSettings = new LockSettingsService(context);
530                    ServiceManager.addService("lock_settings", lockSettings);
531                } catch (Throwable e) {
532                    reportWtf("starting LockSettingsService service", e);
533                }
534
535                try {
536                    if (pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
537                        mSystemServiceManager.startServiceIfExists(
538                                DEVICE_POLICY_MANAGER_SERVICE_CLASS);
539                    }
540                } catch (Throwable e) {
541                    reportWtf("starting DevicePolicyService", e);
542                }
543            }
544
545            if (!disableSystemUI) {
546                try {
547                    Slog.i(TAG, "Status Bar");
548                    statusBar = new StatusBarManagerService(context, wm);
549                    ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
550                } catch (Throwable e) {
551                    reportWtf("starting StatusBarManagerService", e);
552                }
553            }
554
555            if (!disableNonCoreServices) {
556                try {
557                    Slog.i(TAG, "Clipboard Service");
558                    ServiceManager.addService(Context.CLIPBOARD_SERVICE,
559                            new ClipboardService(context));
560                } catch (Throwable e) {
561                    reportWtf("starting Clipboard Service", e);
562                }
563            }
564
565            if (!disableNetwork) {
566                try {
567                    Slog.i(TAG, "NetworkManagement Service");
568                    networkManagement = NetworkManagementService.create(context);
569                    ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
570                } catch (Throwable e) {
571                    reportWtf("starting NetworkManagement Service", e);
572                }
573            }
574
575            if (!disableNonCoreServices) {
576                try {
577                    Slog.i(TAG, "Text Service Manager Service");
578                    tsms = new TextServicesManagerService(context);
579                    ServiceManager.addService(Context.TEXT_SERVICES_MANAGER_SERVICE, tsms);
580                } catch (Throwable e) {
581                    reportWtf("starting Text Service Manager Service", e);
582                }
583            }
584
585            if (!disableNetwork) {
586                try {
587                    Slog.i(TAG, "NetworkStats Service");
588                    networkStats = new NetworkStatsService(context, networkManagement, alarm);
589                    ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);
590                } catch (Throwable e) {
591                    reportWtf("starting NetworkStats Service", e);
592                }
593
594                try {
595                    Slog.i(TAG, "NetworkPolicy Service");
596                    networkPolicy = new NetworkPolicyManagerService(
597                            context, mActivityManagerService,
598                            (IPowerManager)ServiceManager.getService(Context.POWER_SERVICE),
599                            networkStats, networkManagement);
600                    ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
601                } catch (Throwable e) {
602                    reportWtf("starting NetworkPolicy Service", e);
603                }
604
605               try {
606                    Slog.i(TAG, "Wi-Fi P2pService");
607                    wifiP2p = new WifiP2pService(context);
608                    ServiceManager.addService(Context.WIFI_P2P_SERVICE, wifiP2p);
609                } catch (Throwable e) {
610                    reportWtf("starting Wi-Fi P2pService", e);
611                }
612
613               try {
614                    Slog.i(TAG, "Wi-Fi Service");
615                    wifi = new WifiService(context);
616                    ServiceManager.addService(Context.WIFI_SERVICE, wifi);
617                } catch (Throwable e) {
618                    reportWtf("starting Wi-Fi Service", e);
619                }
620
621                try {
622                    Slog.i(TAG, "Connectivity Service");
623                    connectivity = new ConnectivityService(
624                            context, networkManagement, networkStats, networkPolicy);
625                    ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
626                    networkStats.bindConnectivityManager(connectivity);
627                    networkPolicy.bindConnectivityManager(connectivity);
628
629                    wifiP2p.connectivityServiceReady();
630                    wifi.checkAndStartWifi();
631                } catch (Throwable e) {
632                    reportWtf("starting Connectivity Service", e);
633                }
634
635                try {
636                    Slog.i(TAG, "Network Service Discovery Service");
637                    serviceDiscovery = NsdService.create(context);
638                    ServiceManager.addService(
639                            Context.NSD_SERVICE, serviceDiscovery);
640                } catch (Throwable e) {
641                    reportWtf("starting Service Discovery Service", e);
642                }
643            }
644
645            if (!disableNonCoreServices) {
646                try {
647                    Slog.i(TAG, "UpdateLock Service");
648                    ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
649                            new UpdateLockService(context));
650                } catch (Throwable e) {
651                    reportWtf("starting UpdateLockService", e);
652                }
653            }
654
655            /*
656             * MountService has a few dependencies: Notification Manager and
657             * AppWidget Provider. Make sure MountService is completely started
658             * first before continuing.
659             */
660            if (mountService != null && !onlyCore) {
661                mountService.waitForAsecScan();
662            }
663
664            try {
665                if (accountManager != null)
666                    accountManager.systemReady();
667            } catch (Throwable e) {
668                reportWtf("making Account Manager Service ready", e);
669            }
670
671            try {
672                if (contentService != null)
673                    contentService.systemReady();
674            } catch (Throwable e) {
675                reportWtf("making Content Service ready", e);
676            }
677
678            mSystemServiceManager.startService(NotificationManagerService.class);
679            notification = INotificationManager.Stub.asInterface(
680                    ServiceManager.getService(Context.NOTIFICATION_SERVICE));
681            networkPolicy.bindNotificationManager(notification);
682
683            mSystemServiceManager.startService(DeviceStorageMonitorService.class);
684
685            if (!disableLocation) {
686                try {
687                    Slog.i(TAG, "Location Manager");
688                    location = new LocationManagerService(context);
689                    ServiceManager.addService(Context.LOCATION_SERVICE, location);
690                } catch (Throwable e) {
691                    reportWtf("starting Location Manager", e);
692                }
693
694                try {
695                    Slog.i(TAG, "Country Detector");
696                    countryDetector = new CountryDetectorService(context);
697                    ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
698                } catch (Throwable e) {
699                    reportWtf("starting Country Detector", e);
700                }
701            }
702
703            if (!disableNonCoreServices) {
704                try {
705                    Slog.i(TAG, "Search Service");
706                    ServiceManager.addService(Context.SEARCH_SERVICE,
707                            new SearchManagerService(context));
708                } catch (Throwable e) {
709                    reportWtf("starting Search Service", e);
710                }
711            }
712
713            try {
714                Slog.i(TAG, "DropBox Service");
715                ServiceManager.addService(Context.DROPBOX_SERVICE,
716                        new DropBoxManagerService(context, new File("/data/system/dropbox")));
717            } catch (Throwable e) {
718                reportWtf("starting DropBoxManagerService", e);
719            }
720
721            if (!disableNonCoreServices && context.getResources().getBoolean(
722                        R.bool.config_enableWallpaperService)) {
723                try {
724                    Slog.i(TAG, "Wallpaper Service");
725                    wallpaper = new WallpaperManagerService(context);
726                    ServiceManager.addService(Context.WALLPAPER_SERVICE, wallpaper);
727                } catch (Throwable e) {
728                    reportWtf("starting Wallpaper Service", e);
729                }
730            }
731
732            if (!disableMedia && !"0".equals(SystemProperties.get("system_init.startaudioservice"))) {
733                try {
734                    Slog.i(TAG, "Audio Service");
735                    ServiceManager.addService(Context.AUDIO_SERVICE, new AudioService(context));
736                } catch (Throwable e) {
737                    reportWtf("starting Audio Service", e);
738                }
739            }
740
741            if (!disableNonCoreServices) {
742                try {
743                    Slog.i(TAG, "Dock Observer");
744                    // Listen for dock station changes
745                    dock = new DockObserver(context);
746                } catch (Throwable e) {
747                    reportWtf("starting DockObserver", e);
748                }
749            }
750
751            if (!disableMedia) {
752                try {
753                    Slog.i(TAG, "Wired Accessory Manager");
754                    // Listen for wired headset changes
755                    inputManager.setWiredAccessoryCallbacks(
756                            new WiredAccessoryManager(context, inputManager));
757                } catch (Throwable e) {
758                    reportWtf("starting WiredAccessoryManager", e);
759                }
760            }
761
762            if (!disableNonCoreServices) {
763                try {
764                    Slog.i(TAG, "USB Service");
765                    // Manage USB host and device support
766                    usb = new UsbService(context);
767                    ServiceManager.addService(Context.USB_SERVICE, usb);
768                } catch (Throwable e) {
769                    reportWtf("starting UsbService", e);
770                }
771
772                try {
773                    Slog.i(TAG, "Serial Service");
774                    // Serial port support
775                    serial = new SerialService(context);
776                    ServiceManager.addService(Context.SERIAL_SERVICE, serial);
777                } catch (Throwable e) {
778                    Slog.e(TAG, "Failure starting SerialService", e);
779                }
780            }
781
782            mSystemServiceManager.startService(TwilightService.class);
783
784            mSystemServiceManager.startService(UiModeManagerService.class);
785
786            if (!disableNonCoreServices) {
787                try {
788                    if (pm.hasSystemFeature(PackageManager.FEATURE_BACKUP)) {
789                        mSystemServiceManager.startServiceIfExists(BACKUP_MANAGER_SERVICE_CLASS);
790                    }
791                } catch (Throwable e) {
792                    Slog.e(TAG, "Failure starting Backup Service", e);
793                }
794
795                try {
796                    if (pm.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)) {
797                        mSystemServiceManager.startServiceIfExists(APPWIDGET_SERVICE_CLASS);
798                    }
799                } catch (Throwable e) {
800                    reportWtf("starting AppWidget Service", e);
801                }
802
803                try {
804                    Slog.i(TAG, "Recognition Service");
805                    recognition = new RecognitionManagerService(context);
806                } catch (Throwable e) {
807                    reportWtf("starting Recognition Service", e);
808                }
809            }
810
811            try {
812                Slog.i(TAG, "DiskStats Service");
813                ServiceManager.addService("diskstats", new DiskStatsService(context));
814            } catch (Throwable e) {
815                reportWtf("starting DiskStats Service", e);
816            }
817
818            try {
819                // need to add this service even if SamplingProfilerIntegration.isEnabled()
820                // is false, because it is this service that detects system property change and
821                // turns on SamplingProfilerIntegration. Plus, when sampling profiler doesn't work,
822                // there is little overhead for running this service.
823                Slog.i(TAG, "SamplingProfiler Service");
824                ServiceManager.addService("samplingprofiler",
825                            new SamplingProfilerService(context));
826            } catch (Throwable e) {
827                reportWtf("starting SamplingProfiler Service", e);
828            }
829
830            if (!disableNetwork) {
831                try {
832                    Slog.i(TAG, "NetworkTimeUpdateService");
833                    networkTimeUpdater = new NetworkTimeUpdateService(context);
834                } catch (Throwable e) {
835                    reportWtf("starting NetworkTimeUpdate service", e);
836                }
837            }
838
839            if (!disableMedia) {
840                try {
841                    Slog.i(TAG, "CommonTimeManagementService");
842                    commonTimeMgmtService = new CommonTimeManagementService(context);
843                    ServiceManager.addService("commontime_management", commonTimeMgmtService);
844                } catch (Throwable e) {
845                    reportWtf("starting CommonTimeManagementService service", e);
846                }
847            }
848
849            if (!disableNetwork) {
850                try {
851                    Slog.i(TAG, "CertBlacklister");
852                    CertBlacklister blacklister = new CertBlacklister(context);
853                } catch (Throwable e) {
854                    reportWtf("starting CertBlacklister", e);
855                }
856            }
857
858            if (!disableNonCoreServices
859                    && context.getResources().getBoolean(R.bool.config_dreamsSupported)) {
860                // Dreams (interactive idle-time views, a/k/a screen savers)
861                mSystemServiceManager.startService(DreamManagerService.class);
862            }
863
864            if (!disableNonCoreServices) {
865                try {
866                    Slog.i(TAG, "Assets Atlas Service");
867                    atlas = new AssetAtlasService(context);
868                    ServiceManager.addService(AssetAtlasService.ASSET_ATLAS_SERVICE, atlas);
869                } catch (Throwable e) {
870                    reportWtf("starting AssetAtlasService", e);
871                }
872            }
873
874            try {
875                Slog.i(TAG, "IdleMaintenanceService");
876                new IdleMaintenanceService(context, battery);
877            } catch (Throwable e) {
878                reportWtf("starting IdleMaintenanceService", e);
879            }
880
881            try {
882                if (pm.hasSystemFeature(PackageManager.FEATURE_PRINTING)) {
883                    mSystemServiceManager.startServiceIfExists(PRINT_MANAGER_SERVICE_CLASS);
884                }
885            } catch (Throwable e) {
886                reportWtf("starting Print Service", e);
887            }
888
889            if (!disableNonCoreServices) {
890                try {
891                    Slog.i(TAG, "Media Router Service");
892                    mediaRouter = new MediaRouterService(context);
893                    ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);
894                } catch (Throwable e) {
895                    reportWtf("starting MediaRouterService", e);
896                }
897            }
898        }
899
900        // Before things start rolling, be sure we have decided whether
901        // we are in safe mode.
902        final boolean safeMode = wm.detectSafeMode();
903        if (safeMode) {
904            mActivityManagerService.enterSafeMode();
905            // Post the safe mode state in the Zygote class
906            Zygote.systemInSafeMode = true;
907            // Disable the JIT for the system_server process
908            VMRuntime.getRuntime().disableJitCompilation();
909        } else {
910            // Enable the JIT for the system_server process
911            VMRuntime.getRuntime().startJitCompilation();
912        }
913
914        // It is now time to start up the app processes...
915
916        try {
917            vibrator.systemReady();
918        } catch (Throwable e) {
919            reportWtf("making Vibrator Service ready", e);
920        }
921
922        if (lockSettings != null) {
923            try {
924                lockSettings.systemReady();
925            } catch (Throwable e) {
926                reportWtf("making Lock Settings Service ready", e);
927            }
928        }
929
930        // Needed by DevicePolicyManager for initialization
931        mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
932
933        mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
934
935        try {
936            wm.systemReady();
937        } catch (Throwable e) {
938            reportWtf("making Window Manager Service ready", e);
939        }
940
941        if (safeMode) {
942            mActivityManagerService.showSafeModeOverlay();
943        }
944
945        // Update the configuration for this context by hand, because we're going
946        // to start using it before the config change done in wm.systemReady() will
947        // propagate to it.
948        Configuration config = wm.computeNewConfiguration();
949        DisplayMetrics metrics = new DisplayMetrics();
950        WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
951        w.getDefaultDisplay().getMetrics(metrics);
952        context.getResources().updateConfiguration(config, metrics);
953
954        try {
955            // TODO: use boot phase
956            mPowerManagerService.systemReady();
957        } catch (Throwable e) {
958            reportWtf("making Power Manager Service ready", e);
959        }
960
961        try {
962            pm.systemReady();
963        } catch (Throwable e) {
964            reportWtf("making Package Manager Service ready", e);
965        }
966
967        try {
968            // TODO: use boot phase and communicate these flags some other way
969            mDisplayManagerService.systemReady(safeMode, onlyCore);
970        } catch (Throwable e) {
971            reportWtf("making Display Manager Service ready", e);
972        }
973
974        // These are needed to propagate to the runnable below.
975        final Context contextF = context;
976        final MountService mountServiceF = mountService;
977        final BatteryService batteryF = battery;
978        final NetworkManagementService networkManagementF = networkManagement;
979        final NetworkStatsService networkStatsF = networkStats;
980        final NetworkPolicyManagerService networkPolicyF = networkPolicy;
981        final ConnectivityService connectivityF = connectivity;
982        final DockObserver dockF = dock;
983        final UsbService usbF = usb;
984        final WallpaperManagerService wallpaperF = wallpaper;
985        final InputMethodManagerService immF = imm;
986        final RecognitionManagerService recognitionF = recognition;
987        final LocationManagerService locationF = location;
988        final CountryDetectorService countryDetectorF = countryDetector;
989        final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
990        final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService;
991        final TextServicesManagerService textServiceManagerServiceF = tsms;
992        final StatusBarManagerService statusBarF = statusBar;
993        final AssetAtlasService atlasF = atlas;
994        final InputManagerService inputManagerF = inputManager;
995        final TelephonyRegistry telephonyRegistryF = telephonyRegistry;
996        final MediaRouterService mediaRouterF = mediaRouter;
997
998        // We now tell the activity manager it is okay to run third party
999        // code.  It will call back into us once it has gotten to the state
1000        // where third party code can really run (but before it has actually
1001        // started launching the initial applications), for us to complete our
1002        // initialization.
1003        mActivityManagerService.systemReady(new Runnable() {
1004            public void run() {
1005                Slog.i(TAG, "Making services ready");
1006
1007                try {
1008                    mActivityManagerService.startObservingNativeCrashes();
1009                } catch (Throwable e) {
1010                    reportWtf("observing native crashes", e);
1011                }
1012                try {
1013                    startSystemUi(contextF);
1014                } catch (Throwable e) {
1015                    reportWtf("starting System UI", e);
1016                }
1017                try {
1018                    if (mountServiceF != null) mountServiceF.systemReady();
1019                } catch (Throwable e) {
1020                    reportWtf("making Mount Service ready", e);
1021                }
1022                try {
1023                    if (batteryF != null) batteryF.systemReady();
1024                } catch (Throwable e) {
1025                    reportWtf("making Battery Service ready", e);
1026                }
1027                try {
1028                    if (networkManagementF != null) networkManagementF.systemReady();
1029                } catch (Throwable e) {
1030                    reportWtf("making Network Managment Service ready", e);
1031                }
1032                try {
1033                    if (networkStatsF != null) networkStatsF.systemReady();
1034                } catch (Throwable e) {
1035                    reportWtf("making Network Stats Service ready", e);
1036                }
1037                try {
1038                    if (networkPolicyF != null) networkPolicyF.systemReady();
1039                } catch (Throwable e) {
1040                    reportWtf("making Network Policy Service ready", e);
1041                }
1042                try {
1043                    if (connectivityF != null) connectivityF.systemReady();
1044                } catch (Throwable e) {
1045                    reportWtf("making Connectivity Service ready", e);
1046                }
1047                try {
1048                    if (dockF != null) dockF.systemReady();
1049                } catch (Throwable e) {
1050                    reportWtf("making Dock Service ready", e);
1051                }
1052                try {
1053                    if (usbF != null) usbF.systemReady();
1054                } catch (Throwable e) {
1055                    reportWtf("making USB Service ready", e);
1056                }
1057                try {
1058                    if (recognitionF != null) recognitionF.systemReady();
1059                } catch (Throwable e) {
1060                    reportWtf("making Recognition Service ready", e);
1061                }
1062                Watchdog.getInstance().start();
1063
1064                // It is now okay to let the various system services start their
1065                // third party code...
1066                mSystemServiceManager.startBootPhase(SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
1067
1068                try {
1069                    if (wallpaperF != null) wallpaperF.systemRunning();
1070                } catch (Throwable e) {
1071                    reportWtf("Notifying WallpaperService running", e);
1072                }
1073                try {
1074                    if (immF != null) immF.systemRunning(statusBarF);
1075                } catch (Throwable e) {
1076                    reportWtf("Notifying InputMethodService running", e);
1077                }
1078                try {
1079                    if (locationF != null) locationF.systemRunning();
1080                } catch (Throwable e) {
1081                    reportWtf("Notifying Location Service running", e);
1082                }
1083                try {
1084                    if (countryDetectorF != null) countryDetectorF.systemRunning();
1085                } catch (Throwable e) {
1086                    reportWtf("Notifying CountryDetectorService running", e);
1087                }
1088                try {
1089                    if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
1090                } catch (Throwable e) {
1091                    reportWtf("Notifying NetworkTimeService running", e);
1092                }
1093                try {
1094                    if (commonTimeMgmtServiceF != null) commonTimeMgmtServiceF.systemRunning();
1095                } catch (Throwable e) {
1096                    reportWtf("Notifying CommonTimeManagementService running", e);
1097                }
1098                try {
1099                    if (textServiceManagerServiceF != null)
1100                        textServiceManagerServiceF.systemRunning();
1101                } catch (Throwable e) {
1102                    reportWtf("Notifying TextServicesManagerService running", e);
1103                }
1104                try {
1105                    if (atlasF != null) atlasF.systemRunning();
1106                } catch (Throwable e) {
1107                    reportWtf("Notifying AssetAtlasService running", e);
1108                }
1109                try {
1110                    // TODO(BT) Pass parameter to input manager
1111                    if (inputManagerF != null) inputManagerF.systemRunning();
1112                } catch (Throwable e) {
1113                    reportWtf("Notifying InputManagerService running", e);
1114                }
1115
1116                try {
1117                    if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
1118                } catch (Throwable e) {
1119                    reportWtf("Notifying TelephonyRegistry running", e);
1120                }
1121
1122                try {
1123                    if (mediaRouterF != null) mediaRouterF.systemRunning();
1124                } catch (Throwable e) {
1125                    reportWtf("Notifying MediaRouterService running", e);
1126                }
1127
1128                mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETE);
1129            }
1130        });
1131    }
1132
1133    static final void startSystemUi(Context context) {
1134        Intent intent = new Intent();
1135        intent.setComponent(new ComponentName("com.android.systemui",
1136                    "com.android.systemui.SystemUIService"));
1137        //Slog.d(TAG, "Starting service: " + intent);
1138        context.startServiceAsUser(intent, UserHandle.OWNER);
1139    }
1140}
1141