1、SystemServer进程作用
SystemServer进程紧张是用于创建体系服务的,比方AMS、WMS、PMS;
SystemService进程被创建后,紧张的处理处罚如下:
● 初始化一些体系设置,假造机设置等;
● 启动Binder线程池,如许就可以与其他进程举行Binder跨进程通讯;
● 创建SystemServiceManager,它用来对体系服务举行创建、启动和生命周期管理;
● 创建主线程Looper并进入循环等候消息;
● 启动各种体系服务:引导服务、核心折务、其他服务,如引导服务ActivityManagerService、PackageManagerService和其他服务WindowManagerService、InputManagerService即可;
2、SystemServer进程启动流程
2.1、Zygote进程调用
2.1.1、启动参数
在Init进程启动时,分析init.rc文件时,拿到干系启动参数,此中参数中包罗“--start-system-server”,表现启动时要启动SystemServer进程,终极Zygote进程拿到干系参数,以是startSystemServer值为true;
2.1.2、Zygote进程fork
在Zygote进程启动后,实行ZygoteInit类的main()方法,通过fork的方式启动SystemServer;
启动完SystemServer之后会返回一个Runnable对象,在父进程Zygote中该Runnable对象为null,子进程SystemServer中不为null,会在SystemServer进程中实行该Runnable对象;
public static void main(String argv[]) { ZygoteServer zygoteServer = new ZygoteServer(); ... boolean startSystemServer = false; for (int i = 1; i < argv.length; i++) { if ("start-system-server".equals(argv)) { startSystemServer = true; }... } ... zygoteServer.registerServerSocketFromEnv(socketName); ... if (startSystemServer) { Runnable r = forkSystemServer(abiList, socketName, zygoteServer); // {@code r == null} in the parent (zygote) process, and {@code r != null} in the // child (system_server) process. if (r != null) { r.run(); return; } } ...}在forkSystemServer()方法中,通过硬编码的方法写入启动参数数组,调用ZygoteConnection.Arguments类去分析该参数数组,末了调用Zygote类的forkSystemServer()方法去哀求fork SystemServer进程;
如果fork乐成,在父进程中会返回子进程的pid,子进程中会返回pid=0,而且子进程会继承从该处实行,判定pid大于0,如果有两个Zygote进程,则须要等候另一个也完成,然后子进程扫除调从父进程fork过来的socket信息,继承实行handleSystemServerProcess()方法;
private static Runnable forkSystemServer(String abiList, String socketName, ZygoteServer zygoteServer) { ... String args[] = { "--setuid=1000", "--setgid=1000", "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1024,1032,1065,3001,3002,3003,3006,3007,3009,3010", "--capabilities=" + capabilities + "," + capabilities, "--nice-name=system_server", "--runtime-args", "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT, "com.android.server.SystemServer", }; ZygoteConnection.Arguments parsedArgs = null; int pid; try { parsedArgs = new ZygoteConnection.Arguments(args); ... /* Request to fork the system server process */ pid = Zygote.forkSystemServer( parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.runtimeFlags, null, parsedArgs.permittedCapabilities, parsedArgs.effectiveCapabilities); } catch (IllegalArgumentException ex) { throw new RuntimeException(ex); } /* For child process */ if (pid == 0) { if (hasSecondZygote(abiList)) { waitForSecondaryZygote(socketName); } zygoteServer.closeServerSocket(); return handleSystemServerProcess(parsedArgs); } return null;}在Zygote的forkSystemServer()方法中,会先重置线程优先级,然后调用native方法去实行fork;
public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags, int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) { VM_HOOKS.preFork(); // Resets nice priority for zygote process. resetNicePriority(); int pid = nativeForkSystemServer(uid, gid, gids, runtimeFlags, rlimits, permittedCapabilities, effectiveCapabilities); ... VM_HOOKS.postForkCommon(); return pid;}native private static int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags, int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);2.1.3、进入Native层方法
Zygote类对应的native方法在AndroidRuntime.cpp中注册的,调用com_android_internal_os_Zygote.cpp中的register_com_android_internal_os_Zygote()方法创建native方法的映射关系;
在native方法中又调用ForkAndSpecializeCommon()方法,创建完成后Zygote进程会去检查SystemServer是否已经启动,如果system_server创建失败后,会重启zygote进程,Zygote进程和SystemServer进程是Android体系的两个紧张的进程,二者缺一不可,否则就无法正常运行;
static jint com_android_internal_os_Zygote_nativeForkSystemServer( JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jlong permittedCapabilities, jlong effectiveCapabilities) { pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits, permittedCapabilities, effectiveCapabilities, MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL, NULL, false, NULL, NULL); ... if (pid > 0) { int status; if (waitpid(pid, &status, WNOHANG) == pid) { ALOGE("System server process %d has died. Restarting Zygote!", pid); RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!"); } } return pid;}2.1.4、fork进程
在ForkAndSpecializeCommon()方法中,调用fork()函数去从父进程Zygote中fork出子进程,即SystemServer进程,然后根据进程pid去判定,做一些初始化工作;
在进程fork的时间,利用体系会复制一个与父进程完全雷同的子进程,共享代码空间,但是数据空间是相互独立的,子进程数据空间中的内容是父进程的完备拷贝,指令指针也完全雷同,子进程拥有父进程当前运行到的位置(两进程的步伐计数器pc值雷同,也就是说,子进程是从fork返回处开始实行的),但是两者返回的pid是差异的,如果fork乐成,子进程中会返回pid=0,父进程Zygote中会返回子进程的pid,fork失败父进程中会返回负数;
子进程SystemServer创建乐成之后,会将从父进程拷贝过来的数据做一些初始化利用;
// 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 runtime_flags, jobjectArray javaRlimits, jlong permittedCapabilities, jlong effectiveCapabilities, jint mount_external, jstring java_se_info, jstring java_se_name, bool is_system_server, jintArray fdsToClose, jintArray fdsToIgnore, bool is_child_zygote, jstring instructionSet, jstring dataDir) { SetSignalHandlers(); ... pid_t pid = fork(); if (pid == 0) { // pid = 0 为在子进程中,即SystemServer进程,然后做一系列初始化工作 ... } else if (pid > 0) { // pid > 0 为在父进程中,即Zygote进程 ... } return pid;}2.1.5、Java层获取到效果
此时子进程SystemServer进程fork乐成,顺着调用的API返回到ZygoteInit类的forkSystemServer()方法中,此时在Native层fork进程完成,效果返回到Java层,SystemServer进程从fork之后开始实行,即handleSystemServerProcess();
2.1.6、SystemServer进程干系设置
初始化SystemServer进程名,创建类加载器等,继承调用zygoteInit()方法;
private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) { ... // 设置进程名 if (parsedArgs.niceName != null) { Process.setArgV0(parsedArgs.niceName); } ... if (parsedArgs.invokeWith != null) { ... } else { ClassLoader cl = null; if (systemServerClasspath != null) { cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion); Thread.currentThread().setContextClassLoader(cl); } /* * Pass the remaining arguments to SystemServer. */ return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl); }}在该方法中做一些初始化利用,如日记定向,通用初始化即Zygote的初始化,末了调用applicationInit()方法;
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) { ... // 日记干系 RuntimeInit.redirectLogStreams(); RuntimeInit.commonInit(); ZygoteInit.nativeZygoteInit(); return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);}RunTimeInit类中的commonInit()方法紧张初始化一些通用设置,如日记、时区、Http User-agent、socket的tag等;protected static final void commonInit() { ... // 设置时区 TimezoneGetter.setInstance(new TimezoneGetter() { @Override public String getId() { return SystemProperties.get("persist.sys.timezone"); } }); TimeZone.setDefault(null); ... // 设置默认的HTTP User-agent格式 String userAgent = getDefaultUserAgent(); System.setProperty("http.agent", userAgent); ...}在applicationInit()方法中初始化步伐退出时的设置,设置假造机内存使用率参数,sdk版本等,随后继承调用findStaticMain()方法;
protected static Runnable applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) { // 步伐退出时干系设置 nativeSetExitWithoutCleanup(true); // 设置假造机的内存使用率参数值为0.75 VMRuntime.getRuntime().setTargetHeapUtilization(0.75f); VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion); ... return findStaticMain(args.startClass, args.startArgs, classLoader);}2.1.7、进入SystemServer进程main方法
在findStaticMain()方法中通过反射找到SystemServer类的main()方法,将其作为参数新建MethodAndArgsCaller对象,MethodAndArgsCaller是一个Runnable对象,其run方法里是调用该传入的方法,即实行SystemServer类的main()方法;
protected static Runnable findStaticMain(String className, String[] argv, ClassLoader classLoader) { Class<?> cl; try { cl = Class.forName(className, true, classLoader); } 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 }); } catch (NoSuchMethodException ex) { throw new RuntimeException("Missing static main on " + className, ex); } catch (SecurityException ex) { throw new RuntimeException( "roblem getting static main on " + className, ex); } ... return new MethodAndArgsCaller(m, argv);}2.2、SystemServer进程工作
SystemServer的run()方法中,做了大量的初始化利用,如设置体系时间、设置假造机干系设置参数、binder调用干系、创建主线程Looper并循环等候消息、并创建SystemServerManager等;
public final class SystemServer { public static void main(String[] args) { new SystemServer().run(); } private void run() { try { VMRuntime.getRuntime().clearGrowthLimit(); VMRuntime.getRuntime().setTargetHeapUtilization(0.8f); Build.ensureFingerprintProperty(); Environment.setUserRequired(true); BinderInternal.disableBackgroundScheduling(true); 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"); ... // Initialize the system context. createSystemContext(); mSystemServiceManager = new SystemServiceManager(mSystemContext); } finally { ... } // Start services. try { traceBeginAndSlog("StartServices"); startBootstrapServices(); startCoreServices(); startOtherServices(); SystemServerInitThreadPool.shutdown(); } catch (Throwable ex) { ... } ... // Loop forever. Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }}此时SystemServer进入自身的Looper循环中,等候消息处理处罚,SystemServer进程正式运行起来了;
2.2.1、初始化设置
SystemServer启动之后,会实行一系列初始化利用,如判定体系时间是否早于1970年,设置体系时间、假造机内存设置、加载指纹信息、Binder调用的优先级、Binder线程池的最大数量、创建主线程Looper、加载android_servers库、初始化体系上下文、创建SystemServerManager等;
2.2.2、创建SystemServerManager
在run()方法中,会先实行createSystemContext()方法创建体系上下文对象,mSystemContext对象是从ActivityThread获取的,调用ActivityThread的systemMain()方法,实行其attach()方法,创建出App的context,及实行Application的onCreate()方法,体系上下文对象是通过ActivityThread的getSystemContext()方法获取,调用ContextImpl类的createSystemContext()方法创建;
private void createSystemContext() { ActivityThread activityThread = ActivityThread.systemMain(); mSystemContext = activityThread.getSystemContext(); mSystemContext.setTheme(DEFAULT_SYSTEM_THEME); final Context systemUiContext = activityThread.getSystemUiContext(); systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);}# ActivityThreadpublic static ActivityThread systemMain() { ... ActivityThread thread = new ActivityThread(); thread.attach(true, 0); return thread;}private void attach(boolean system, long startSeq) { ... if (!system) { ... } else { ... try { ... ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo); mInitialApplication = context.mPackageInfo.makeApplication(true, null); mInitialApplication.onCreate(); } catch (Exception e) { throw new RuntimeException("Unable to instantiate Application():" + e.toString(), e); } } ...}public ContextImpl getSystemContext() { synchronized (this) { if (mSystemContext == null) { mSystemContext = ContextImpl.createSystemContext(this); } return mSystemContext; }}拿到上下文对象,去创建SystemServerManager对象;
mSystemServiceManager = new SystemServiceManager(mSystemContext);// SystemServiceManagerpublic class SystemServiceManager { SystemServiceManager(Context context) { mContext = context; }}2.2.3、启动引导服务
SystemServer调用startBootstrapServices()方法去启动一系列的引导服务,如ActivityManagerService、PackageManagerService等;
private void startBootstrapServices() { ... // 启动AMS mActivityManagerService = mSystemServiceManager.startService(ActivityManagerService.Lifecycle.class).getService(); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); ... // 启动PMS mPackageManagerService = PackageManagerService.main(mSystemContext, installer, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore); mFirstBoot = mPackageManagerService.isFirstBoot(); mPackageManager = mSystemContext.getPackageManager(); ...}2.2.4、启动核心折务
启动核心折务,如电量管理服务、WebViewUpdateService等;
private void startCoreServices() { ... mSystemServiceManager.startService(BatteryService.class); ... if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) { traceBeginAndSlog("StartWebViewUpdateService"); mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class); traceEnd(); } ...}2.2.5、启动其他服务
调用startOtherServices()方法创建其他服务,如NetworkManagementService、WindowManagerService、InputManagerService等;
而且在该方法中会实行ActivityManagerService的systemReady()方法,通过调用该方法会启动Launcher进程,即桌面App,桌面自己就是一个App进程;
private void startOtherServices() { ... try { networkManagement = NetworkManagementService.create(context); ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement); } ... // WMS wm = WindowManagerService.main(context, inputManager, mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL, !mFirstBoot, mOnlyCore, new PhoneWindowManager()); ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO); ...}2.2.6、Looper循环消息
创建了主线程Looper,并实行loop()函数开启消息轮训等候消息到来;
来自:https://www.yuque.com/jesus_yangshijie/ruafsa/gib2tf
|