美文网首页
Android 10.0 SystemServer进程启动过程

Android 10.0 SystemServer进程启动过程

作者: 竖起大拇指 | 来源:发表于2020-10-12 09:45 被阅读0次

    Zygote是所有应用的鼻祖,SystemServer和其他所有Dalivik虚拟机进程都是由Zygote fork而来。Zygote fork的第一个进程就是SystemServer,其在手机中的进程名为system_server。

    回顾ZygoteInit的startSystemServer

    public static void main(String argv[]) {
        ZygoteServer zygoteServer = null;
        ...
        try {
            zygoteServer = new ZygoteServer(isPrimaryZygote);
            if (startSystemServer) {
                //fork system_server
                Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
     
                // {@code r == null} in the parent (zygote) process, and {@code r != null} in the
                // child (system_server) process.
                if (r != null) {
                    r.run(); //启动SystemServer.java的main()
                    return; //Android 8.0之前是通过抛异常的方式来启动,这里是直接return出去,用来清空栈,提高栈帧利用率
                }
            }
            caller = zygoteServer.runSelectLoop(abiList);
        } catch (Throwable ex) {
            Log.e(TAG, "System zygote died with exception", ex);
            throw ex;
        } finally {
            if (zygoteServer != null) {
                zygoteServer.closeServerSocket();
            }
        }
        if (caller != null) {
            caller.run();
        }
    }
    

    ZygoteInit#forkSystemServer

    private static Runnable forkSystemServer(String abiList, String socketName,
            ZygoteServer zygoteServer) {
        ......
        //参数准备,uid和gid都是为1000
        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",
        };
        ZygoteArguments parsedArgs = null;
        int pid;
        try {
            //将上面准备的参数,按照ZygoteArguments的风格进行封装
            parsedArgs = new ZygoteArguments(args);
            Zygote.applyDebuggerSystemProperty(parsedArgs);
            Zygote.applyInvokeWithSystemProperty(parsedArgs);
     
            //通过fork"分裂"出子进程system_server
            /* Request to fork the system server process */
            pid = Zygote.forkSystemServer(
                    parsedArgs.mUid, parsedArgs.mGid,
                    parsedArgs.mGids,
                    parsedArgs.mRuntimeFlags,
                    null,
                    parsedArgs.mPermittedCapabilities,
                    parsedArgs.mEffectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }
     
        //进入子进程system_server
        if (pid == 0) {
            // 处理32_64和64_32的情况
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);  //需要等待第二个Zygote创建完成
            }
     
            // fork时会copy socket,Zygote原有的socket需要关闭
            zygoteServer.closeServerSocket();
            // system server进程处理自己的工作
            return handleSystemServerProcess(parsedArgs);
        }
        return null;
    }
    

    ZygoteInit#handleSystemServerProcess

    private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
     
        if (parsedArgs.mNiceName != null) {
            Process.setArgV0(parsedArgs.mNiceName); //设置当前进程名为"system_server"
        }
     
        final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
        if (systemServerClasspath != null) {
           //执行dex优化操作
            if (performSystemServerDexOpt(systemServerClasspath)) {
                sCachedSystemServerClassLoader = null;
            }
            ...
        }
     
        if (parsedArgs.mInvokeWith != null) {
            String[] args = parsedArgs.mRemainingArgs;
            //如果我们有一个非空系统服务器类路径,我们将不得不复制现有的参数并将类路径附加到它。
            //当我们执行一个新进程时,ART将正确地处理类路径。
            if (systemServerClasspath != null) {
                String[] amendedArgs = new String[args.length + 2];
                amendedArgs[0] = "-cp";
                amendedArgs[1] = systemServerClasspath;
                System.arraycopy(args, 0, amendedArgs, 2, args.length);
                args = amendedArgs;
            }
     
            //启动应用进程
            WrapperInit.execApplication(parsedArgs.mInvokeWith,
                    parsedArgs.mNiceName, parsedArgs.mTargetSdkVersion,
                    VMRuntime.getCurrentInstructionSet(), null, args);
     
            throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
        } else {
            // 创建类加载器,并赋予当前线程
            createSystemServerClassLoader();
            ClassLoader cl = sCachedSystemServerClassLoader;
            if (cl != null) {
                Thread.currentThread().setContextClassLoader(cl);
            }
     
            //system_server进入此分支
            return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
                    parsedArgs.mRemainingArgs, cl);
        }
    }
    

    ZygoteInit.java#zygoteInit

     public static final Runnable zygoteInit(int targetSdkVersion, String[] argv,
                ClassLoader classLoader) {
            if (RuntimeInit.DEBUG) {
                Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
            }
    
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
            RuntimeInit.redirectLogStreams(); //重定向log输出
    
            RuntimeInit.commonInit();//通用的一些初始化
            ZygoteInit.nativeZygoteInit();//zygote初始化
            //应用初始化
            return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
        }
    

    RuntimeInit.java#commonInit

    配置log,时区,http userAgent等基础信息

    protected static final void commonInit() {
        LoggingHandler loggingHandler = new LoggingHandler();
        
        // 设置默认的未捕捉异常处理方法
        RuntimeHooks.setUncaughtExceptionPreHandler(loggingHandler);
        Thread.setDefaultUncaughtExceptionHandler(new KillApplicationHandler(loggingHandler));
     
        // 设置时区,通过属性读出中国时区为"Asia/Shanghai"
        RuntimeHooks.setTimeZoneIdSupplier(() -> SystemProperties.get("persist.sys.timezone"));
     
        //重置log配置
        LogManager.getLogManager().reset();
        new AndroidConfig();
     
        //设置默认的HTTP User-agent格式,用于 HttpURLConnection
        String userAgent = getDefaultUserAgent();
        System.setProperty("http.agent", userAgent);
     
        /*
         * Wire socket tagging to traffic stats.
         */
        //设置socket的tag,用于网络流量统计
        NetworkManagementSocketTagger.install();
        ...
    }
    

    RuntimeInit.java#applicaitonInit

    protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
                ClassLoader classLoader) {
            // 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.
          //true代表应用程序退出时不调用AppRuntime.onExit(),否则会在退出前调用
            nativeSetExitWithoutCleanup(true);
    
            // We want to be fairly aggressive about heap utilization, to avoid
            // holding on to a lot of memory that isn't needed.
            //设置虚拟机的内存利用率参数值为0.75
            VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
            VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
            //解析参数
            final Arguments args = new Arguments(argv);
    
            // 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
            //找到systemServer 的main方法
            return findStaticMain(args.startClass, args.startArgs, classLoader);
        }
    
    

    RuntimeInit.java#findStaticMain()

      protected static Runnable findStaticMain(String className, String[] argv,
                ClassLoader classLoader) {
            Class<?> cl;
    
            try {
                //拿到com.android.server.SystemServer 的类对象
                cl = Class.forName(className, true, classLoader);
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(
                        "Missing class when invoking static main " + className,
                        ex);
            }
    
            Method m;
            try {
                //得到SystemServer的main()方法
                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(
                        "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.
             */
            //把MethodAndArgsCaller的对象返回给ZygoteInit.main()
            //这样做的好处是能清空栈,提高栈帧利用率。清除了设置进程所需的多有堆栈帧
            return new MethodAndArgsCaller(m, argv);
        }
    
    
    static class MethodAndArgsCaller 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 {
                      //根据传递进来的参数,可知此处通过反射机制调用的是
                      SystemServer.main()方法
                    mMethod.invoke(null, new Object[] { mArgs });
                } 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);
                }
            }
        }
    

    SystemServer.java#main

    main函数由Zygote进程fork后运行,作用是new 一个SystemServer对象,在调用该对象的run()方法

      /* The main entry point from zygote.
         */
        public static void main(String[] args) {
            new SystemServer().run();
        }
    

    SystemServer.java#run

    先初始化一些系统变量,加载类库,启动引导服务,核心服务,和其他服务。

    private void run() {
        try {
            traceBeginAndSlog("InitBeforeStartServices");
     
            // Record the process start information in sys props.
            //从属性中读取system_server进程的一些信息
            SystemProperties.set(SYSPROP_START_COUNT, String.valueOf(mStartCount));
            SystemProperties.set(SYSPROP_START_ELAPSED, String.valueOf(mRuntimeStartElapsedTime));
            SystemProperties.set(SYSPROP_START_UPTIME, String.valueOf(mRuntimeStartUptime));
     
            EventLog.writeEvent(EventLogTags.SYSTEM_SERVER_START,
                    mStartCount, mRuntimeStartUptime, mRuntimeStartElapsedTime);
     
     
            //如果一个设备的时钟是在1970年之前(0年之前),
            //那么很多api 都会因为处理负数而崩溃,尤其是java.io.File#setLastModified
            //我把把时间设置为1970
            if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
                Slog.w(TAG, "System clock is before 1970; setting to 1970.");
                SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
            }
     
            //如果时区不存在,设置时区为GMT
            String timezoneProperty = SystemProperties.get("persist.sys.timezone");
            if (timezoneProperty == null || timezoneProperty.isEmpty()) {
                Slog.w(TAG, "Timezone not set; setting to GMT.");
                SystemProperties.set("persist.sys.timezone", "GMT");
            }
     
            //变更虚拟机的库文件,对于Android 10.0默认采用的是libart.so
            SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
     
            // Mmmmmm... more memory!
            //清除vm内存增长上限,由于启动过程需要较多的虚拟机内存空间
            VMRuntime.getRuntime().clearGrowthLimit();
            ...
            //系统服务器必须一直运行,所以它需要尽可能高效地使用内存
            //设置内存的可能有效使用率为0.8
            VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
     
     
            //一些设备依赖于运行时指纹生成,所以在进一步启动之前,请确保我们已经定义了它。
            Build.ensureFingerprintProperty();
     
            //访问环境变量前,需要明确地指定用户
            //在system_server中,任何传入的包都应该被解除,以避免抛出BadParcelableException。
            BaseBundle.setShouldDefuse(true);
     
            //在system_server中,当打包异常时,信息需要包含堆栈跟踪
            Parcel.setStackTraceParceling(true);
     
            //确保当前系统进程的binder调用,总是运行在前台优先级(foreground priority)
            BinderInternal.disableBackgroundScheduling(true);
     
            //设置system_server中binder线程的最大数量,最大值为31
            BinderInternal.setMaxThreads(sMaxBinderThreads);
     
            //准备主线程lopper,即在当前线程运行
            android.os.Process.setThreadPriority(
                    android.os.Process.THREAD_PRIORITY_FOREGROUND);
            android.os.Process.setCanSelfBackground(false);
            Looper.prepareMainLooper();
            Looper.getMainLooper().setSlowLogThresholdMs(
                    SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
     
            //加载android_servers.so库,初始化native service
            System.loadLibrary("android_servers");
     
            // Debug builds - allow heap profiling.
            //如果是Debug版本,允许堆内存分析
            if (Build.IS_DEBUGGABLE) {
                initZygoteChildHeapProfiling();
            }
     
            //检测上次关机过程是否失败,这个调用可能不会返回
            performPendingShutdown();
     
            //初始化系统上下文
            createSystemContext();
     
            //创建系统服务管理--SystemServiceManager
            mSystemServiceManager = new SystemServiceManager(mSystemContext);
            mSystemServiceManager.setStartInfo(mRuntimeRestart,
                    mRuntimeStartElapsedTime, mRuntimeStartUptime);
            //将mSystemServiceManager添加到本地服务的成员sLocalServiceObjects
            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
            // Prepare the thread pool for init tasks that can be parallelized
            //为可以并行化的init任务准备线程池
            SystemServerInitThreadPool.get();
        } finally {
            traceEnd();  // InitBeforeStartServices
        }
     
        // Start services.
        //启动服务
        try {
            traceBeginAndSlog("StartServices");
            startBootstrapServices();   // 启动引导服务
            startCoreServices();        // 启动核心服务
            startOtherServices();       // 启动其他服务
            SystemServerInitThreadPool.shutdown(); //停止线程池
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {
            traceEnd();
        }
     
        //为当前的虚拟机初始化VmPolicy
        StrictMode.initVmDefaults(null);
        ...
        // Loop forever.
        //死循环执行
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
    

    SystemServer.java#createSystemContext

    初始化系统上下文,该过程会创建对象有ActivityThread,Instrumentation,ContextImpl,LoadedAPk,Applicaiton

    private void createSystemContext() {
        //创建system_server进程的上下文信息
        ActivityThread activityThread = ActivityThread.systemMain();
        mSystemContext = activityThread.getSystemContext();
        //设置主题
        mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
     
        //获取systemui上下文信息,并设置主题
        final Context systemUiContext = activityThread.getSystemUiContext();
        systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
    }
    

    SystemServer.java#startBootstrapServices

    用来启动系统Boot级服务,有ActivityManager,PowerManagerService,LightsService,DisplayManagerService,PackageManagerService等

    private void startBootstrapServices() {
        traceBeginAndSlog("StartWatchdog");
        //启动watchdog
        //尽早启动watchdog,如果在早起启动时发生死锁,我们可以让system_server
        //崩溃,从而进行详细分析
        final Watchdog watchdog = Watchdog.getInstance();
        watchdog.start();
        traceEnd();
     
    ...
        //添加PLATFORM_COMPAT_SERVICE,Platform compat服务被ActivityManagerService、PackageManagerService
        //以及将来可能出现的其他服务使用。
        traceBeginAndSlog("PlatformCompat");
        ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE,
                new PlatformCompat(mSystemContext));
        traceEnd();
     
        //阻塞等待installd完成启动,以便有机会创建具有适当权限的关键目录,如/data/user。
        //我们需要在初始化其他服务之前完成此任务。
        traceBeginAndSlog("StartInstaller");
        Installer installer = mSystemServiceManager.startService(Installer.class);
        traceEnd();
    ...
        //启动服务ActivityManagerService,并为其设置mSystemServiceManager和installer
        traceBeginAndSlog("StartActivityManager");
        ActivityTaskManagerService atm = mSystemServiceManager.startService(
                ActivityTaskManagerService.Lifecycle.class).getService();
        mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);
        mWindowManagerGlobalLock = atm.getGlobalLock();
        traceEnd();
     
        //启动服务PowerManagerService
        //Power manager需要尽早启动,因为其他服务需要它。
        //本机守护进程可能正在监视它的注册,
        //因此它必须准备好立即处理传入的绑定器调用(包括能够验证这些调用的权限)
    。
        traceBeginAndSlog("StartPowerManager");
        mPowerManagerService = mSystemServiceManager.startService(
    PowerManagerService.class);
        traceEnd();
     
    ...
        //初始化power management
        traceBeginAndSlog("InitPowerManagement");
        mActivityManagerService.initPowerManagement();
        traceEnd();
     
        //启动recovery system,以防需要重新启动
        traceBeginAndSlog("StartRecoverySystemService");
        mSystemServiceManager.startService(RecoverySystemService.class);
        traceEnd();
    ...
        //启动服务LightsService
        //管理led和显示背光,所以我们需要它来打开显示
        traceBeginAndSlog("StartLightsService");
        mSystemServiceManager.startService(LightsService.class);
        traceEnd();
    ...
        //启动服务DisplayManagerService
        //显示管理器需要在包管理器之前提供显示指标
        traceBeginAndSlog("StartDisplayManager");
        mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
        traceEnd();
     
        // Boot Phases: Phase100: 在初始化package manager之前,需要默认的显示.
        traceBeginAndSlog("WaitForDisplay");
        mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
        traceEnd();
     
        //当设备正在加密时,仅运行核心
        String cryptState = VoldProperties.decrypt().orElse("");
        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;
        }
    ...
        //启动服务PackageManagerService
        traceBeginAndSlog("StartPackageManagerService");
        try {
            Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
            mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                    mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
        } finally {
            Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
        }
    ...
        //启动服务UserManagerService,新建目录/data/user/
        traceBeginAndSlog("StartUserManagerService");
        mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
        traceEnd();
     
        // Set up the Application instance for the system process and get  started.
        //为系统进程设置应用程序实例并开始。
        //设置AMS
        traceBeginAndSlog("SetSystemProcess");
        mActivityManagerService.setSystemProcess();
        traceEnd();
     
        //使用一个ActivityManager实例完成watchdog设置并监听重启,
    //只有在ActivityManagerService作为一个系统进程正确启动后才能这样做
        traceBeginAndSlog("InitWatchdog");
        watchdog.init(mSystemContext, mActivityManagerService);
        traceEnd();
     
         //传感器服务需要访问包管理器服务、app ops服务和权限服务,
        //因此我们在它们之后启动它。
        //在单独的线程中启动传感器服务。在使用它之前应该检查完成情况。
        mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
            TimingsTraceLog traceLog = new TimingsTraceLog(
                    SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.
    TRACE_TAG_SYSTEM_SERVER);
            traceLog.traceBegin(START_SENSOR_SERVICE);
            startSensorService(); //启动传感器服务
            traceLog.traceEnd();
        }, START_SENSOR_SERVICE);
    }
     
    

    SystemServerManager.java$statService()

     /**
         * Creates and starts a system service. The class must be a subclass of
         * {@link com.android.server.SystemService}.
         *
         * @param serviceClass A Java class that implements the SystemService interface.
         * @return The service instance, never null.
         * @throws RuntimeException if the service fails to start.
         */
        @SuppressWarnings("unchecked")
        public <T extends SystemService> T startService(Class<T> serviceClass) {
            try {
                final String name = serviceClass.getName();
                Slog.i(TAG, "Starting " + name);
                Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);
    
                // Create the service.
                if (!SystemService.class.isAssignableFrom(serviceClass)) {
                    throw new RuntimeException("Failed to create " + name
                            + ": service must extend " + SystemService.class.getName());
                }
                final T service;
                try {
                    Constructor<T> constructor = serviceClass.getConstructor(Context.class);
                    service = constructor.newInstance(mContext);  //1
                } catch (InstantiationException ex) {
                    throw new RuntimeException("Failed to create service " + name
                            + ": service could not be instantiated", ex);
                } catch (IllegalAccessException ex) {
                    throw new RuntimeException("Failed to create service " + name
                            + ": service must have a public constructor with a Context argument", ex);
                } catch (NoSuchMethodException ex) {
                    throw new RuntimeException("Failed to create service " + name
                            + ": service must have a public constructor with a Context argument", ex);
                } catch (InvocationTargetException ex) {
                    throw new RuntimeException("Failed to create service " + name
                            + ": service constructor threw an exception", ex);
                }
    
                startService(service);
                return service;
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
            }
        }
    
        public void startService(@NonNull final SystemService service) {
            // Register it.
            mServices.add(service);  //2
            // Start it.
            long time = SystemClock.elapsedRealtime();
            try {
                service.onStart();   //3
            } catch (RuntimeException ex) {
                throw new RuntimeException("Failed to start service " + service.getClass().getName()
                        + ": onStart threw an exception", ex);
            }
            warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
        }
    
    

    通过反射创建SystemService,然后将服务添加到mServices中,这里mServices是一个存储SystemService类型的ArrayList。然后调用服务的onStart函数启动并返回。
    我们看看PackageManagerService,它是通过另外一种方式启动的,直接调用了PackageManagerService的main函数:

    public static PackageManagerService main(Context context, Installer installer,
                boolean factoryTest, boolean onlyCore) {
            // Self-check for initial settings.
            PackageManagerServiceCompilerMapping.checkProperties();
    
            PackageManagerService m = new PackageManagerService(context, installer,
                    factoryTest, onlyCore);
            m.enableSystemUserPackages();
            ServiceManager.addService("package", m);
            final PackageManagerNative pmn = m.new PackageManagerNative();
            ServiceManager.addService("package_native", pmn);
            return m;
        }
    

    创建PackageMangerService实例,然后注册到ServiceManager中。ServiceManager用来管理系统中的各种Service,用系统C/S架构中的Binder机制通信,Client端要使用某个Service,则需要先到ServiceManager查询Service的相关信息,然后根据Service的相关信息与Service所在的进程建立通讯通路,这样Client端就可以使用Service了。

    SystemServer.java#startCoreServices

    启动核心服务BatteryService,WebViewUpdateService等

    private void startCoreServices() {
        //启动服务BatteryService,用于统计电池电量,需要LightService.
        mSystemServiceManager.startService(BatteryService.class);
     
        //启动服务UsageStatsService,用于统计应用使用情况
        mSystemServiceManager.startService(UsageStatsService.class);
        mActivityManagerService.setUsageStatsManager(
                LocalServices.getService(UsageStatsManagerInternal.class));
     
        //启动服务WebViewUpdateService
        //跟踪可更新的WebView是否处于就绪状态,并监视更新安装
        if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
            mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
        }
     
        //启动CachedDeviceStateService,跟踪和缓存设备状态
        mSystemServiceManager.startService(CachedDeviceStateService.class);
     
        //启动BinderCallsStatsService, 跟踪在绑定器调用中花费的cpu时间
        traceBeginAndSlog("StartBinderCallsStatsService");
        mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);
        traceEnd();
     
        //启动LooperStatsService,跟踪处理程序中处理消息所花费的时间。
        traceBeginAndSlog("StartLooperStatsService");
        mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);
        traceEnd();
     
        //启动RollbackManagerService,管理apk回滚
        mSystemServiceManager.startService(RollbackManagerService.class);
     
        //启动BugreportManagerService,捕获bugreports的服务
        mSystemServiceManager.startService(BugreportManagerService.class);
     
        //启动GpuService,为GPU和GPU驱动程序提供服务。
        mSystemServiceManager.startService(GpuService.class);
    }
     
    

    SystemServer.java#startOtherServices

    这里面启动的服务太多,大体流程如下

    private void startOtherServices() {
        ...
        //启动TelecomLoaderService,通话相关核心服务
        mSystemServiceManager.startService(TelecomLoaderService.class);
     
        //启动TelephonyRegistry
        telephonyRegistry = new TelephonyRegistry(context);
        ServiceManager.addService("telephony.registry", telephonyRegistry);
        ...
        //启动AlarmManagerService,时钟管理
        mSystemServiceManager.startService(new AlarmManagerService(context));
        ...
        //启动InputManagerService
        inputManager = new InputManagerService(context);
        ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
                /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
        ...
        inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback());
        inputManager.start();
        ...
        //Phase480:在接收到此启动阶段后,服务可以获得锁设置数据
        mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
     
        //Phase500:在接收到这个启动阶段之后,服务可以安全地调用核心系统服务,
        //如PowerManager或PackageManager。
        mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
        
        mActivityManagerService.systemReady(() -> {
            //Phase550:在接收到此引导阶段后,服务可以广播意图。
            mSystemServiceManager.startBootPhase(
                    SystemService.PHASE_ACTIVITY_MANAGER_READY);
     
            //Phase600:在接收到这个启动阶段后,服务可以启动/绑定到第三方应用程序。
            //此时,应用程序将能够对服务进行绑定调用。
            mSystemServiceManager.startBootPhase(
            SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
        }
    }
    

    总结

    • Zygote启动后fork的第一个进程为SystemServer,在手机中的进程别名为"system_server",主要用来启动系统中的服务
    • Zygote fork后,进入SystemServer的main()
    • SystemServer在启动过程中,先初始化一些系统变量,加载类库,创建Context对象,创建SystemServiceManager对象等候再启动服务
    • 启动的服务分为 引导服务(Boot Service)、核心服务(Core Service)和其他服务(Other Service)三大类,共90多个服务
    • SystemServer在启动服务前,会尝试与Zygote建立Socket通信,通信成功后才去启动服务
    • 启动的服务都单独运行在SystemServer的各自线程中,同属于SystemServer进程

    相关文章

      网友评论

          本文标题:Android 10.0 SystemServer进程启动过程

          本文链接:https://www.haomeiwen.com/subject/fzfjpktx.html