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