赞
踩
if (startSystemServer) {
startSystemServer(abiList, socketName);/*启动 systemServer*/
}
然后看看startSystemServer方法的具体实现:
/** * Prepare the arguments and fork for the system server process. */ private static boolean startSystemServer(String abiList, String socketName) throws MethodAndArgsCaller, RuntimeException { long capabilities = posixCapabilitiesAsBits( OsConstants.CAP_IPC_LOCK, OsConstants.CAP_KILL, OsConstants.CAP_NET_ADMIN, OsConstants.CAP_NET_BIND_SERVICE, OsConstants.CAP_NET_BROADCAST, OsConstants.CAP_NET_RAW, OsConstants.CAP_SYS_MODULE, OsConstants.CAP_SYS_NICE, OsConstants.CAP_SYS_RESOURCE, OsConstants.CAP_SYS_TIME, OsConstants.CAP_SYS_TTY_CONFIG ); /* Containers run without this capability, so avoid setting it in that case */ if (!SystemProperties.getBoolean(PROPERTY_RUNNING_IN_CONTAINER, false)) { capabilities |= posixCapabilitiesAsBits(OsConstants.CAP_BLOCK_SUSPEND); } /* Hardcoded command line to start the system server */ String args[] = { "--setuid=1000", "--setgid=1000", "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1032,3001,3002,3003,3006,3007,3009,3010", "--capabilities=" + capabilities + "," + capabilities, "--nice-name=system_server", "--runtime-args", "com.android.server.SystemServer", }; ZygoteConnection.Arguments parsedArgs = null; int pid; try { parsedArgs = new ZygoteConnection.Arguments(args); ZygoteConnection.applyDebuggerSystemProperty(parsedArgs); ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs); /* Request to fork the system server process */ pid = Zygote.forkSystemServer( parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,parsedArgs.debugFlags, null,parsedArgs.permittedCapabilities,parsedArgs.effectiveCapabilities);/*单独创建一个进程来运行 systemserver*/ } catch (IllegalArgumentException ex) { throw new RuntimeException(ex); } /* For child process */ if (pid == 0) { if (hasSecondZygote(abiList)) { waitForSecondaryZygote(socketName); } handleSystemServerProcess(parsedArgs); } return true; }
该方法中主要做了:
属性arg数组将会作为syster_server进程的启动参数,通过参数可以知道,syster_server进程 所属的用户id和用户组id为1000,拥有用户组1001,1002等等部分组的权限.进程名字就是system_server,启动的java类名为com.android.server.SystemServer
,然后会将这些string封装到ZygoteConnection.Arguments对象中。
/** * Special method to start the system server process. In addition to the common actions performed in forkAndSpecialize, the pid of the child process is recorded such that the death of the child process will cause zygote to exit. * * @param uid the UNIX uid that the new process should setuid() to after fork()ing and and before spawning any threads. * @param gid the UNIX gid that the new process should setgid() to after fork()ing and and before spawning any threads. * @param gids null-ok; a list of UNIX gids that the new process should setgroups() to after fork and before spawning any threads. * @param debugFlags bit flags that enable debugging features. * @param rlimits null-ok an array of rlimit tuples, with the second dimension having a length of 3 and representing (resource, rlim_cur, rlim_max). These are set via the posix setrlimit(2) call. * @param permittedCapabilities argument for setcap() * @param effectiveCapabilities argument for setcap() * * @return 0 if this is the child, pid of the child if this is the parent, or -1 on error. */ public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags, int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) { VM_HOOKS.preFork(); int pid = nativeForkSystemServer(uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities); // Enable tracing as soon as we enter the system_server. if (pid == 0) { Trace.setTracingEnabled(true); } VM_HOOKS.postForkCommon(); return pid; }
从该方法中可以看出,主要还是通过native层的方法nativeForkSystemServer来创建一个进程,该发生实际上使用的是frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
目录下的ForkAndSpecializeCommon
方法:
// Utility routine to fork zygote and specialize the child process. static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids, jint debug_flags, jobjectArray javaRlimits,jlong permittedCapabilities, jlong effectiveCapabilities, jint mount_external, jstring java_se_info, jstring java_se_name,bool is_system_server, jintArray fdsToClose, jstring instructionSet, jstring dataDir) { SetSigChldHandler(); #ifdef ENABLE_SCHED_BOOST SetForkLoad(true); #endif sigset_t sigchld; sigemptyset(&sigchld); sigaddset(&sigchld, SIGCHLD); // Temporarily block SIGCHLD during forks. The SIGCHLD handler might log, which would result in the logging FDs we close being reopened. This would cause failures because the FDs are not whitelisted. // Note that the zygote process is single threaded at this point. if (sigprocmask(SIG_BLOCK, &sigchld, nullptr) == -1) { ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)); RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_BLOCK, { SIGCHLD }) failed."); } // Close any logging related FDs before we start evaluating the list of // file descriptors. __android_log_close(); // If this is the first fork for this zygote, create the open FD table. // If it isn't, we just need to check whether the list of open files has // changed (and it shouldn't in the normal case). if (gOpenFdTable == NULL) { gOpenFdTable = FileDescriptorTable::Create(); if (gOpenFdTable == NULL) { RuntimeAbort(env, __LINE__, "Unable to construct file descriptor table."); } } else if (!gOpenFdTable->Restat()) { RuntimeAbort(env, __LINE__, "Unable to restat file descriptor table."); } pid_t pid = fork();/*本质上还是使用系统调用来fork一个进程*/ if (pid == 0) { // The child process. gMallocLeakZygoteChild = 1; // Clean up any descriptors which must be closed immediately DetachDescriptors(env, fdsToClose); // Re-open all remaining open file descriptors so that they aren't shared // with the zygote across a fork. if (!gOpenFdTable->ReopenOrDetach()) { RuntimeAbort(env, __LINE__, "Unable to reopen whitelisted descriptors."); } if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) { ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)); RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_UNBLOCK, { SIGCHLD }) failed."); } // Keep capabilities across UID change, unless we're staying root. if (uid != 0) { EnableKeepCapabilities(env); } DropCapabilitiesBoundingSet(env); bool use_native_bridge = !is_system_server && (instructionSet != NULL) && android::NativeBridgeAvailable(); if (use_native_bridge) { ScopedUtfChars isa_string(env, instructionSet); use_native_bridge = android::NeedsNativeBridge(isa_string.c_str()); } if (use_native_bridge && dataDir == NULL) { // dataDir should never be null if we need to use a native bridge. // In general, dataDir will never be null for normal applications. It can only happen in // special cases (for isolated processes which are not associated with any app). These are // launched by the framework and should not be emulated anyway. use_native_bridge = false; ALOGW("Native bridge will not be used because dataDir == NULL."); } if (!MountEmulatedStorage(uid, mount_external, use_native_bridge)) { ALOGW("Failed to mount emulated storage: %s", strerror(errno)); if (errno == ENOTCONN || errno == EROFS) { // When device is actively encrypting, we get ENOTCONN here // since FUSE was mounted before the framework restarted. // When encrypted device is booting, we get EROFS since // FUSE hasn't been created yet by init. // In either case, continue without external storage. } else { RuntimeAbort(env, __LINE__, "Cannot continue without emulated storage"); } } if (!is_system_server) { int rc = createProcessGroup(uid, getpid()); if (rc != 0) { if (rc == -EROFS) { ALOGW("createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?"); } else { ALOGE("createProcessGroup(%d, %d) failed: %s", uid, pid, strerror(-rc)); } } } /* MODIFIED-BEGIN by Wang Xiongke, 2016-09-28,BUG-3005175*/ //SmartContainer modified begin #ifdef ENABLE_CLONE if (isSmartContainerEnabled()) { smartinstance_zygote_hook_pre(env, uid, gid, javaGids, javaRlimits, is_system_server, fdsToClose, dataDir); } else { #endif //SmartContainer modified end SetGids(env, javaGids); //SmartContainer modified begin #ifdef ENABLE_CLONE } #endif //SmartContainer modified end SetRLimits(env, javaRlimits); if (use_native_bridge) { ScopedUtfChars isa_string(env, instructionSet); ScopedUtfChars data_dir(env, dataDir); android::PreInitializeNativeBridge(data_dir.c_str(), isa_string.c_str()); } //SmartContainer modified begin int rc = -1; #ifdef ENABLE_CLONE if (isSmartContainerEnabled()) { smartinstance_zygote_hook_uid_gid(env, uid, gid, javaGids, javaRlimits, is_system_server, fdsToClose, dataDir); } else{ #endif rc = setresgid(gid, gid, gid); //SmartContainer modified end /* MODIFIED-END by Wang Xiongke,BUG-3005175*/ if (rc == -1) { ALOGE("setresgid(%d) failed: %s", gid, strerror(errno)); RuntimeAbort(env, __LINE__, "setresgid failed"); } rc = setresuid(uid, uid, uid); if (rc == -1) { ALOGE("setresuid(%d) failed: %s", uid, strerror(errno)); RuntimeAbort(env, __LINE__, "setresuid failed"); } /* MODIFIED-BEGIN by Wang Xiongke, 2016-09-28,BUG-3005175*/ //SmartContainer modified begin #ifdef ENABLE_CLONE } #endif //SmartContainer modified end /* MODIFIED-END by Wang Xiongke,BUG-3005175*/ if (NeedsNoRandomizeWorkaround()) { // Work around ARM kernel ASLR lossage (http://b/5817320). int old_personality = personality(0xffffffff); int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE); if (new_personality == -1) { ALOGW("personality(%d) failed: %s", new_personality, strerror(errno)); } } SetCapabilities(env, permittedCapabilities, effectiveCapabilities); SetSchedulerPolicy(env); const char* se_info_c_str = NULL; ScopedUtfChars* se_info = NULL; if (java_se_info != NULL) { se_info = new ScopedUtfChars(env, java_se_info); se_info_c_str = se_info->c_str(); if (se_info_c_str == NULL) { RuntimeAbort(env, __LINE__, "se_info_c_str == NULL"); } } const char* se_name_c_str = NULL; ScopedUtfChars* se_name = NULL; if (java_se_name != NULL) { se_name = new ScopedUtfChars(env, java_se_name); se_name_c_str = se_name->c_str(); if (se_name_c_str == NULL) { RuntimeAbort(env, __LINE__, "se_name_c_str == NULL"); } } rc = selinux_android_setcontext(uid, is_system_server, se_info_c_str, se_name_c_str); if (rc == -1) { ALOGE("selinux_android_setcontext(%d, %d, \"%s\", \"%s\") failed", uid, is_system_server, se_info_c_str, se_name_c_str); RuntimeAbort(env, __LINE__, "selinux_android_setcontext failed"); } /* MODIFIED-BEGIN by Wang Xiongke, 2016-09-28,BUG-3005175*/ //SmartContainer modified begin #ifdef ENABLE_CLONE if (isSmartContainerEnabled()) { smartinstance_zygote_hook_post(env, uid, gid, javaGids, javaRlimits, is_system_server, fdsToClose, dataDir); } #endif //SmartContainer modified end /* MODIFIED-END by Wang Xiongke,BUG-3005175*/ // Make it easier to debug audit logs by setting the main thread's name to the // nice name rather than "app_process". if (se_info_c_str == NULL && is_system_server) { se_name_c_str = "system_server"; } if (se_info_c_str != NULL) { SetThreadName(se_name_c_str); } delete se_info; delete se_name; UnsetSigChldHandler(); env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,is_system_server, instructionSet); /*此处又通过java虚拟机来调用java类的方法 gZygoteClass对应的类名是 "com/android/internal/os/Zygote" 调用的静态方法gCallPostForkChildHooks对应zygote类的"callPostForkChildHooks" */ if (env->ExceptionCheck()) { RuntimeAbort(env, __LINE__, "Error calling post fork hooks."); } } else if (pid > 0) { // the parent process #ifdef ENABLE_SCHED_BOOST // unset scheduler knob SetForkLoad(false); #endif // We blocked SIGCHLD prior to a fork, we unblock it here. if (sigprocmask(SIG_UNBLOCK, &sigchld, nullptr) == -1) { ALOGE("sigprocmask(SIG_SETMASK, { SIGCHLD }) failed: %s", strerror(errno)); RuntimeAbort(env, __LINE__, "Call to sigprocmask(SIG_UNBLOCK, { SIGCHLD }) failed."); } } return pid; } } // anonymous namespace static const char kZygoteClassName[] = "com/android/internal/os/Zygote"; static jclass gZygoteClass; static jmethodID gCallPostForkChildHooks; int register_com_android_internal_os_Zygote(JNIEnv* env) { gZygoteClass = MakeGlobalRefOrDie(env, FindClassOrDie(env, kZygoteClassName)); gCallPostForkChildHooks = GetStaticMethodIDOrDie(env, gZygoteClass, "callPostForkChildHooks", "(IZLjava/lang/String;)V"); return RegisterMethodsOrDie(env, "com/android/internal/os/Zygote", gMethods, NELEM(gMethods)); }
所以这个方法中主要做了:
/** * Finish remaining work for the newly forked system server process. */ private static void handleSystemServerProcess( ZygoteConnection.Arguments parsedArgs) throws ZygoteInit.MethodAndArgsCaller { closeServerSocket();/*因为system_server是从app_process进程fork出来,它也有个zygote socket,所以在这里需要关闭它*/ // set umask to 0077 so new files and directories will default to owner-only permissions. Os.umask(S_IRWXG | S_IRWXO); if (parsedArgs.niceName != null) { Process.setArgV0(parsedArgs.niceName);/*进程名字设置为system_server*/ } final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH"); if (systemServerClasspath != null) { performSystemServerDexOpt(systemServerClasspath); } if (parsedArgs.invokeWith != null) { String[] args = parsedArgs.remainingArgs; // If we have a non-null system server class path, we'll have to duplicate the existing arguments and append the classpath to it. ART will handle the classpath correctly when we exec a new process. if (systemServerClasspath != null) { String[] amendedArgs = new String[args.length + 2]; amendedArgs[0] = "-cp"; amendedArgs[1] = systemServerClasspath; System.arraycopy(parsedArgs.remainingArgs, 0, amendedArgs, 2, parsedArgs.remainingArgs.length); } WrapperInit.execApplication(parsedArgs.invokeWith,parsedArgs.niceName, parsedArgs.targetSdkVersion, VMRuntime.getCurrentInstructionSet(), null, args); } else {/*如果是syster_server走此流程*/ ClassLoader cl = null; if (systemServerClasspath != null) { cl = createSystemServerClassLoader(systemServerClasspath,parsedArgs.targetSdkVersion); Thread.currentThread().setContextClassLoader(cl); } /* * Pass the remaining arguments to SystemServer. */ RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl); } /* should never reach here */ }
从名字可以知道该方法用来完成system_server进程遗留下来的工作,
首先,关闭从app_process 进程fork来的 socket ,因为system_server不需要其他进程通过socket向它发生请求,system_server使用的binder实现跨进程请求
然后,创建一个ClassLoader
最后, 执行zygoteInit
/** * The main function called when started through the zygote process. This could be unified with main(), if the native code in nativeFinishInit() were rationalized with Zygote startup.<p> * * Current recognized args: * <ul> * <li> <code> [--] <start class name> <args> * </ul> * * @param targetSdkVersion target SDK version * @param argv arg strings */ public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) throws ZygoteInit.MethodAndArgsCaller { if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from zygote"); Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "RuntimeInit"); redirectLogStreams(); /*从名字就可以猜到 是和log相关的操作*/ commonInit(); nativeZygoteInit();/*启动binder线程池*/ applicationInit(targetSdkVersion, argv, classLoader);/*执行system_server 的主函数*/ }
该方法主要为整个sysete_mserver进程提供binder服务。本质上也是开启一个loop循环,不断的向binder驱动映射的空间继续读操作,并将读取的到信息进行处理,然后将处理结果写回binder驱动,如果没有信息读取,线程阻塞。详细情况 略。
private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) throws ZygoteInit.MethodAndArgsCaller { // If the application calls System.exit(), terminate the process immediately without running any shutdown hooks. It is not possible to shutdown an Android application gracefully. Among other things, the Android runtime shutdown hooks close the Binder driver, which can cause leftover running threads to crash before the process actually exits. nativeSetExitWithoutCleanup(true); // We want to be fairly aggressive about heap utilization, to avoid holding on to a lot of memory that isn't needed. VMRuntime.getRuntime().setTargetHeapUtilization(0.75f); VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion); final Arguments args; try { args = new Arguments(argv); } catch (IllegalArgumentException ex) { Slog.e(TAG, ex.getMessage()); // let the process exit return; } // The end of of the RuntimeInit event (see #zygoteInit). Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); // Remaining arguments are passed to the start class's static main invokeStaticMain(args.startClass, args.startArgs, classLoader); } /** * Invokes a static "main(argv[]) method on class "className". Converts various failing exceptions into RuntimeExceptions, with the assumption that they will then cause the VM instance to exit. * * @param className Fully-qualified class name * @param argv Argument vector for main() * @param classLoader the classLoader to load {@className} with */ private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader) throws ZygoteInit.MethodAndArgsCaller { Class<?> cl; try { cl = Class.forName(className, true, classLoader);/*通过反射获得com.android.server.SystemServer类*/ } catch (ClassNotFoundException ex) { throw new RuntimeException( "Missing class when invoking static main " + className, ex); } Method m; try { m = cl.getMethod("main", new Class[] { String[].class });//*获得main 方法*/ } catch (NoSuchMethodException ex) { throw new RuntimeException( "Missing static main on " + className, ex); } catch (SecurityException ex) { throw new RuntimeException("Problem getting static main on " + className, ex); } int modifiers = m.getModifiers(); if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) { throw new RuntimeException( "Main method is not public and static on " + className); } /* * This throw gets caught in ZygoteInit.main(), which responds by invoking the exception's run() method. This arrangement clears up all the stack frames that were required in setting up the process. */ throw new ZygoteInit.MethodAndArgsCaller(m, argv); /*这里会将方法&&参数存入静态成员类MethodAndArgsCaller中,同时抛出异常,即回到ZygoteInit类main函数中的catchl流程中 } catch (MethodAndArgsCaller caller) { caller.run();//开始执行MethodAndArgsCaller对象的run方法 } */ }
然后看看MethodAndArgsCaller类的run方法实现:
/** * Helper exception class which holds a method and arguments and can call them. This is used as part of a trampoline to get rid of the initial process setup stack frames. */ public static class MethodAndArgsCaller extends Exception implements Runnable { /** method to call */ private final Method mMethod; /** argument array */ private final String[] mArgs; public MethodAndArgsCaller(Method method, String[] args) { mMethod = method; mArgs = args; } public void run() { try { mMethod.invoke(null, new Object[] { mArgs });/*mMethod表示的是com.android.server.SystemServer类main方法,即开始执行main方法*/ } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { Throwable cause = ex.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof Error) { throw (Error) cause; } throw new RuntimeException(ex); } } } }
从startSystemServer开始,经过一系列的操作,到此终于走到了systemServer类的主方法了,之所以需要这么做而不是一开始就执行systemServer的main方法:
/** * The main entry point from zygote. */ public static void main(String[] args) { new SystemServer().run(); } public SystemServer() { // Check for factory test mode. mFactoryTestMode = FactoryTest.getMode(); // Remember if it's runtime restart(when sys.boot_completed is already set) or reboot mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed")); } private void run() { try { Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitBeforeStartServices"); // If a device's clock is before 1970 (before 0), a lot of // APIs crash dealing with negative numbers, notably // java.io.File#setLastModified, so instead we fake it and // hope that time from cell towers or NTP fixes it shortly. if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) { Slog.w(TAG, "System clock is before 1970; setting to 1970."); SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME); } // If the system has "persist.sys.language" and friends set, replace them with // "persist.sys.locale". Note that the default locale at this point is calculated // using the "-Duser.locale" command line flag. That flag is usually populated by // AndroidRuntime using the same set of system properties, but only the system_server // and system apps are allowed to set them. // // NOTE: Most changes made here will need an equivalent change to // core/jni/AndroidRuntime.cpp //[SDM]feature_language_fromsim_on is not effect //persist.sys.language should not influence persist.sys.locale as they have different uses. // Here we go! Slog.i(TAG, "Entered the Android system server!"); EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis()); // In case the runtime switched since last boot (such as when // the old runtime was removed in an OTA), set the system // property so that it is in sync. We can't do this in // libnativehelper's JniInvocation::Init code where we already // had to fallback to a different runtime because it is // running as root and we need to be the system user to set // the property. http://b/11463182 SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary()); // Enable the sampling profiler. if (SamplingProfilerIntegration.isEnabled()) { SamplingProfilerIntegration.start(); mProfilerSnapshotTimer = new Timer(); mProfilerSnapshotTimer.schedule(new TimerTask() { @Override public void run() { SamplingProfilerIntegration.writeSnapshot("system_server", null); } }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL); } // Mmmmmm... more memory! VMRuntime.getRuntime().clearGrowthLimit(); // The system server has to run all of the time, so it needs to be // as efficient as possible with its memory usage. VMRuntime.getRuntime().setTargetHeapUtilization(0.8f); // Some devices rely on runtime fingerprint generation, so make sure // we've defined it before booting further. Build.ensureFingerprintProperty(); // Within the system server, it is an error to access Environment paths without // explicitly specifying a user. Environment.setUserRequired(true); // Within the system server, any incoming Bundles should be defused // to avoid throwing BadParcelableException. BaseBundle.setShouldDefuse(true); // Ensure binder calls into the system always run at foreground priority. BinderInternal.disableBackgroundScheduling(true); // Increase the number of binder threads in system_server BinderInternal.setMaxThreads(sMaxBinderThreads); // Prepare the main looper thread (this thread). android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_FOREGROUND); android.os.Process.setCanSelfBackground(false); Looper.prepareMainLooper(); // Initialize native services. System.loadLibrary("android_servers"); ///M:Add for low storage feature,to delete the reserver file.@{ try { Runtime.getRuntime().exec("rm -r /data/piggybank"); } catch (IOException e) { Slog.e(TAG, "system server init delete piggybank fail" + e); } //@} // Check whether we failed to shut down last time we tried. // This call may not return. performPendingShutdown(); // Initialize the system context. createSystemContext(); // Create the system service manager. mSystemServiceManager = new SystemServiceManager(mSystemContext); mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart); LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); } finally { Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } // Start services. try { Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices"); startBootstrapServices(); startCoreServices(); startOtherServices(); } catch (Throwable ex) { Slog.e("System", "******************************************"); Slog.e("System", "************ Failure starting system services", ex); StringBuilder exception = new StringBuilder(256); exception.append(ex.getClass().getName()); exception.append("_"); exception.append(ex.toString()); MiniLogger.writeSystemLog(exception.toString(),Log.getStackTraceString(ex)); throw ex; } finally { Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } // For debug builds, log event loop stalls to dropbox for analysis. if (StrictMode.conditionallyEnableDebugLogging()) { Slog.i(TAG, "Enabled StrictMode for system server main thread."); } recordLastBootTime(); // Loop forever. Looper.loop();/*进入死循环,直到关机*/ throw new RuntimeException("Main thread loop unexpectedly exited");/*所以这个语句正常情况不会执行 */ }
/** * Starts the small tangle of critical services that are needed to get the system off the ground. These services have complex mutual dependencies which is why we initialize them all in one place here. Unless your service is also entwined in these dependencies, it should be initialized in one of the other functions. */ //SmartContainer modified begin private Installer mInstaller; //SmartContainer modified end private void startBootstrapServices() { // Wait for installd to finish starting up so that it has a chance to create critical directories such as /data/user with the appropriate permissions. We need this to complete before we initialize other services. Installer installer = mSystemServiceManager.startService(Installer.class); //SmartContainer modified begin mInstaller = installer; //SmartContainer modified end // Activity manager runs the show. mActivityManagerService = mSystemServiceManager.startService(ActivityManagerService.Lifecycle.class).getService(); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); // Power manager needs to be started early because other services need it.Native daemons may be watching for it to be registered so it must be ready to handle incoming binder calls immediately (including being able to verify the permissions for those calls). mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class); // Now that the power manager has been started, let the activity manager initialize power management features. Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitPowerManagement"); mActivityManagerService.initPowerManagement(); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); // Manages LEDs and display backlight so we need it to bring up the display. mSystemServiceManager.startService(LightsService.class); // Display manager is needed to provide display metrics before package manager starts up. mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class); // We need the default display before we can initialize the package manager. mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY); // Only run "core" apps if we're encrypting the device. String cryptState = SystemProperties.get("vold.decrypt"); mIsAlarmBoot = SystemProperties.getBoolean("ro.alarm_boot", false); if (ENCRYPTING_STATE.equals(cryptState)) { Slog.w(TAG, "Detected encryption in progress - only parsing core apps"); mOnlyCore = true; } else if (ENCRYPTED_STATE.equals(cryptState)) { Slog.w(TAG, "Device encrypted - only parsing core apps"); mOnlyCore = true; } else if (mIsAlarmBoot) { // power off alarm mode is similar to encryption mode. Only power off alarm applications will be parsed by packageParser. Some services or settings are not necessary to power off alarm mode. So reuse mOnlyCore for power off alarm mode. mOnlyCore = true; } if (RegionalizationEnvironment.isSupported()) { Slog.i(TAG, "Regionalization Service"); RegionalizationService regionalizationService = new RegionalizationService(); ServiceManager.addService("regionalization", regionalizationService); } // Start the package manager. traceBeginAndSlog("StartPackageManagerService"); mPackageManagerService = PackageManagerService.main(mSystemContext, installer,mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore); mFirstBoot = mPackageManagerService.isFirstBoot(); mPackageManager = mSystemContext.getPackageManager(); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename A/B artifacts after boot, before anything else might touch/need them. // Note: this isn't needed during decryption (we don't have /data anyways). if (!mOnlyCore) { boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt", false); if (!disableOtaDexopt) { traceBeginAndSlog("StartOtaDexOptService"); try { OtaDexoptService.main(mSystemContext, mPackageManagerService); } catch (Throwable e) { reportWtf("starting OtaDexOptService", e); } finally { Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } } } traceBeginAndSlog("StartUserManagerService"); mSystemServiceManager.startService(UserManagerService.LifeCycle.class); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); // Initialize attribute cache used to cache resources from packages. AttributeCache.init(mSystemContext); // Set up the Application instance for the system process and get started. mActivityManagerService.setSystemProcess(); // The sensor service needs access to package manager service, app opsservice, and permissions service, therefore we start it after them. startSensorService(); }
/data/user
,该目录可以保证其他服务顺利启动 /**
* Starts some essential services that are not tangled up in the bootstrap process.
*/
private void startCoreServices() {
// Tracks the battery level. Requires LightService.
mSystemServiceManager.startService(BatteryService.class);
// Tracks application usage stats.
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
// Tracks whether the updatable WebView is in a ready state and watches for update installs.
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
}
核心服务优先级低于bootstrap服务,它下面的服务不是很多,主要包括电池电量管理服务、应用程序使用情况管理服务等。
/** * Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized. */ private void startOtherServices() { final Context context = mSystemContext; VibratorService vibrator = null; IMountService mountService = null; NetworkManagementService networkManagement = null; NetworkStatsService networkStats = null; NetworkPolicyManagerService networkPolicy = null; ConnectivityService connectivity = null; NetworkScoreService networkScore = null; NsdService serviceDiscovery= null; WindowManagerService wm = null; SerialService serial = null; NetworkTimeUpdateService networkTimeUpdater = null; CommonTimeManagementService commonTimeMgmtService = null; InputManagerService inputManager = null; TelephonyRegistry telephonyRegistry = null; ConsumerIrService consumerIr = null; MmsServiceBroker mmsService = null; HardwarePropertiesManagerService hardwarePropertiesService = null; Object wigigP2pService = null; Object wigigService = null; AlipayFingerprintService alipayFingerprintService = null; SsvService ssvService = null; boolean ssvEnabled = false; try { ssvEnabled = SystemProperties.getBoolean("ro.ssv.enabled", false); if (ssvEnabled) { //Slog.i(TAG, "SSV Service"); ssvService = new SsvService(mSystemContext); ServiceManager.addService(Context.SSV_SERVICE, ssvService); } } catch (RuntimeException e) { Slog.e(TAG, "Starting SsvService exception ", e); } BackupManagerService backup = null; try { Slog.i(TAG, "tct BackupManagerService"); backup = new BackupManagerService(mSystemContext); if (backup != null) { ServiceManager.addService(Context.TCT_BACKUP_SERVICE, backup); backup.start(); } } catch (Throwable e) { reportWtf("Failure starting tct BackupManagerService", e); } boolean disableStorage = SystemProperties.getBoolean("config.disable_storage", false); boolean disableBluetooth = SystemProperties.getBoolean("config.disable_bluetooth", false); boolean disableLocation = SystemProperties.getBoolean("config.disable_location", false); boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui", false); boolean disableNonCoreServices = SystemProperties.getBoolean("config.disable_noncore", false); boolean disableNetwork = SystemProperties.getBoolean("config.disable_network", false); boolean disableNetworkTime = SystemProperties.getBoolean("config.disable_networktime", false); boolean disableRtt = SystemProperties.getBoolean("config.disable_rtt", false); boolean disableMediaProjection = SystemProperties.getBoolean("config.disable_mediaproj", false); boolean disableSerial = SystemProperties.getBoolean("config.disable_serial", false); boolean disableSearchManager = SystemProperties.getBoolean("config.disable_searchmanager", false); boolean disableTrustManager = SystemProperties.getBoolean("config.disable_trustmanager", false); boolean disableTextServices = SystemProperties.getBoolean("config.disable_textservices", false); boolean disableSamplingProfiler = SystemProperties.getBoolean("config.disable_samplingprof", false); boolean disableConsumerIr = SystemProperties.getBoolean("config.disable_consumerir", false); boolean disableVrManager = SystemProperties.getBoolean("config.disable_vrmanager", false); boolean disableCameraService = SystemProperties.getBoolean("config.disable_cameraservice", false); boolean isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1"); boolean enableWigig = SystemProperties.getBoolean("persist.wigig.enable", false); //Modified for SmartContainer begin IBinder containerService = null; try { if ( !SmartContainerConfig.WITH_OUT_ALL ){ Slog.i(TAG, "Loading SmartContainer Core service"); try { Class containerServiceClass = Thread.currentThread().getContextClassLoader() .loadClass("com.cmx.cmplus.SmartContainerManagerService"); Constructor ctor = containerServiceClass.getConstructor(Context.class); ctor.setAccessible(true); containerService = (IBinder)ctor.newInstance(mSystemContext); Method startMethod = containerServiceClass.getMethod("start" ); startMethod.invoke(containerService); ServiceManager.addService("smart_container", containerService); Method setMethod = containerServiceClass.getMethod("setInstallerConnection", InstallerConnection.class); setMethod.invoke(containerService, mInstaller.getInstallerConnection()); } catch (Exception e) { Slog.e("System", "Failed to load container service. Disable all!\n" + e); e.printStackTrace(); SmartContainerConfig.turnOff(); } } //Modified for SmartContainer end Slog.i(TAG, "Reading configuration..."); SystemConfig.getInstance(); traceBeginAndSlog("StartSchedulingPolicyService"); ServiceManager.addService("scheduling_policy", new SchedulingPolicyService()); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); mSystemServiceManager.startService(TelecomLoaderService.class); boolean disableAlipayFingerprint = SystemProperties.getBoolean("ro.alipay.fingerprint.show",false); Slog.d(TAG,"disableAlipayFingerprint = " + disableAlipayFingerprint); if (disableAlipayFingerprint) { try { Slog.i(TAG, "AlipayFingerprintService"); alipayFingerprintService = new AlipayFingerprintService(context); ServiceManager.addService(Context.ALIPAY_FP_SERVICE, alipayFingerprintService); } catch (Exception e) { Slog.e(TAG, "Failure starting AlipayFingerprintService", e); } } traceBeginAndSlog("StartTelephonyRegistry"); telephonyRegistry = new TelephonyRegistry(context); ServiceManager.addService("telephony.registry", telephonyRegistry); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); traceBeginAndSlog("StartEntropyMixer"); mEntropyMixer = new EntropyMixer(context); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); mContentResolver = context.getContentResolver(); if (!disableCameraService) { Slog.i(TAG, "Camera Service"); mSystemServiceManager.startService(CameraService.class); } // The AccountManager must come before the ContentService traceBeginAndSlog("StartAccountManagerService"); mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); traceBeginAndSlog("StartContentService"); mSystemServiceManager.startService(CONTENT_SERVICE_CLASS); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); traceBeginAndSlog("InstallSystemProviders"); mActivityManagerService.installSystemProviders(); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); traceBeginAndSlog("StartVibratorService"); vibrator = new VibratorService(context); ServiceManager.addService("vibrator", vibrator); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); if (!disableConsumerIr) { traceBeginAndSlog("StartConsumerIrService"); consumerIr = new ConsumerIrService(context); ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } traceBeginAndSlog("StartAlarmManagerService"); mSystemServiceManager.startService(AlarmManagerService.class); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); traceBeginAndSlog("InitWatchdog"); final Watchdog watchdog = Watchdog.getInstance(); watchdog.init(context, mActivityManagerService); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); traceBeginAndSlog("StartInputManagerService"); inputManager = new InputManagerService(context); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); traceBeginAndSlog("StartWindowManagerService"); wm = WindowManagerService.main(context, inputManager, mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL, !mFirstBoot, mOnlyCore); ServiceManager.addService(Context.WINDOW_SERVICE, wm); ServiceManager.addService(Context.INPUT_SERVICE, inputManager); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); if (!disableVrManager) { traceBeginAndSlog("StartVrManagerService"); mSystemServiceManager.startService(VrManagerService.class); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } mActivityManagerService.setWindowManager(wm); inputManager.setWindowManagerCallbacks(wm.getInputMonitor()); inputManager.start(); // TODO: Use service dependencies instead. mDisplayManagerService.windowManagerAndInputReady(); if(Global.SPRINT_APP_SPECIFIC_FEATURE) { sprintExtensionService = new SprintExtensionService(context); ServiceManager.addService(Context.SPRINT_EXTENSION_SERVICE, sprintExtensionService); } // Skip Bluetooth if we have an emulator kernel // TODO: Use a more reliable check to see if this product should // support Bluetooth - see bug 988521 if (isEmulator) { Slog.i(TAG, "No Bluetooth Service (emulator)"); } else if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) { Slog.i(TAG, "No Bluetooth Service (factory test)"); } else if (!context.getPackageManager().hasSystemFeature (PackageManager.FEATURE_BLUETOOTH)) { Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)"); } else if (disableBluetooth) { Slog.i(TAG, "Bluetooth Service disabled by config"); } else { mSystemServiceManager.startService(BluetoothService.class); } traceBeginAndSlog("ConnectivityMetricsLoggerService"); mSystemServiceManager.startService(MetricsLoggerService.class); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); traceBeginAndSlog("IpConnectivityMetrics"); mSystemServiceManager.startService(IpConnectivityMetrics.class); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); traceBeginAndSlog("PinnerService"); mSystemServiceManager.startService(PinnerService.class); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } catch (RuntimeException e) { Slog.e("System", "******************************************"); Slog.e("System", "************ Failure starting core service", e); } StatusBarManagerService statusBar = null; INotificationManager notification = null; LocationManagerService location = null; CountryDetectorService countryDetector = null; ILockSettings lockSettings = null; AssetAtlasService atlas = null; MediaRouterService mediaRouter = null; // Bring up services needed for UI. if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) { mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class); traceBeginAndSlog("StartAccessibilityManagerService"); try { ServiceManager.addService(Context.ACCESSIBILITY_SERVICE, new AccessibilityManagerService(context)); } catch (Throwable e) { reportWtf("starting Accessibility Manager", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } try { wm.displayReady(); } catch (Throwable e) { reportWtf("making display ready", e); } if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) { if (!disableStorage && !"0".equals(SystemProperties.get("system_init.startmountservice"))) { try { /* * NotificationManagerService is dependant on MountService, * (for media / usb notifications) so we must start MountService first. */ mSystemServiceManager.startService(MOUNT_SERVICE_CLASS); mountService = IMountService.Stub.asInterface( ServiceManager.getService("mount")); } catch (Throwable e) { reportWtf("starting Mount Service", e); } } } // We start this here so that we update our configuration to set watch or television // as appropriate. mSystemServiceManager.startService(UiModeManagerService.class); if (!mOnlyCore) { Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "UpdatePackagesIfNeeded"); try { mPackageManagerService.updatePackagesIfNeeded(); } catch (Throwable e) { reportWtf("update packages", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PerformFstrimIfNeeded"); try { mPackageManagerService.performFstrimIfNeeded(); } catch (Throwable e) { reportWtf("performing fstrim", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) { if (!disableNonCoreServices) { traceBeginAndSlog("StartLockSettingsService"); try { mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS); lockSettings = ILockSettings.Stub.asInterface( ServiceManager.getService("lock_settings")); } catch (Throwable e) { reportWtf("starting LockSettingsService service", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); if (!SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("")) { mSystemServiceManager.startService(PersistentDataBlockService.class); } mSystemServiceManager.startService(DeviceIdleController.class); // Always start the Device Policy Manager, so that the API is compatible with // API8. mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class); } if (!disableSystemUI) { traceBeginAndSlog("StartStatusBarManagerService"); try { statusBar = new StatusBarManagerService(context, wm); ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar); } catch (Throwable e) { reportWtf("starting StatusBarManagerService", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } if (!disableNonCoreServices) { traceBeginAndSlog("StartClipboardService"); try { ServiceManager.addService(Context.CLIPBOARD_SERVICE, new ClipboardService(context)); } catch (Throwable e) { reportWtf("starting Clipboard Service", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } if (!disableNetwork) { traceBeginAndSlog("StartNetworkManagementService"); try { networkManagement = NetworkManagementService.create(context); ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement); } catch (Throwable e) { reportWtf("starting NetworkManagement Service", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } if (!disableNonCoreServices && !disableTextServices) { mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class); } if (!disableNetwork) { traceBeginAndSlog("StartNetworkScoreService"); try { networkScore = new NetworkScoreService(context); ServiceManager.addService(Context.NETWORK_SCORE_SERVICE, networkScore); } catch (Throwable e) { reportWtf("starting Network Score Service", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); traceBeginAndSlog("StartNetworkStatsService"); try { networkStats = NetworkStatsService.create(context, networkManagement); ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats); } catch (Throwable e) { reportWtf("starting NetworkStats Service", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); traceBeginAndSlog("StartNetworkPolicyManagerService"); try { networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService, networkStats, networkManagement); ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy); } catch (Throwable e) { reportWtf("starting NetworkPolicy Service", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_NAN)) { mSystemServiceManager.startService(WIFI_NAN_SERVICE_CLASS); } else { Slog.i(TAG, "No Wi-Fi NAN Service (NAN support Not Present)"); } mSystemServiceManager.startService(WIFI_P2P_SERVICE_CLASS); mSystemServiceManager.startService(WIFI_SERVICE_CLASS); mSystemServiceManager.startService( "com.android.server.wifi.scanner.WifiScanningService"); if (!disableRtt) { mSystemServiceManager.startService("com.android.server.wifi.RttService"); } if (enableWigig) { try { Slog.i(TAG, "Wigig Service"); PathClassLoader wigigClassLoader = new PathClassLoader("/system/framework/wigig-service.jar", "/system/lib64:/system/vendor/lib64", getClass().getClassLoader()); Class wigigP2pClass = wigigClassLoader.loadClass( "com.qualcomm.qti.server.wigig.p2p.WigigP2pServiceImpl"); Constructor<Class> ctor = wigigP2pClass.getConstructor(Context.class); wigigP2pService = ctor.newInstance(context); Slog.i(TAG, "Successfully loaded WigigP2pServiceImpl class"); ServiceManager.addService("wigigp2p", (IBinder) wigigP2pService); Class wigigClass = wigigClassLoader.loadClass( "com.qualcomm.qti.server.wigig.WigigService"); ctor = wigigClass.getConstructor(Context.class); wigigService = ctor.newInstance(context); Slog.i(TAG, "Successfully loaded WigigService class"); ServiceManager.addService("wigig", (IBinder) wigigService); } catch (Throwable e) { reportWtf("starting WigigService", e); } } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) || mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) { mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS); } traceBeginAndSlog("StartConnectivityService"); try { connectivity = new ConnectivityService( context, networkManagement, networkStats, networkPolicy); ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity); networkStats.bindConnectivityManager(connectivity); networkPolicy.bindConnectivityManager(connectivity); } catch (Throwable e) { reportWtf("starting Connectivity Service", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); traceBeginAndSlog("StartNsdService"); try { serviceDiscovery = NsdService.create(context); ServiceManager.addService( Context.NSD_SERVICE, serviceDiscovery); } catch (Throwable e) { reportWtf("starting Service Discovery Service", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } if (!disableNonCoreServices) { traceBeginAndSlog("StartUpdateLockService"); try { ServiceManager.addService(Context.UPDATE_LOCK_SERVICE, new UpdateLockService(context)); } catch (Throwable e) { reportWtf("starting UpdateLockService", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } if (!disableNonCoreServices) { mSystemServiceManager.startService(RecoverySystemService.class); } /* * MountService has a few dependencies: Notification Manager and * AppWidget Provider. Make sure MountService is completely started * first before continuing. */ if (mountService != null && !mOnlyCore) { Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "WaitForAsecScan"); try { mountService.waitForAsecScan(); } catch (RemoteException ignored) { } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } mSystemServiceManager.startService(NotificationManagerService.class); notification = INotificationManager.Stub.asInterface( ServiceManager.getService(Context.NOTIFICATION_SERVICE)); networkPolicy.bindNotificationManager(notification); mSystemServiceManager.startService(DeviceStorageMonitorService.class); if (!disableLocation) { traceBeginAndSlog("StartLocationManagerService"); try { location = new LocationManagerService(context); ServiceManager.addService(Context.LOCATION_SERVICE, location); } catch (Throwable e) { reportWtf("starting Location Manager", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); traceBeginAndSlog("StartCountryDetectorService"); try { countryDetector = new CountryDetectorService(context); ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector); } catch (Throwable e) { reportWtf("starting Country Detector", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } if (!disableNonCoreServices && !disableSearchManager) { traceBeginAndSlog("StartSearchManagerService"); try { mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS); } catch (Throwable e) { reportWtf("starting Search Service", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } mSystemServiceManager.startService(DropBoxManagerService.class); if (!disableNonCoreServices && context.getResources().getBoolean( R.bool.config_enableWallpaperService) && !mIsAlarmBoot) { traceBeginAndSlog("StartWallpaperManagerService"); mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } traceBeginAndSlog("StartAudioService"); mSystemServiceManager.startService(AudioService.Lifecycle.class); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); if (!disableNonCoreServices) { mSystemServiceManager.startService(DockObserver.class); if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) { //#Fixme:mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS); } } traceBeginAndSlog("StartWiredAccessoryManager"); try { // Listen for wired headset changes inputManager.setWiredAccessoryCallbacks( new WiredAccessoryManager(context, inputManager)); } catch (Throwable e) { reportWtf("starting WiredAccessoryManager", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); if (!disableNonCoreServices) { if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) { // Start MIDI Manager service mSystemServiceManager.startService(MIDI_SERVICE_CLASS); } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST) || mPackageManager.hasSystemFeature( PackageManager.FEATURE_USB_ACCESSORY)) { // Manage USB host and device support Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartUsbService"); mSystemServiceManager.startService(USB_SERVICE_CLASS); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } if (!disableSerial) { traceBeginAndSlog("StartSerialService"); try { // Serial port support serial = new SerialService(context); ServiceManager.addService(Context.SERIAL_SERVICE, serial); } catch (Throwable e) { Slog.e(TAG, "Failure starting SerialService", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartHardwarePropertiesManagerService"); try { hardwarePropertiesService = new HardwarePropertiesManagerService(context); ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE, hardwarePropertiesService); } catch (Throwable e) { Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } mSystemServiceManager.startService(TwilightService.class); if (NightDisplayController.isAvailable(context)) { mSystemServiceManager.startService(NightDisplayService.class); } mSystemServiceManager.startService(JobSchedulerService.class); mSystemServiceManager.startService(SoundTriggerService.class); if (!disableNonCoreServices) { if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) { mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS); } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS) || context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) { mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS); } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_VOICE_RECOGNIZERS)) { mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS); } if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) { Slog.i(TAG, "Gesture Launcher Service"); mSystemServiceManager.startService(GestureLauncherService.class); } mSystemServiceManager.startService(SensorNotificationService.class); mSystemServiceManager.startService(ContextHubSystemService.class); } traceBeginAndSlog("StartDiskStatsService"); try { ServiceManager.addService("diskstats", new DiskStatsService(context)); } catch (Throwable e) { reportWtf("starting DiskStats Service", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); if (!disableSamplingProfiler) { traceBeginAndSlog("StartSamplingProfilerService"); try { // need to add this service even if SamplingProfilerIntegration.isEnabled() // is false, because it is this service that detects system property change and // turns on SamplingProfilerIntegration. Plus, when sampling profiler doesn't work, // there is little overhead for running this service. ServiceManager.addService("samplingprofiler", new SamplingProfilerService(context)); } catch (Throwable e) { reportWtf("starting SamplingProfiler Service", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } if (!disableNetwork && !disableNetworkTime) { traceBeginAndSlog("StartNetworkTimeUpdateService"); try { networkTimeUpdater = new NetworkTimeUpdateService(context); ServiceManager.addService("network_time_update_service", networkTimeUpdater); } catch (Throwable e) { reportWtf("starting NetworkTimeUpdate service", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } traceBeginAndSlog("StartCommonTimeManagementService"); try { commonTimeMgmtService = new CommonTimeManagementService(context); ServiceManager.addService("commontime_management", commonTimeMgmtService); } catch (Throwable e) { reportWtf("starting CommonTimeManagementService service", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); if (!disableNetwork) { traceBeginAndSlog("CertBlacklister"); try { CertBlacklister blacklister = new CertBlacklister(context); } catch (Throwable e) { reportWtf("starting CertBlacklister", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } if (!disableNetwork && !disableNonCoreServices && EmergencyAffordanceManager.ENABLED) { // EmergencyMode sevice mSystemServiceManager.startService(EmergencyAffordanceService.class); } if (!disableNonCoreServices) { // Dreams (interactive idle-time views, a/k/a screen savers, and doze mode) mSystemServiceManager.startService(DreamManagerService.class); } if (!disableNonCoreServices && ZygoteInit.PRELOAD_RESOURCES) { traceBeginAndSlog("StartAssetAtlasService"); try { atlas = new AssetAtlasService(context); ServiceManager.addService(AssetAtlasService.ASSET_ATLAS_SERVICE, atlas); } catch (Throwable e) { reportWtf("starting AssetAtlasService", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } if (!disableNonCoreServices) { ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE, new GraphicsStatsService(context)); } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) { mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS); } mSystemServiceManager.startService(RestrictionsManagerService.class); mSystemServiceManager.startService(MediaSessionService.class); if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) { mSystemServiceManager.startService(HdmiControlService.class); } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)) { mSystemServiceManager.startService(TvInputManagerService.class); } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) { mSystemServiceManager.startService(MediaResourceMonitorService.class); } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { mSystemServiceManager.startService(TvRemoteService.class); } if (!disableNonCoreServices) { traceBeginAndSlog("StartMediaRouterService"); try { mediaRouter = new MediaRouterService(context); ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter); } catch (Throwable e) { reportWtf("starting MediaRouterService", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); if (!disableTrustManager) { mSystemServiceManager.startService(TrustManagerService.class); } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) { mSystemServiceManager.startService(FingerprintService.class); } traceBeginAndSlog("StartBackgroundDexOptService"); try { BackgroundDexOptService.schedule(context); } catch (Throwable e) { reportWtf("starting BackgroundDexOptService", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } // LauncherAppsService uses ShortcutService. mSystemServiceManager.startService(ShortcutService.Lifecycle.class); mSystemServiceManager.startService(LauncherAppsService.class); } boolean fpenable = context.getResources().getBoolean(com.android.internal.R.bool.feature_attrname_enabled); if(fpenable && Global.JRD_ATTRNAME_SERVICE){ mSystemServiceManager.startService(AttrNameService.class); } if (!disableNonCoreServices && !disableMediaProjection) { mSystemServiceManager.startService(MediaProjectionManagerService.class); } if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) { //#Fixme:mSystemServiceManager.startService(WEAR_BLUETOOTH_SERVICE_CLASS); mSystemServiceManager.startService(WEAR_BLUETOOTH_SERVICE_CLASS); mSystemServiceManager.startService(WEAR_WIFI_MEDIATOR_SERVICE_CLASS); if (SystemProperties.getBoolean("config.enable_cellmediator", false)) { mSystemServiceManager.startService(WEAR_CELLULAR_MEDIATOR_SERVICE_CLASS); } if (!disableNonCoreServices) { mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS); } } // Before things start rolling, be sure we have decided whether we are in safe mode. final boolean safeMode = wm.detectSafeMode(); if (safeMode) { mActivityManagerService.enterSafeMode(); // Disable the JIT for the system_server process VMRuntime.getRuntime().disableJitCompilation(); } else { // Enable the JIT for the system_server process VMRuntime.getRuntime().startJitCompilation(); } // MMS service broker mmsService = mSystemServiceManager.startService(MmsServiceBroker.class); if (Settings.Global.getInt(mContentResolver, Settings.Global.DEVICE_PROVISIONED, 0) == 0 ||UserManager.isDeviceInDemoMode(mSystemContext)) { mSystemServiceManager.startService(RetailDemoModeService.class); } // It is now time to start up the app processes... Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeVibratorServiceReady"); try { vibrator.systemReady(); } catch (Throwable e) { reportWtf("making Vibrator Service ready", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeLockSettingsServiceReady"); if (lockSettings != null) { try { lockSettings.systemReady(); } catch (Throwable e) { reportWtf("making Lock Settings Service ready", e); } } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); // Needed by DevicePolicyManager for initialization mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY); mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeWindowManagerServiceReady"); // Wigig services are not registered as system services because of class loader limitations, send boot phase notification separately if (enableWigig) { try { Slog.i(TAG, "calling onBootPhase for Wigig Services"); Class wigigP2pClass = wigigP2pService.getClass(); Method m = wigigP2pClass.getMethod("onBootPhase", int.class); m.invoke(wigigP2pService, new Integer(SystemService.PHASE_SYSTEM_SERVICES_READY)); Class wigigClass = wigigService.getClass(); m = wigigClass.getMethod("onBootPhase", int.class); m.invoke(wigigService, new Integer(SystemService.PHASE_SYSTEM_SERVICES_READY)); } catch (Throwable e) { reportWtf("Wigig services ready", e); } } try { wm.systemReady(); } catch (Throwable e) { reportWtf("making Window Manager Service ready", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); if (safeMode) { mActivityManagerService.showSafeModeOverlay(); } // Update the configuration for this context by hand, because we're going to start using it before the config change done in wm.systemReady() will propagate to it. Configuration config = wm.computeNewConfiguration(); DisplayMetrics metrics = new DisplayMetrics(); WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); w.getDefaultDisplay().getMetrics(metrics); context.getResources().updateConfiguration(config, metrics); // The system context's theme may be configuration-dependent. final Theme systemTheme = context.getTheme(); if (systemTheme.getChangingConfigurations() != 0) { systemTheme.rebase(); } Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakePowerManagerServiceReady"); try { // TODO: use boot phase mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService()); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } catch (Throwable e) { reportWtf("making Power Manager Service ready", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakePackageManagerServiceReady"); try { mPackageManagerService.systemReady(); } catch (Throwable e) { reportWtf("making Package Manager Service ready", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeDisplayManagerServiceReady"); try { // TODO: use boot phase and communicate these flags some other way mDisplayManagerService.systemReady(safeMode, mOnlyCore); } catch (Throwable e) { reportWtf("making Display Manager Service ready", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); // These are needed to propagate to the runnable below. final NetworkManagementService networkManagementF = networkManagement; final NetworkStatsService networkStatsF = networkStats; final NetworkPolicyManagerService networkPolicyF = networkPolicy; final ConnectivityService connectivityF = connectivity; final NetworkScoreService networkScoreF = networkScore; final LocationManagerService locationF = location; final CountryDetectorService countryDetectorF = countryDetector; final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater; final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService; final AssetAtlasService atlasF = atlas; final InputManagerService inputManagerF = inputManager; final TelephonyRegistry telephonyRegistryF = telephonyRegistry; final MediaRouterService mediaRouterF = mediaRouter; final MmsServiceBroker mmsServiceF = mmsService; // We now tell the activity manager it is okay to run third partycode. It will call back into us once it has gotten to the state where third party code can really run (but before it has actually started launching the initial applications), for us to complete our initialization. mActivityManagerService.systemReady(new Runnable() { @Override public void run() { Slog.i(TAG, "Making services ready"); mSystemServiceManager.startBootPhase(SystemService.PHASE_ACTIVITY_MANAGER_READY); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseActivityManagerReady"); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartObservingNativeCrashes"); try { mActivityManagerService.startObservingNativeCrashes(); } catch (Throwable e) { reportWtf("observing native crashes", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); if (!mOnlyCore) { Slog.i(TAG, "WebViewFactory preparation"); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "WebViewFactoryPreparation"); mWebViewUpdateService.prepareWebViewInSystemServer(); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartSystemUI"); try { startSystemUi(context); } catch (Throwable e) { reportWtf("starting System UI", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkScoreReady"); try { if (networkScoreF != null) networkScoreF.systemReady(); } catch (Throwable e) { reportWtf("making Network Score Service ready", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkManagementServiceReady"); try { if (networkManagementF != null) networkManagementF.systemReady(); } catch (Throwable e) { reportWtf("making Network Managment Service ready", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkStatsServiceReady"); try { if (networkStatsF != null) networkStatsF.systemReady(); } catch (Throwable e) { reportWtf("making Network Stats Service ready", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkPolicyServiceReady"); try { if (networkPolicyF != null) networkPolicyF.systemReady(); } catch (Throwable e) { reportWtf("making Network Policy Service ready", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeConnectivityServiceReady"); try { if (connectivityF != null) connectivityF.systemReady(); } catch (Throwable e) { reportWtf("making Connectivity Service ready", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); if(Global.SPRINT_APP_SPECIFIC_FEATURE) { try { if (sprintExtensionServiceF != null) sprintExtensionServiceF.systemReady(); } catch (Throwable e) { reportWtf("Notifying MmsService running", e); } } Watchdog.getInstance().start(); // It is now okay to let the various system services start their third party code... Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseThirdPartyAppsCanStart"); mSystemServiceManager.startBootPhase( SystemService.PHASE_THIRD_PARTY_APPS_CAN_START); try { if (locationF != null) locationF.systemRunning(); } catch (Throwable e) { reportWtf("Notifying Location Service running", e); } try { if (countryDetectorF != null) countryDetectorF.systemRunning(); } catch (Throwable e) { reportWtf("Notifying CountryDetectorService running", e); } try { if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning(); } catch (Throwable e) { reportWtf("Notifying NetworkTimeService running", e); } try { if (commonTimeMgmtServiceF != null) { commonTimeMgmtServiceF.systemRunning(); } } catch (Throwable e) { reportWtf("Notifying CommonTimeManagementService running", e); } try { if (atlasF != null) atlasF.systemRunning(); } catch (Throwable e) { reportWtf("Notifying AssetAtlasService running", e); } try { // TODO(BT) Pass parameter to input manager if (inputManagerF != null) inputManagerF.systemRunning(); } catch (Throwable e) { reportWtf("Notifying InputManagerService running", e); } try { if (telephonyRegistryF != null) telephonyRegistryF.systemRunning(); } catch (Throwable e) { reportWtf("Notifying TelephonyRegistry running", e); } try { if (mediaRouterF != null) mediaRouterF.systemRunning(); } catch (Throwable e) { reportWtf("Notifying MediaRouterService running", e); } try { if (mmsServiceF != null) mmsServiceF.systemRunning(); } catch (Throwable e) { reportWtf("Notifying MmsService running", e); } try { if (networkScoreF != null) networkScoreF.systemRunning(); } catch (Throwable e) { reportWtf("Notifying NetworkScoreService running", e); } Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } }); //SmartContainer modified begin if ( !SmartContainerConfig.WITH_OUT_ALL ){ Slog.i(TAG, "System Ready for SmartContainer Core service"); try { Class containerServiceClass = Thread.currentThread().getContextClassLoader() .loadClass("com.cmx.cmplus.SmartContainerManagerService"); Method systemReadyMethod = containerServiceClass.getMethod("systemReady" ); systemReadyMethod.invoke(containerService); } catch (Exception e) { Slog.e("System", "Failed to do system ready. Disable all!\n" + e); e.printStackTrace(); SmartContainerConfig.turnOff(); } } //SmartContainer modified end }
这个other services相对于其他2个服务它是优先级最低的,而且包括的服务也是最多的,懒得写了 略.
参考 《android 内核设计思想》
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。