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