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.ActivityThread;
20import android.app.INotificationManager;
21import android.app.usage.UsageStatsManagerInternal;
22import android.content.ComponentName;
23import android.content.ContentResolver;
24import android.content.Context;
25import android.content.Intent;
26import android.content.pm.PackageManager;
27import android.content.res.Configuration;
28import android.content.res.Resources.Theme;
29import android.os.BaseBundle;
30import android.os.Build;
31import android.os.Environment;
32import android.os.FactoryTest;
33import android.os.FileUtils;
34import android.os.Looper;
35import android.os.PowerManager;
36import android.os.RemoteException;
37import android.os.ServiceManager;
38import android.os.StrictMode;
39import android.os.SystemClock;
40import android.os.SystemProperties;
41import android.os.Trace;
42import android.os.UserHandle;
43import android.os.UserManager;
44import android.os.storage.IMountService;
45import android.provider.Settings;
46import android.util.DisplayMetrics;
47import android.util.EventLog;
48import android.util.Slog;
49import android.view.WindowManager;
50
51import com.android.internal.R;
52import com.android.internal.app.NightDisplayController;
53import com.android.internal.os.BinderInternal;
54import com.android.internal.os.SamplingProfilerIntegration;
55import com.android.internal.os.ZygoteInit;
56import com.android.internal.policy.EmergencyAffordanceManager;
57import com.android.internal.widget.ILockSettings;
58import com.android.server.accessibility.AccessibilityManagerService;
59import com.android.server.am.ActivityManagerService;
60import com.android.server.audio.AudioService;
61import com.android.server.camera.CameraService;
62import com.android.server.clipboard.ClipboardService;
63import com.android.server.connectivity.IpConnectivityMetrics;
64import com.android.server.connectivity.MetricsLoggerService;
65import com.android.server.devicepolicy.DevicePolicyManagerService;
66import com.android.server.display.DisplayManagerService;
67import com.android.server.display.NightDisplayService;
68import com.android.server.dreams.DreamManagerService;
69import com.android.server.emergency.EmergencyAffordanceService;
70import com.android.server.fingerprint.FingerprintService;
71import com.android.server.hdmi.HdmiControlService;
72import com.android.server.input.InputManagerService;
73import com.android.server.job.JobSchedulerService;
74import com.android.server.lights.LightsService;
75import com.android.server.media.MediaResourceMonitorService;
76import com.android.server.media.MediaRouterService;
77import com.android.server.media.MediaSessionService;
78import com.android.server.media.projection.MediaProjectionManagerService;
79import com.android.server.net.NetworkPolicyManagerService;
80import com.android.server.net.NetworkStatsService;
81import com.android.server.notification.NotificationManagerService;
82import com.android.server.os.SchedulingPolicyService;
83import com.android.server.pm.BackgroundDexOptService;
84import com.android.server.pm.Installer;
85import com.android.server.pm.LauncherAppsService;
86import com.android.server.pm.OtaDexoptService;
87import com.android.server.pm.PackageManagerService;
88import com.android.server.pm.ShortcutService;
89import com.android.server.pm.UserManagerService;
90import com.android.server.power.PowerManagerService;
91import com.android.server.power.ShutdownThread;
92import com.android.server.restrictions.RestrictionsManagerService;
93import com.android.server.retaildemo.RetailDemoModeService;
94import com.android.server.soundtrigger.SoundTriggerService;
95import com.android.server.statusbar.StatusBarManagerService;
96import com.android.server.storage.DeviceStorageMonitorService;
97import com.android.server.telecom.TelecomLoaderService;
98import com.android.server.trust.TrustManagerService;
99import com.android.server.tv.TvRemoteService;
100import com.android.server.tv.TvInputManagerService;
101import com.android.server.twilight.TwilightService;
102import com.android.server.usage.UsageStatsService;
103import com.android.server.vr.VrManagerService;
104import com.android.server.webkit.WebViewUpdateService;
105import com.android.server.wm.WindowManagerService;
106
107import dalvik.system.VMRuntime;
108
109import java.io.File;
110import java.io.IOException;
111import java.util.Locale;
112import java.util.Timer;
113import java.util.TimerTask;
114
115public final class SystemServer {
116    private static final String TAG = "SystemServer";
117
118    private static final String ENCRYPTING_STATE = "trigger_restart_min_framework";
119    private static final String ENCRYPTED_STATE = "1";
120
121    private static final long SNAPSHOT_INTERVAL = 60 * 60 * 1000; // 1hr
122
123    // The earliest supported time.  We pick one day into 1970, to
124    // give any timezone code room without going into negative time.
125    private static final long EARLIEST_SUPPORTED_TIME = 86400 * 1000;
126
127    /*
128     * Implementation class names. TODO: Move them to a codegen class or load
129     * them from the build system somehow.
130     */
131    private static final String BACKUP_MANAGER_SERVICE_CLASS =
132            "com.android.server.backup.BackupManagerService$Lifecycle";
133    private static final String APPWIDGET_SERVICE_CLASS =
134            "com.android.server.appwidget.AppWidgetService";
135    private static final String VOICE_RECOGNITION_MANAGER_SERVICE_CLASS =
136            "com.android.server.voiceinteraction.VoiceInteractionManagerService";
137    private static final String PRINT_MANAGER_SERVICE_CLASS =
138            "com.android.server.print.PrintManagerService";
139    private static final String USB_SERVICE_CLASS =
140            "com.android.server.usb.UsbService$Lifecycle";
141    private static final String MIDI_SERVICE_CLASS =
142            "com.android.server.midi.MidiService$Lifecycle";
143    private static final String WIFI_SERVICE_CLASS =
144            "com.android.server.wifi.WifiService";
145    private static final String WIFI_NAN_SERVICE_CLASS =
146            "com.android.server.wifi.nan.WifiNanService";
147    private static final String WIFI_P2P_SERVICE_CLASS =
148            "com.android.server.wifi.p2p.WifiP2pService";
149    private static final String ETHERNET_SERVICE_CLASS =
150            "com.android.server.ethernet.EthernetService";
151    private static final String JOB_SCHEDULER_SERVICE_CLASS =
152            "com.android.server.job.JobSchedulerService";
153    private static final String LOCK_SETTINGS_SERVICE_CLASS =
154            "com.android.server.LockSettingsService$Lifecycle";
155    private static final String MOUNT_SERVICE_CLASS =
156            "com.android.server.MountService$Lifecycle";
157    private static final String SEARCH_MANAGER_SERVICE_CLASS =
158            "com.android.server.search.SearchManagerService$Lifecycle";
159    private static final String THERMAL_OBSERVER_CLASS =
160            "com.google.android.clockwork.ThermalObserver";
161    private static final String WEAR_BLUETOOTH_SERVICE_CLASS =
162            "com.google.android.clockwork.bluetooth.WearBluetoothService";
163    private static final String WEAR_WIFI_MEDIATOR_SERVICE_CLASS =
164            "com.google.android.clockwork.wifi.WearWifiMediatorService";
165    private static final String WEAR_TIME_SERVICE_CLASS =
166            "com.google.android.clockwork.time.WearTimeService";
167    private static final String ACCOUNT_SERVICE_CLASS =
168            "com.android.server.accounts.AccountManagerService$Lifecycle";
169    private static final String CONTENT_SERVICE_CLASS =
170            "com.android.server.content.ContentService$Lifecycle";
171    private static final String WALLPAPER_SERVICE_CLASS =
172            "com.android.server.wallpaper.WallpaperManagerService$Lifecycle";
173
174    private static final String PERSISTENT_DATA_BLOCK_PROP = "ro.frp.pst";
175
176    private static final String UNCRYPT_PACKAGE_FILE = "/cache/recovery/uncrypt_file";
177    private static final String BLOCK_MAP_FILE = "/cache/recovery/block.map";
178
179    // maximum number of binder threads used for system_server
180    // will be higher than the system default
181    private static final int sMaxBinderThreads = 31;
182
183    /**
184     * Default theme used by the system context. This is used to style
185     * system-provided dialogs, such as the Power Off dialog, and other
186     * visual content.
187     */
188    private static final int DEFAULT_SYSTEM_THEME =
189            com.android.internal.R.style.Theme_DeviceDefault_System;
190
191    private final int mFactoryTestMode;
192    private Timer mProfilerSnapshotTimer;
193
194    private Context mSystemContext;
195    private SystemServiceManager mSystemServiceManager;
196
197    // TODO: remove all of these references by improving dependency resolution and boot phases
198    private PowerManagerService mPowerManagerService;
199    private ActivityManagerService mActivityManagerService;
200    private WebViewUpdateService mWebViewUpdateService;
201    private DisplayManagerService mDisplayManagerService;
202    private PackageManagerService mPackageManagerService;
203    private PackageManager mPackageManager;
204    private ContentResolver mContentResolver;
205    private EntropyMixer mEntropyMixer;
206
207    private boolean mOnlyCore;
208    private boolean mFirstBoot;
209
210    /**
211     * Start the sensor service.
212     */
213    private static native void startSensorService();
214
215    /**
216     * The main entry point from zygote.
217     */
218    public static void main(String[] args) {
219        new SystemServer().run();
220    }
221
222    public SystemServer() {
223        // Check for factory test mode.
224        mFactoryTestMode = FactoryTest.getMode();
225    }
226
227    private void run() {
228        try {
229            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitBeforeStartServices");
230            // If a device's clock is before 1970 (before 0), a lot of
231            // APIs crash dealing with negative numbers, notably
232            // java.io.File#setLastModified, so instead we fake it and
233            // hope that time from cell towers or NTP fixes it shortly.
234            if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
235                Slog.w(TAG, "System clock is before 1970; setting to 1970.");
236                SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
237            }
238
239            // If the system has "persist.sys.language" and friends set, replace them with
240            // "persist.sys.locale". Note that the default locale at this point is calculated
241            // using the "-Duser.locale" command line flag. That flag is usually populated by
242            // AndroidRuntime using the same set of system properties, but only the system_server
243            // and system apps are allowed to set them.
244            //
245            // NOTE: Most changes made here will need an equivalent change to
246            // core/jni/AndroidRuntime.cpp
247            if (!SystemProperties.get("persist.sys.language").isEmpty()) {
248                final String languageTag = Locale.getDefault().toLanguageTag();
249
250                SystemProperties.set("persist.sys.locale", languageTag);
251                SystemProperties.set("persist.sys.language", "");
252                SystemProperties.set("persist.sys.country", "");
253                SystemProperties.set("persist.sys.localevar", "");
254            }
255
256            // Here we go!
257            Slog.i(TAG, "Entered the Android system server!");
258            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis());
259
260            // In case the runtime switched since last boot (such as when
261            // the old runtime was removed in an OTA), set the system
262            // property so that it is in sync. We can't do this in
263            // libnativehelper's JniInvocation::Init code where we already
264            // had to fallback to a different runtime because it is
265            // running as root and we need to be the system user to set
266            // the property. http://b/11463182
267            SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
268
269            // Enable the sampling profiler.
270            if (SamplingProfilerIntegration.isEnabled()) {
271                SamplingProfilerIntegration.start();
272                mProfilerSnapshotTimer = new Timer();
273                mProfilerSnapshotTimer.schedule(new TimerTask() {
274                        @Override
275                        public void run() {
276                            SamplingProfilerIntegration.writeSnapshot("system_server", null);
277                        }
278                    }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
279            }
280
281            // Mmmmmm... more memory!
282            VMRuntime.getRuntime().clearGrowthLimit();
283
284            // The system server has to run all of the time, so it needs to be
285            // as efficient as possible with its memory usage.
286            VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
287
288            // Some devices rely on runtime fingerprint generation, so make sure
289            // we've defined it before booting further.
290            Build.ensureFingerprintProperty();
291
292            // Within the system server, it is an error to access Environment paths without
293            // explicitly specifying a user.
294            Environment.setUserRequired(true);
295
296            // Within the system server, any incoming Bundles should be defused
297            // to avoid throwing BadParcelableException.
298            BaseBundle.setShouldDefuse(true);
299
300            // Ensure binder calls into the system always run at foreground priority.
301            BinderInternal.disableBackgroundScheduling(true);
302
303            // Increase the number of binder threads in system_server
304            BinderInternal.setMaxThreads(sMaxBinderThreads);
305
306            // Prepare the main looper thread (this thread).
307            android.os.Process.setThreadPriority(
308                android.os.Process.THREAD_PRIORITY_FOREGROUND);
309            android.os.Process.setCanSelfBackground(false);
310            Looper.prepareMainLooper();
311
312            // Initialize native services.
313            System.loadLibrary("android_servers");
314
315            // Check whether we failed to shut down last time we tried.
316            // This call may not return.
317            performPendingShutdown();
318
319            // Initialize the system context.
320            createSystemContext();
321
322            // Create the system service manager.
323            mSystemServiceManager = new SystemServiceManager(mSystemContext);
324            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
325        } finally {
326            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
327        }
328
329        // Start services.
330        try {
331            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
332            startBootstrapServices();
333            startCoreServices();
334            startOtherServices();
335        } catch (Throwable ex) {
336            Slog.e("System", "******************************************");
337            Slog.e("System", "************ Failure starting system services", ex);
338            throw ex;
339        } finally {
340            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
341        }
342
343        // For debug builds, log event loop stalls to dropbox for analysis.
344        if (StrictMode.conditionallyEnableDebugLogging()) {
345            Slog.i(TAG, "Enabled StrictMode for system server main thread.");
346        }
347
348        // Loop forever.
349        Looper.loop();
350        throw new RuntimeException("Main thread loop unexpectedly exited");
351    }
352
353    private void reportWtf(String msg, Throwable e) {
354        Slog.w(TAG, "***********************************************");
355        Slog.wtf(TAG, "BOOT FAILURE " + msg, e);
356    }
357
358    private void performPendingShutdown() {
359        final String shutdownAction = SystemProperties.get(
360                ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
361        if (shutdownAction != null && shutdownAction.length() > 0) {
362            boolean reboot = (shutdownAction.charAt(0) == '1');
363
364            final String reason;
365            if (shutdownAction.length() > 1) {
366                reason = shutdownAction.substring(1, shutdownAction.length());
367            } else {
368                reason = null;
369            }
370
371            // If it's a pending reboot into recovery to apply an update,
372            // always make sure uncrypt gets executed properly when needed.
373            // If '/cache/recovery/block.map' hasn't been created, stop the
374            // reboot which will fail for sure, and get a chance to capture a
375            // bugreport when that's still feasible. (Bug: 26444951)
376            if (PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
377                File packageFile = new File(UNCRYPT_PACKAGE_FILE);
378                if (packageFile.exists()) {
379                    String filename = null;
380                    try {
381                        filename = FileUtils.readTextFile(packageFile, 0, null);
382                    } catch (IOException e) {
383                        Slog.e(TAG, "Error reading uncrypt package file", e);
384                    }
385
386                    if (filename != null && filename.startsWith("/data")) {
387                        if (!new File(BLOCK_MAP_FILE).exists()) {
388                            Slog.e(TAG, "Can't find block map file, uncrypt failed or " +
389                                       "unexpected runtime restart?");
390                            return;
391                        }
392                    }
393                }
394            }
395            ShutdownThread.rebootOrShutdown(null, reboot, reason);
396        }
397    }
398
399    private void createSystemContext() {
400        ActivityThread activityThread = ActivityThread.systemMain();
401        mSystemContext = activityThread.getSystemContext();
402        mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
403    }
404
405    /**
406     * Starts the small tangle of critical services that are needed to get
407     * the system off the ground.  These services have complex mutual dependencies
408     * which is why we initialize them all in one place here.  Unless your service
409     * is also entwined in these dependencies, it should be initialized in one of
410     * the other functions.
411     */
412    private void startBootstrapServices() {
413        // Wait for installd to finish starting up so that it has a chance to
414        // create critical directories such as /data/user with the appropriate
415        // permissions.  We need this to complete before we initialize other services.
416        Installer installer = mSystemServiceManager.startService(Installer.class);
417
418        // Activity manager runs the show.
419        mActivityManagerService = mSystemServiceManager.startService(
420                ActivityManagerService.Lifecycle.class).getService();
421        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
422        mActivityManagerService.setInstaller(installer);
423
424        // Power manager needs to be started early because other services need it.
425        // Native daemons may be watching for it to be registered so it must be ready
426        // to handle incoming binder calls immediately (including being able to verify
427        // the permissions for those calls).
428        mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
429
430        // Now that the power manager has been started, let the activity manager
431        // initialize power management features.
432        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitPowerManagement");
433        mActivityManagerService.initPowerManagement();
434        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
435
436        // Manages LEDs and display backlight so we need it to bring up the display.
437        mSystemServiceManager.startService(LightsService.class);
438
439        // Display manager is needed to provide display metrics before package manager
440        // starts up.
441        mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
442
443        // We need the default display before we can initialize the package manager.
444        mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
445
446        // Only run "core" apps if we're encrypting the device.
447        String cryptState = SystemProperties.get("vold.decrypt");
448        if (ENCRYPTING_STATE.equals(cryptState)) {
449            Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
450            mOnlyCore = true;
451        } else if (ENCRYPTED_STATE.equals(cryptState)) {
452            Slog.w(TAG, "Device encrypted - only parsing core apps");
453            mOnlyCore = true;
454        }
455
456        // Start the package manager.
457        traceBeginAndSlog("StartPackageManagerService");
458        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
459                mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
460        mFirstBoot = mPackageManagerService.isFirstBoot();
461        mPackageManager = mSystemContext.getPackageManager();
462        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
463
464        // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
465        // A/B artifacts after boot, before anything else might touch/need them.
466        // Note: this isn't needed during decryption (we don't have /data anyways).
467        if (!mOnlyCore) {
468            boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
469                    false);
470            if (!disableOtaDexopt) {
471                traceBeginAndSlog("StartOtaDexOptService");
472                try {
473                    OtaDexoptService.main(mSystemContext, mPackageManagerService);
474                } catch (Throwable e) {
475                    reportWtf("starting OtaDexOptService", e);
476                } finally {
477                    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
478                }
479            }
480        }
481
482        traceBeginAndSlog("StartUserManagerService");
483        mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
484        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
485
486        // Initialize attribute cache used to cache resources from packages.
487        AttributeCache.init(mSystemContext);
488
489        // Set up the Application instance for the system process and get started.
490        mActivityManagerService.setSystemProcess();
491
492        // The sensor service needs access to package manager service, app ops
493        // service, and permissions service, therefore we start it after them.
494        startSensorService();
495    }
496
497    /**
498     * Starts some essential services that are not tangled up in the bootstrap process.
499     */
500    private void startCoreServices() {
501        // Tracks the battery level.  Requires LightService.
502        mSystemServiceManager.startService(BatteryService.class);
503
504        // Tracks application usage stats.
505        mSystemServiceManager.startService(UsageStatsService.class);
506        mActivityManagerService.setUsageStatsManager(
507                LocalServices.getService(UsageStatsManagerInternal.class));
508
509        // Tracks whether the updatable WebView is in a ready state and watches for update installs.
510        mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
511    }
512
513    /**
514     * Starts a miscellaneous grab bag of stuff that has yet to be refactored
515     * and organized.
516     */
517    private void startOtherServices() {
518        final Context context = mSystemContext;
519        VibratorService vibrator = null;
520        IMountService mountService = null;
521        NetworkManagementService networkManagement = null;
522        NetworkStatsService networkStats = null;
523        NetworkPolicyManagerService networkPolicy = null;
524        ConnectivityService connectivity = null;
525        NetworkScoreService networkScore = null;
526        NsdService serviceDiscovery= null;
527        WindowManagerService wm = null;
528        SerialService serial = null;
529        NetworkTimeUpdateService networkTimeUpdater = null;
530        CommonTimeManagementService commonTimeMgmtService = null;
531        InputManagerService inputManager = null;
532        TelephonyRegistry telephonyRegistry = null;
533        ConsumerIrService consumerIr = null;
534        MmsServiceBroker mmsService = null;
535        HardwarePropertiesManagerService hardwarePropertiesService = null;
536
537        boolean disableStorage = SystemProperties.getBoolean("config.disable_storage", false);
538        boolean disableBluetooth = SystemProperties.getBoolean("config.disable_bluetooth", false);
539        boolean disableLocation = SystemProperties.getBoolean("config.disable_location", false);
540        boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui", false);
541        boolean disableNonCoreServices = SystemProperties.getBoolean("config.disable_noncore", false);
542        boolean disableNetwork = SystemProperties.getBoolean("config.disable_network", false);
543        boolean disableNetworkTime = SystemProperties.getBoolean("config.disable_networktime", false);
544        boolean disableRtt = SystemProperties.getBoolean("config.disable_rtt", false);
545        boolean disableMediaProjection = SystemProperties.getBoolean("config.disable_mediaproj",
546                false);
547        boolean disableSerial = SystemProperties.getBoolean("config.disable_serial", false);
548        boolean disableSearchManager = SystemProperties.getBoolean("config.disable_searchmanager",
549                false);
550        boolean disableTrustManager = SystemProperties.getBoolean("config.disable_trustmanager",
551                false);
552        boolean disableTextServices = SystemProperties.getBoolean("config.disable_textservices", false);
553        boolean disableSamplingProfiler = SystemProperties.getBoolean("config.disable_samplingprof",
554                false);
555        boolean isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1");
556
557        try {
558            Slog.i(TAG, "Reading configuration...");
559            SystemConfig.getInstance();
560
561            traceBeginAndSlog("StartSchedulingPolicyService");
562            ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
563            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
564
565            mSystemServiceManager.startService(TelecomLoaderService.class);
566
567            traceBeginAndSlog("StartTelephonyRegistry");
568            telephonyRegistry = new TelephonyRegistry(context);
569            ServiceManager.addService("telephony.registry", telephonyRegistry);
570            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
571
572            traceBeginAndSlog("StartEntropyMixer");
573            mEntropyMixer = new EntropyMixer(context);
574            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
575
576            mContentResolver = context.getContentResolver();
577
578            Slog.i(TAG, "Camera Service");
579            mSystemServiceManager.startService(CameraService.class);
580
581            // The AccountManager must come before the ContentService
582            traceBeginAndSlog("StartAccountManagerService");
583            mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
584            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
585
586            traceBeginAndSlog("StartContentService");
587            mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);
588            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
589
590            traceBeginAndSlog("InstallSystemProviders");
591            mActivityManagerService.installSystemProviders();
592            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
593
594            traceBeginAndSlog("StartVibratorService");
595            vibrator = new VibratorService(context);
596            ServiceManager.addService("vibrator", vibrator);
597            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
598
599            traceBeginAndSlog("StartConsumerIrService");
600            consumerIr = new ConsumerIrService(context);
601            ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);
602            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
603
604            traceBeginAndSlog("StartAlarmManagerService");
605            mSystemServiceManager.startService(AlarmManagerService.class);
606            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
607
608            traceBeginAndSlog("InitWatchdog");
609            final Watchdog watchdog = Watchdog.getInstance();
610            watchdog.init(context, mActivityManagerService);
611            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
612
613            traceBeginAndSlog("StartInputManagerService");
614            inputManager = new InputManagerService(context);
615            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
616
617            traceBeginAndSlog("StartWindowManagerService");
618            wm = WindowManagerService.main(context, inputManager,
619                    mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
620                    !mFirstBoot, mOnlyCore);
621            ServiceManager.addService(Context.WINDOW_SERVICE, wm);
622            ServiceManager.addService(Context.INPUT_SERVICE, inputManager);
623            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
624
625            traceBeginAndSlog("StartVrManagerService");
626            mSystemServiceManager.startService(VrManagerService.class);
627            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
628
629            mActivityManagerService.setWindowManager(wm);
630
631            inputManager.setWindowManagerCallbacks(wm.getInputMonitor());
632            inputManager.start();
633
634            // TODO: Use service dependencies instead.
635            mDisplayManagerService.windowManagerAndInputReady();
636
637            // Skip Bluetooth if we have an emulator kernel
638            // TODO: Use a more reliable check to see if this product should
639            // support Bluetooth - see bug 988521
640            if (isEmulator) {
641                Slog.i(TAG, "No Bluetooth Service (emulator)");
642            } else if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
643                Slog.i(TAG, "No Bluetooth Service (factory test)");
644            } else if (!context.getPackageManager().hasSystemFeature
645                       (PackageManager.FEATURE_BLUETOOTH)) {
646                Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");
647            } else if (disableBluetooth) {
648                Slog.i(TAG, "Bluetooth Service disabled by config");
649            } else {
650                mSystemServiceManager.startService(BluetoothService.class);
651            }
652
653            traceBeginAndSlog("ConnectivityMetricsLoggerService");
654            mSystemServiceManager.startService(MetricsLoggerService.class);
655            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
656
657            traceBeginAndSlog("IpConnectivityMetrics");
658            mSystemServiceManager.startService(IpConnectivityMetrics.class);
659            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
660
661            traceBeginAndSlog("PinnerService");
662            mSystemServiceManager.startService(PinnerService.class);
663            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
664        } catch (RuntimeException e) {
665            Slog.e("System", "******************************************");
666            Slog.e("System", "************ Failure starting core service", e);
667        }
668
669        StatusBarManagerService statusBar = null;
670        INotificationManager notification = null;
671        LocationManagerService location = null;
672        CountryDetectorService countryDetector = null;
673        ILockSettings lockSettings = null;
674        AssetAtlasService atlas = null;
675        MediaRouterService mediaRouter = null;
676
677        // Bring up services needed for UI.
678        if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
679            mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);
680
681            traceBeginAndSlog("StartAccessibilityManagerService");
682            try {
683                ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
684                        new AccessibilityManagerService(context));
685            } catch (Throwable e) {
686                reportWtf("starting Accessibility Manager", e);
687            }
688            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
689        }
690
691        try {
692            wm.displayReady();
693        } catch (Throwable e) {
694            reportWtf("making display ready", e);
695        }
696
697        if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
698            if (!disableStorage &&
699                !"0".equals(SystemProperties.get("system_init.startmountservice"))) {
700                try {
701                    /*
702                     * NotificationManagerService is dependant on MountService,
703                     * (for media / usb notifications) so we must start MountService first.
704                     */
705                    mSystemServiceManager.startService(MOUNT_SERVICE_CLASS);
706                    mountService = IMountService.Stub.asInterface(
707                            ServiceManager.getService("mount"));
708                } catch (Throwable e) {
709                    reportWtf("starting Mount Service", e);
710                }
711            }
712        }
713
714        // We start this here so that we update our configuration to set watch or television
715        // as appropriate.
716        mSystemServiceManager.startService(UiModeManagerService.class);
717
718        if (!mOnlyCore) {
719            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "UpdatePackagesIfNeeded");
720            try {
721                mPackageManagerService.updatePackagesIfNeeded();
722            } catch (Throwable e) {
723                reportWtf("update packages", e);
724            }
725            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
726        }
727
728        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PerformFstrimIfNeeded");
729        try {
730            mPackageManagerService.performFstrimIfNeeded();
731        } catch (Throwable e) {
732            reportWtf("performing fstrim", e);
733        }
734        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
735
736        if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
737            if (!disableNonCoreServices) {
738                traceBeginAndSlog("StartLockSettingsService");
739                try {
740                    mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);
741                    lockSettings = ILockSettings.Stub.asInterface(
742                            ServiceManager.getService("lock_settings"));
743                } catch (Throwable e) {
744                    reportWtf("starting LockSettingsService service", e);
745                }
746                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
747
748                if (!SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("")) {
749                    mSystemServiceManager.startService(PersistentDataBlockService.class);
750                }
751
752                mSystemServiceManager.startService(DeviceIdleController.class);
753
754                // Always start the Device Policy Manager, so that the API is compatible with
755                // API8.
756                mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class);
757            }
758
759            if (!disableSystemUI) {
760                traceBeginAndSlog("StartStatusBarManagerService");
761                try {
762                    statusBar = new StatusBarManagerService(context, wm);
763                    ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
764                } catch (Throwable e) {
765                    reportWtf("starting StatusBarManagerService", e);
766                }
767                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
768            }
769
770            if (!disableNonCoreServices) {
771                traceBeginAndSlog("StartClipboardService");
772                try {
773                    ServiceManager.addService(Context.CLIPBOARD_SERVICE,
774                            new ClipboardService(context));
775                } catch (Throwable e) {
776                    reportWtf("starting Clipboard Service", e);
777                }
778                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
779            }
780
781            if (!disableNetwork) {
782                traceBeginAndSlog("StartNetworkManagementService");
783                try {
784                    networkManagement = NetworkManagementService.create(context);
785                    ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
786                } catch (Throwable e) {
787                    reportWtf("starting NetworkManagement Service", e);
788                }
789                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
790            }
791
792            if (!disableNonCoreServices && !disableTextServices) {
793                mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);
794            }
795
796            if (!disableNetwork) {
797                traceBeginAndSlog("StartNetworkScoreService");
798                try {
799                    networkScore = new NetworkScoreService(context);
800                    ServiceManager.addService(Context.NETWORK_SCORE_SERVICE, networkScore);
801                } catch (Throwable e) {
802                    reportWtf("starting Network Score Service", e);
803                }
804                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
805
806                traceBeginAndSlog("StartNetworkStatsService");
807                try {
808                    networkStats = NetworkStatsService.create(context, networkManagement);
809                    ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);
810                } catch (Throwable e) {
811                    reportWtf("starting NetworkStats Service", e);
812                }
813                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
814
815                traceBeginAndSlog("StartNetworkPolicyManagerService");
816                try {
817                    networkPolicy = new NetworkPolicyManagerService(context,
818                            mActivityManagerService, networkStats, networkManagement);
819                    ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
820                } catch (Throwable e) {
821                    reportWtf("starting NetworkPolicy Service", e);
822                }
823                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
824
825                if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_NAN)) {
826                    mSystemServiceManager.startService(WIFI_NAN_SERVICE_CLASS);
827                } else {
828                    Slog.i(TAG, "No Wi-Fi NAN Service (NAN support Not Present)");
829                }
830                mSystemServiceManager.startService(WIFI_P2P_SERVICE_CLASS);
831                mSystemServiceManager.startService(WIFI_SERVICE_CLASS);
832                mSystemServiceManager.startService(
833                            "com.android.server.wifi.scanner.WifiScanningService");
834
835                if (!disableRtt) {
836                    mSystemServiceManager.startService("com.android.server.wifi.RttService");
837                }
838
839                if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) ||
840                    mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) {
841                    mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS);
842                }
843
844                traceBeginAndSlog("StartConnectivityService");
845                try {
846                    connectivity = new ConnectivityService(
847                            context, networkManagement, networkStats, networkPolicy);
848                    ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
849                    networkStats.bindConnectivityManager(connectivity);
850                    networkPolicy.bindConnectivityManager(connectivity);
851                } catch (Throwable e) {
852                    reportWtf("starting Connectivity Service", e);
853                }
854                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
855
856                traceBeginAndSlog("StartNsdService");
857                try {
858                    serviceDiscovery = NsdService.create(context);
859                    ServiceManager.addService(
860                            Context.NSD_SERVICE, serviceDiscovery);
861                } catch (Throwable e) {
862                    reportWtf("starting Service Discovery Service", e);
863                }
864                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
865            }
866
867            if (!disableNonCoreServices) {
868                traceBeginAndSlog("StartUpdateLockService");
869                try {
870                    ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
871                            new UpdateLockService(context));
872                } catch (Throwable e) {
873                    reportWtf("starting UpdateLockService", e);
874                }
875                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
876            }
877
878            if (!disableNonCoreServices) {
879                mSystemServiceManager.startService(RecoverySystemService.class);
880            }
881
882            /*
883             * MountService has a few dependencies: Notification Manager and
884             * AppWidget Provider. Make sure MountService is completely started
885             * first before continuing.
886             */
887            if (mountService != null && !mOnlyCore) {
888                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "WaitForAsecScan");
889                try {
890                    mountService.waitForAsecScan();
891                } catch (RemoteException ignored) {
892                }
893                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
894            }
895
896            mSystemServiceManager.startService(NotificationManagerService.class);
897            notification = INotificationManager.Stub.asInterface(
898                    ServiceManager.getService(Context.NOTIFICATION_SERVICE));
899            networkPolicy.bindNotificationManager(notification);
900
901            mSystemServiceManager.startService(DeviceStorageMonitorService.class);
902
903            if (!disableLocation) {
904                traceBeginAndSlog("StartLocationManagerService");
905                try {
906                    location = new LocationManagerService(context);
907                    ServiceManager.addService(Context.LOCATION_SERVICE, location);
908                } catch (Throwable e) {
909                    reportWtf("starting Location Manager", e);
910                }
911                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
912
913                traceBeginAndSlog("StartCountryDetectorService");
914                try {
915                    countryDetector = new CountryDetectorService(context);
916                    ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
917                } catch (Throwable e) {
918                    reportWtf("starting Country Detector", e);
919                }
920                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
921            }
922
923            if (!disableNonCoreServices && !disableSearchManager) {
924                traceBeginAndSlog("StartSearchManagerService");
925                try {
926                    mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS);
927                } catch (Throwable e) {
928                    reportWtf("starting Search Service", e);
929                }
930                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
931            }
932
933            mSystemServiceManager.startService(DropBoxManagerService.class);
934
935            if (!disableNonCoreServices && context.getResources().getBoolean(
936                        R.bool.config_enableWallpaperService)) {
937                traceBeginAndSlog("StartWallpaperManagerService");
938                mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
939                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
940            }
941
942            traceBeginAndSlog("StartAudioService");
943            mSystemServiceManager.startService(AudioService.Lifecycle.class);
944            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
945
946            if (!disableNonCoreServices) {
947                mSystemServiceManager.startService(DockObserver.class);
948
949                if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
950                    mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS);
951                }
952            }
953
954            traceBeginAndSlog("StartWiredAccessoryManager");
955            try {
956                // Listen for wired headset changes
957                inputManager.setWiredAccessoryCallbacks(
958                        new WiredAccessoryManager(context, inputManager));
959            } catch (Throwable e) {
960                reportWtf("starting WiredAccessoryManager", e);
961            }
962            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
963
964            if (!disableNonCoreServices) {
965                if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) {
966                    // Start MIDI Manager service
967                    mSystemServiceManager.startService(MIDI_SERVICE_CLASS);
968                }
969
970                if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)
971                        || mPackageManager.hasSystemFeature(
972                                PackageManager.FEATURE_USB_ACCESSORY)) {
973                    // Manage USB host and device support
974                    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartUsbService");
975                    mSystemServiceManager.startService(USB_SERVICE_CLASS);
976                    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
977                }
978
979                if (!disableSerial) {
980                    traceBeginAndSlog("StartSerialService");
981                    try {
982                        // Serial port support
983                        serial = new SerialService(context);
984                        ServiceManager.addService(Context.SERIAL_SERVICE, serial);
985                    } catch (Throwable e) {
986                        Slog.e(TAG, "Failure starting SerialService", e);
987                    }
988                    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
989                }
990
991                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER,
992                        "StartHardwarePropertiesManagerService");
993                try {
994                    hardwarePropertiesService = new HardwarePropertiesManagerService(context);
995                    ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE,
996                            hardwarePropertiesService);
997                } catch (Throwable e) {
998                    Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e);
999                }
1000                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1001            }
1002
1003            mSystemServiceManager.startService(TwilightService.class);
1004
1005            if (NightDisplayController.isAvailable(context)) {
1006                mSystemServiceManager.startService(NightDisplayService.class);
1007            }
1008
1009            mSystemServiceManager.startService(JobSchedulerService.class);
1010
1011            mSystemServiceManager.startService(SoundTriggerService.class);
1012
1013            if (!disableNonCoreServices) {
1014                if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) {
1015                    mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS);
1016                }
1017
1018                if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)
1019                    || context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {
1020                    mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS);
1021                }
1022
1023                if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_VOICE_RECOGNIZERS)) {
1024                    mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS);
1025                }
1026
1027                if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) {
1028                    Slog.i(TAG, "Gesture Launcher Service");
1029                    mSystemServiceManager.startService(GestureLauncherService.class);
1030                }
1031                mSystemServiceManager.startService(SensorNotificationService.class);
1032                mSystemServiceManager.startService(ContextHubSystemService.class);
1033            }
1034
1035            traceBeginAndSlog("StartDiskStatsService");
1036            try {
1037                ServiceManager.addService("diskstats", new DiskStatsService(context));
1038            } catch (Throwable e) {
1039                reportWtf("starting DiskStats Service", e);
1040            }
1041            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1042
1043            if (!disableSamplingProfiler) {
1044                traceBeginAndSlog("StartSamplingProfilerService");
1045                try {
1046                    // need to add this service even if SamplingProfilerIntegration.isEnabled()
1047                    // is false, because it is this service that detects system property change and
1048                    // turns on SamplingProfilerIntegration. Plus, when sampling profiler doesn't work,
1049                    // there is little overhead for running this service.
1050                    ServiceManager.addService("samplingprofiler",
1051                                new SamplingProfilerService(context));
1052                } catch (Throwable e) {
1053                    reportWtf("starting SamplingProfiler Service", e);
1054                }
1055                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1056            }
1057
1058            if (!disableNetwork && !disableNetworkTime) {
1059                traceBeginAndSlog("StartNetworkTimeUpdateService");
1060                try {
1061                    networkTimeUpdater = new NetworkTimeUpdateService(context);
1062                    ServiceManager.addService("network_time_update_service", networkTimeUpdater);
1063                } catch (Throwable e) {
1064                    reportWtf("starting NetworkTimeUpdate service", e);
1065                }
1066                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1067            }
1068
1069            traceBeginAndSlog("StartCommonTimeManagementService");
1070            try {
1071                commonTimeMgmtService = new CommonTimeManagementService(context);
1072                ServiceManager.addService("commontime_management", commonTimeMgmtService);
1073            } catch (Throwable e) {
1074                reportWtf("starting CommonTimeManagementService service", e);
1075            }
1076            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1077
1078            if (!disableNetwork) {
1079                traceBeginAndSlog("CertBlacklister");
1080                try {
1081                    CertBlacklister blacklister = new CertBlacklister(context);
1082                } catch (Throwable e) {
1083                    reportWtf("starting CertBlacklister", e);
1084                }
1085                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1086            }
1087
1088            if (!disableNetwork && !disableNonCoreServices && EmergencyAffordanceManager.ENABLED) {
1089                // EmergencyMode sevice
1090                mSystemServiceManager.startService(EmergencyAffordanceService.class);
1091            }
1092
1093            if (!disableNonCoreServices) {
1094                // Dreams (interactive idle-time views, a/k/a screen savers, and doze mode)
1095                mSystemServiceManager.startService(DreamManagerService.class);
1096            }
1097
1098            if (!disableNonCoreServices && ZygoteInit.PRELOAD_RESOURCES) {
1099                traceBeginAndSlog("StartAssetAtlasService");
1100                try {
1101                    atlas = new AssetAtlasService(context);
1102                    ServiceManager.addService(AssetAtlasService.ASSET_ATLAS_SERVICE, atlas);
1103                } catch (Throwable e) {
1104                    reportWtf("starting AssetAtlasService", e);
1105                }
1106                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1107            }
1108
1109            if (!disableNonCoreServices) {
1110                ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE,
1111                        new GraphicsStatsService(context));
1112            }
1113
1114            if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) {
1115                mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS);
1116            }
1117
1118            mSystemServiceManager.startService(RestrictionsManagerService.class);
1119
1120            mSystemServiceManager.startService(MediaSessionService.class);
1121
1122            if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) {
1123                mSystemServiceManager.startService(HdmiControlService.class);
1124            }
1125
1126            if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)) {
1127                mSystemServiceManager.startService(TvInputManagerService.class);
1128            }
1129
1130            if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
1131                mSystemServiceManager.startService(MediaResourceMonitorService.class);
1132            }
1133
1134            if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
1135                mSystemServiceManager.startService(TvRemoteService.class);
1136            }
1137
1138            if (!disableNonCoreServices) {
1139                traceBeginAndSlog("StartMediaRouterService");
1140                try {
1141                    mediaRouter = new MediaRouterService(context);
1142                    ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);
1143                } catch (Throwable e) {
1144                    reportWtf("starting MediaRouterService", e);
1145                }
1146                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1147
1148                if (!disableTrustManager) {
1149                    mSystemServiceManager.startService(TrustManagerService.class);
1150                }
1151
1152                if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
1153                    mSystemServiceManager.startService(FingerprintService.class);
1154                }
1155
1156                traceBeginAndSlog("StartBackgroundDexOptService");
1157                try {
1158                    BackgroundDexOptService.schedule(context);
1159                } catch (Throwable e) {
1160                    reportWtf("starting BackgroundDexOptService", e);
1161                }
1162                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1163            }
1164            // LauncherAppsService uses ShortcutService.
1165            mSystemServiceManager.startService(ShortcutService.Lifecycle.class);
1166
1167            mSystemServiceManager.startService(LauncherAppsService.class);
1168        }
1169
1170        if (!disableNonCoreServices && !disableMediaProjection) {
1171            mSystemServiceManager.startService(MediaProjectionManagerService.class);
1172        }
1173
1174        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
1175            mSystemServiceManager.startService(WEAR_BLUETOOTH_SERVICE_CLASS);
1176            mSystemServiceManager.startService(WEAR_WIFI_MEDIATOR_SERVICE_CLASS);
1177          if (!disableNonCoreServices) {
1178              mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS);
1179          }
1180        }
1181
1182        // Before things start rolling, be sure we have decided whether
1183        // we are in safe mode.
1184        final boolean safeMode = wm.detectSafeMode();
1185        if (safeMode) {
1186            mActivityManagerService.enterSafeMode();
1187            // Disable the JIT for the system_server process
1188            VMRuntime.getRuntime().disableJitCompilation();
1189        } else {
1190            // Enable the JIT for the system_server process
1191            VMRuntime.getRuntime().startJitCompilation();
1192        }
1193
1194        // MMS service broker
1195        mmsService = mSystemServiceManager.startService(MmsServiceBroker.class);
1196
1197        if (Settings.Global.getInt(mContentResolver, Settings.Global.DEVICE_PROVISIONED, 0) == 0 ||
1198                UserManager.isDeviceInDemoMode(mSystemContext)) {
1199            mSystemServiceManager.startService(RetailDemoModeService.class);
1200        }
1201
1202        // It is now time to start up the app processes...
1203
1204        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeVibratorServiceReady");
1205        try {
1206            vibrator.systemReady();
1207        } catch (Throwable e) {
1208            reportWtf("making Vibrator Service ready", e);
1209        }
1210        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1211
1212        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeLockSettingsServiceReady");
1213        if (lockSettings != null) {
1214            try {
1215                lockSettings.systemReady();
1216            } catch (Throwable e) {
1217                reportWtf("making Lock Settings Service ready", e);
1218            }
1219        }
1220        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1221
1222        // Needed by DevicePolicyManager for initialization
1223        mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
1224
1225        mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
1226
1227        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeWindowManagerServiceReady");
1228        try {
1229            wm.systemReady();
1230        } catch (Throwable e) {
1231            reportWtf("making Window Manager Service ready", e);
1232        }
1233        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1234
1235        if (safeMode) {
1236            mActivityManagerService.showSafeModeOverlay();
1237        }
1238
1239        // Update the configuration for this context by hand, because we're going
1240        // to start using it before the config change done in wm.systemReady() will
1241        // propagate to it.
1242        Configuration config = wm.computeNewConfiguration();
1243        DisplayMetrics metrics = new DisplayMetrics();
1244        WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
1245        w.getDefaultDisplay().getMetrics(metrics);
1246        context.getResources().updateConfiguration(config, metrics);
1247
1248        // The system context's theme may be configuration-dependent.
1249        final Theme systemTheme = context.getTheme();
1250        if (systemTheme.getChangingConfigurations() != 0) {
1251            systemTheme.rebase();
1252        }
1253
1254        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakePowerManagerServiceReady");
1255        try {
1256            // TODO: use boot phase
1257            mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
1258            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1259        } catch (Throwable e) {
1260            reportWtf("making Power Manager Service ready", e);
1261        }
1262        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1263
1264        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakePackageManagerServiceReady");
1265        try {
1266            mPackageManagerService.systemReady();
1267        } catch (Throwable e) {
1268            reportWtf("making Package Manager Service ready", e);
1269        }
1270        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1271
1272        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeDisplayManagerServiceReady");
1273        try {
1274            // TODO: use boot phase and communicate these flags some other way
1275            mDisplayManagerService.systemReady(safeMode, mOnlyCore);
1276        } catch (Throwable e) {
1277            reportWtf("making Display Manager Service ready", e);
1278        }
1279        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1280
1281        // These are needed to propagate to the runnable below.
1282        final NetworkManagementService networkManagementF = networkManagement;
1283        final NetworkStatsService networkStatsF = networkStats;
1284        final NetworkPolicyManagerService networkPolicyF = networkPolicy;
1285        final ConnectivityService connectivityF = connectivity;
1286        final NetworkScoreService networkScoreF = networkScore;
1287        final LocationManagerService locationF = location;
1288        final CountryDetectorService countryDetectorF = countryDetector;
1289        final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
1290        final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService;
1291        final AssetAtlasService atlasF = atlas;
1292        final InputManagerService inputManagerF = inputManager;
1293        final TelephonyRegistry telephonyRegistryF = telephonyRegistry;
1294        final MediaRouterService mediaRouterF = mediaRouter;
1295        final MmsServiceBroker mmsServiceF = mmsService;
1296
1297        // We now tell the activity manager it is okay to run third party
1298        // code.  It will call back into us once it has gotten to the state
1299        // where third party code can really run (but before it has actually
1300        // started launching the initial applications), for us to complete our
1301        // initialization.
1302        mActivityManagerService.systemReady(new Runnable() {
1303            @Override
1304            public void run() {
1305                Slog.i(TAG, "Making services ready");
1306                mSystemServiceManager.startBootPhase(
1307                        SystemService.PHASE_ACTIVITY_MANAGER_READY);
1308                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseActivityManagerReady");
1309
1310                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartObservingNativeCrashes");
1311                try {
1312                    mActivityManagerService.startObservingNativeCrashes();
1313                } catch (Throwable e) {
1314                    reportWtf("observing native crashes", e);
1315                }
1316                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1317
1318                if (!mOnlyCore) {
1319                    Slog.i(TAG, "WebViewFactory preparation");
1320                    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "WebViewFactoryPreparation");
1321                    mWebViewUpdateService.prepareWebViewInSystemServer();
1322                    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1323                }
1324
1325                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartSystemUI");
1326                try {
1327                    startSystemUi(context);
1328                } catch (Throwable e) {
1329                    reportWtf("starting System UI", e);
1330                }
1331                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1332                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkScoreReady");
1333                try {
1334                    if (networkScoreF != null) networkScoreF.systemReady();
1335                } catch (Throwable e) {
1336                    reportWtf("making Network Score Service ready", e);
1337                }
1338                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1339                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkManagementServiceReady");
1340                try {
1341                    if (networkManagementF != null) networkManagementF.systemReady();
1342                } catch (Throwable e) {
1343                    reportWtf("making Network Managment Service ready", e);
1344                }
1345                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1346                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkStatsServiceReady");
1347                try {
1348                    if (networkStatsF != null) networkStatsF.systemReady();
1349                } catch (Throwable e) {
1350                    reportWtf("making Network Stats Service ready", e);
1351                }
1352                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1353                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkPolicyServiceReady");
1354                try {
1355                    if (networkPolicyF != null) networkPolicyF.systemReady();
1356                } catch (Throwable e) {
1357                    reportWtf("making Network Policy Service ready", e);
1358                }
1359                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1360                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeConnectivityServiceReady");
1361                try {
1362                    if (connectivityF != null) connectivityF.systemReady();
1363                } catch (Throwable e) {
1364                    reportWtf("making Connectivity Service ready", e);
1365                }
1366                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1367
1368                Watchdog.getInstance().start();
1369
1370                // It is now okay to let the various system services start their
1371                // third party code...
1372                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1373                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseThirdPartyAppsCanStart");
1374                mSystemServiceManager.startBootPhase(
1375                        SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
1376
1377                try {
1378                    if (locationF != null) locationF.systemRunning();
1379                } catch (Throwable e) {
1380                    reportWtf("Notifying Location Service running", e);
1381                }
1382                try {
1383                    if (countryDetectorF != null) countryDetectorF.systemRunning();
1384                } catch (Throwable e) {
1385                    reportWtf("Notifying CountryDetectorService running", e);
1386                }
1387                try {
1388                    if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
1389                } catch (Throwable e) {
1390                    reportWtf("Notifying NetworkTimeService running", e);
1391                }
1392                try {
1393                    if (commonTimeMgmtServiceF != null) {
1394                        commonTimeMgmtServiceF.systemRunning();
1395                    }
1396                } catch (Throwable e) {
1397                    reportWtf("Notifying CommonTimeManagementService running", e);
1398                }
1399                try {
1400                    if (atlasF != null) atlasF.systemRunning();
1401                } catch (Throwable e) {
1402                    reportWtf("Notifying AssetAtlasService running", e);
1403                }
1404                try {
1405                    // TODO(BT) Pass parameter to input manager
1406                    if (inputManagerF != null) inputManagerF.systemRunning();
1407                } catch (Throwable e) {
1408                    reportWtf("Notifying InputManagerService running", e);
1409                }
1410                try {
1411                    if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
1412                } catch (Throwable e) {
1413                    reportWtf("Notifying TelephonyRegistry running", e);
1414                }
1415                try {
1416                    if (mediaRouterF != null) mediaRouterF.systemRunning();
1417                } catch (Throwable e) {
1418                    reportWtf("Notifying MediaRouterService running", e);
1419                }
1420
1421                try {
1422                    if (mmsServiceF != null) mmsServiceF.systemRunning();
1423                } catch (Throwable e) {
1424                    reportWtf("Notifying MmsService running", e);
1425                }
1426
1427                try {
1428                    if (networkScoreF != null) networkScoreF.systemRunning();
1429                } catch (Throwable e) {
1430                    reportWtf("Notifying NetworkScoreService running", e);
1431                }
1432                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1433            }
1434        });
1435    }
1436
1437    static final void startSystemUi(Context context) {
1438        Intent intent = new Intent();
1439        intent.setComponent(new ComponentName("com.android.systemui",
1440                    "com.android.systemui.SystemUIService"));
1441        intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
1442        //Slog.d(TAG, "Starting service: " + intent);
1443        context.startServiceAsUser(intent, UserHandle.SYSTEM);
1444    }
1445
1446    private static void traceBeginAndSlog(String name) {
1447        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, name);
1448        Slog.i(TAG, name);
1449    }
1450}
1451