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