Android中system server进程启动流程源码解析 系统服务启动

版权声明:本文为博主原创文章,转载请标明出处 https://blog.csdn.net/qq_30993595/article/details/83856471

前言

在平时的开发中或多或少会了解过ActivityManagerService,WindowManagerService,PowerManagerService等服务,那你有想过这些服务如何产生的吗,它们运行在哪呢?我们是如何获取到这些服务的呢?要想了解这些就要看System Server进程了

本篇博客源码基于API24

System Server

System Server进程和Zygote进程可以说是Android世界中的两大最重要的进程,离开其中之一基本上系统就玩完了(这里还有一个Media Server进程,是由init进程fork而来,负责启动和管理整个C++ framework,包含AudioFlinger,Camera Service等服务);System Server负责启动和管理整个framework,基本上在Framework中的大多数服务都是在system server进程中以一个线程的方式存在的;System Server进程的进程名是system_server,大家可以通过adb shell ps查看当前手机存在的进程信息,可以看到这几条

USER     PID   PPID   VSIZE    RSS     WCHAN    PC         NAME
root      1     0     9048     1012    ffffffff 00000000 S /init

root      349   1     2118552  17464   ffffffff 00000000 S zygote64
root      350   1     1526172  16800   ffffffff 00000000 S zygote

system    793   349   2792784  109876  ffffffff 00000000 S system_server

fork SystemServer

System Server进程是由Zygote进程fork出来的,至于如何被Zygote进程fork出来的以及Zygote进程的信息可以参考下面博客
Android系统启动流程概述 init进程启动 zygote进程启动 system server进程启动

zygote进程fork成功后,会反射调用SystemServer.main()方法,至此进入system server进程的工作空间

SystemServer.main()

public static void main(String[] args) {
        new SystemServer().run();
}

private void run() {
        try {
           	//若当前时间小于1970年1月1日,那就设置为1970年1月1日
            if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
                SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
            }
            //设置系统的语言环境
			if (!SystemProperties.get("persist.sys.language").isEmpty()) {
                final String languageTag = Locale.getDefault().toLanguageTag();
                SystemProperties.set("persist.sys.locale", languageTag);
                SystemProperties.set("persist.sys.language", "");
                SystemProperties.set("persist.sys.country", "");
                SystemProperties.set("persist.sys.localevar", "");
            }
            
            //变更虚拟机的库文件,对于Android 6.0默认采用的是libart.so
            SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());

            //清除vm内存增长上限,由于启动过程需要较多的虚拟机内存空间
            VMRuntime.getRuntime().clearGrowthLimit();

            //设置内存的可能有效使用率为0.8
            VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

            // 针对部分设备依赖于运行时就产生指纹信息,因此需要在开机完成前已经定义
            Build.ensureFingerprintProperty();

            //访问环境变量前,需要明确地指定用户
            Environment.setUserRequired(true);

            // Within the system server, any incoming Bundles should be defused
            // to avoid throwing BadParcelableException.
            BaseBundle.setShouldDefuse(true);

            //确保当前系统进程的binder调用,总是运行在前台优先级(foreground priority)
            BinderInternal.disableBackgroundScheduling(true);

            // 增加system_server中的binder线程数
            BinderInternal.setMaxThreads(sMaxBinderThreads);

            // 创建主线程looper 在当前线程运行
            android.os.Process.setThreadPriority(
                android.os.Process.THREAD_PRIORITY_FOREGROUND);
            android.os.Process.setCanSelfBackground(false);
            Looper.prepareMainLooper();

            //初始化android_servers库
            System.loadLibrary("android_servers");

            //检测上次关机过程是否失败
            performPendingShutdown();

            //初始化系统上下文
            //初始化系统上下文对象mSystemContext,并设置默认的主题,mSystemContext实际上是一个ContextImpl对象。
            //调用ActivityThread.systemMain()的时候,会调用ActivityThread.attach(true),而在attach()里面,则创建了Application对象,并调用了Application.onCreate()。
            createSystemContext();

            //创建系统服务管理
            mSystemServiceManager = new SystemServiceManager(mSystemContext);
            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }

        //启动各种系统服务
        try {
	        //引导服务
            startBootstrapServices();
            //核心服务
            startCoreServices();
            //其它服务
            startOtherServices();
        } catch (Throwable ex) {
            throw ex;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }

        //开启消息循环
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

这个main方法做了很多事情:设置系统时间,设置语言环境,设置虚拟机内存,设置binder线程数,初始化Loop,加载运行库等

除了这些操作外,接下来继续往下看main方法后半段


SystemServer.createSystemContext

private Context mSystemContext;

private void createSystemContext() {
        ActivityThread activityThread = ActivityThread.systemMain();
        mSystemContext = activityThread.getSystemContext();
        mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
}

没想到啊,原来System Server中也有Context对象,这个方法就是初始化system context;可能有人不太理解Context到底是个什么玩意

Context英文原意是上下文的意思,在平时开发中涉及到的四大组件及资源操作基本上都离不开Context对象;你可以想象它是一团神秘的漂浮的物质,在一个生活场景中,不管你在哪,在干什么,你都可以通过这团神秘物质获取到一些属于这个场景的隐性信息

比如你在吃一条鱼这个场景,你能知道的就是这条鱼多大,多好吃,但是假如你有Context这个上下文信息,你就能获取到更多信息,比如鱼的重量,鱼的种类,鱼的年龄等,用代码表示就是Context.getFishType(),你就知道这条鱼的种类了

这就是上下文的意思,某一个场景下一些隐藏的信息

其实Context家族很复杂,Context本身是一个抽象类,而ContextImpl,ContextWrapper,Activity,Service,Application等都是它的直接或间接子类

接下来我们看下方法后续调用

public static ActivityThread systemMain() {
        // 低内存设备上的系统进程无法使用硬件加速绘图,因为这会给进程增加太多开销
        if (!ActivityManager.isHighEndGfx()) {
            ThreadedRenderer.disable(true);
        } else {
            ThreadedRenderer.enableForegroundTrimming();
        }
        ActivityThread thread = new ActivityThread();
        thread.attach(true);
        return thread;
}

public ContextImpl getSystemContext() {
        synchronized (this) {
            if (mSystemContext == null) {
                mSystemContext = ContextImpl.createSystemContext(this);
            }
            return mSystemContext;
        }
}

其中 thread.attach(true)这句话经过一系列调用后会创建很多对象,比如ActivityThread,Instrumentation, ContextImpl,LoadedApk,Application等

具体执行过程可查看博主博客

从Activity加载源码深入理解ActivityThrad的工作逻辑

执行完后System Server后续就能用到这些对象了


SystemServiceManager

继续往下看

//创建系统服务管理
mSystemServiceManager = new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

这里是实例化SystemServiceManager对象,这个类主要是用来对System server中的一些系统服务的创建,启动和其它的一些生命周期事件进行管理

SystemServiceManager维护了一个集合

private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();

SystemServer启动的很多服务都保存在这个集合里


启动服务三连

		//启动各种系统服务
        try {
	        //引导服务
            startBootstrapServices();
            //核心服务
            startCoreServices();
            //其它服务
            startOtherServices();
        } catch (Throwable ex) {
            throw ex;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }

main方法最后会执行这三个重要的启动服务方法,先看第一个

SystemServer.startBootstrapServices

这个方法将会启动一些引导服务

	private PowerManagerService mPowerManagerService;
    private ActivityManagerService mActivityManagerService;
    private WebViewUpdateService mWebViewUpdateService;
    private DisplayManagerService mDisplayManagerService;
    private PackageManagerService mPackageManagerService;
    private PackageManager mPackageManager;
		
	/**
     * 启动一些系统运行必须的关键服务,这些服务具有复杂的相互依赖性,所以就在这里全部初始化
     */
    private void startBootstrapServices() {
        // 阻塞等待installd完成启动,与其建立socket通道
        // 以便它有机会使用适当的权限创建关键目录,例如/ data / user
        // 在初始化其他服务之前,我们需要完成此操作
        Installer installer = mSystemServiceManager.startService(Installer.class);

        // 启动ActivityManagerService
        mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);

        // PowerManagerService需要尽早启动,因为其他服务需要它。 本机守护程序可能正在监视它是否已注册
        // 因为它要立即准备好处理传入进来的binder调用(包括能够验证这些调用的权限)
        mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

        // 现在电源管理器已经启动,让ActivityManagerService初始化电源管理功能
        mActivityManagerService.initPowerManagement();

        // 启动服务LightsService 管理LED并显示背光
        mSystemServiceManager.startService(LightsService.class);

        // 启动服务DisplayManagerService
        mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

        // 在初始化package manager之前,需要默认的显示
        mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

        // 如果我们正在加密设备,则只运行“核心”应用程序.
        String cryptState = SystemProperties.get("vold.decrypt");
        if (ENCRYPTING_STATE.equals(cryptState)) {
            //加密程序正在运行
            mOnlyCore = true;
        } else if (ENCRYPTED_STATE.equals(cryptState)) {
            //已经被加密了
            mOnlyCore = true;
        }

        // 启动PackageManagerService
        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
        mFirstBoot = mPackageManagerService.isFirstBoot();
        mPackageManager = mSystemContext.getPackageManager();

        // 没有加密的话进行odex优化
        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);
                }
            }
        }

        //启动服务UserManagerService,新建目录/data/user/
        mSystemServiceManager.startService(UserManagerService.LifeCycle.class);

        //初始化属性缓存用来缓存包资源.
        AttributeCache.init(mSystemContext);

        // 为系统进程设置Application实例并开始使用
        mActivityManagerService.setSystemProcess();

        // 启动传感器服务
        // 传感器服务需要访问包管理器服务,app ops服务和权限服务,因此我们在它们之后启动它
        startSensorService();
    }
    
    //这是native方法
    private static native void startSensorService();

可以看到这里启动了很多系统关键性服务,而且都是通过SystemServiceManager实例去操作

SystemServiceManager.startService

/**
     * 创建并启动 system service. 且这些服务必须是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();

            // 创建 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);
            } 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);
            }

            // 添加到list集合
            mServices.add(service);

            try {
            		//启动
                service.onStart();
            } catch (RuntimeException ex) {
                throw new RuntimeException("Failed to start service " + name
                        + ": onStart threw an exception", ex);
            }
            return service;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }

这里都是通过反射构造出这些服务的实例,然后调用它们的onStart方法启动,以Installer服务为例看一下

Installer.onStart

public final class Installer extends SystemService {

		private final InstallerConnection mInstaller;
		
		public Installer(Context context) {
	        super(context);
	        mInstaller = new InstallerConnection();
    	}
		
		@Override
    	public void onStart() {
        	//等待installd准备完毕
        	mInstaller.waitForConnection();
    	}
    
}
    
public class InstallerConnection {

    public void waitForConnection() {
        for (;;) {
            try {
                execute("ping");
                return;
            } catch (InstallerException ignored) {
            }
            //还没准备好,休息一秒继续尝试
            SystemClock.sleep(1000);
        }
    }
    
}

其实就是不断的通过ping命令连接Zygote进程(SystemServer和Zygote进程通过socket方式通讯,其他进程通过Binder方式通讯),成功连接之后才会开始启动其他服务


SystemServer.startCoreServices

接下来看第二个启动方法

	/**
     * 启动一些与引导服务没有复杂依赖的基本服务
     */
    private void startCoreServices() {
        // 启动BatteryService 跟踪电池电量
        mSystemServiceManager.startService(BatteryService.class);

        // 启动UsageStatsService 跟踪应用程序使用统计信息
        mSystemServiceManager.startService(UsageStatsService.class);
        mActivityManagerService.setUsageStatsManager(
                LocalServices.getService(UsageStatsManagerInternal.class));

        // 启动WebViewUpdateService 跟踪可更新的WebView是否处于就绪状态并监视更新安装。
        mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);   
    }

SystemServer.startOtherServices

这个方法着实有点长,将近一千行,不过做的事情不复杂,主要是启动服务;这里就不一一列举了

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;

		//读取配置信息
        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 isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1");

        try {
            SystemConfig.getInstance();

            ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
            
            mSystemServiceManager.startService(TelecomLoaderService.class);

            telephonyRegistry = new TelephonyRegistry(context);
            ServiceManager.addService("telephony.registry", telephonyRegistry);

			......
						
        } catch (RuntimeException e) {
            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;
				
		......

		ActivityManagerNative.getDefault().showBootMessage(...); //显示启动界面

        
        try {
            vibrator.systemReady();
        } catch (Throwable e) {
            reportWtf("making Vibrator Service ready", e);
        }

        
        mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
        mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);

        try {
            wm.systemReady();
        } catch (Throwable e) {
            reportWtf("making Window Manager Service ready", e);
        }

		......

        
        mActivityManagerService.systemReady(new Runnable() {
            @Override
            public void run() {

                mSystemServiceManager.startBootPhase(
                        SystemService.PHASE_ACTIVITY_MANAGER_READY);
								
				......

                try {
                    startSystemUi(context);
                } catch (Throwable e) {
                    reportWtf("starting System UI", e);
                }


                mSystemServiceManager.startBootPhase(
                        SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);

               ......
            }
        });
    }

这里会启动大量的服务,到这里系统服务基本上启动完成,system_server进程随后进入Looper.loop()状态,随时等待消息到来

总结

  • SystemServer进程启动后会设置系统时间,设置语言环境,设置虚拟机内存,设置binder线程数,初始化Loop,加载运行库等
  • 接下来创建Context对象,SystemServiceManager对象
  • 最后启动三类服务:引导服务,核心服务,其它服务;其中引导服务有7个,核心服务有三个,其他服务有70+
  • 进行消息循环,随时处理接收到的事件

猜你喜欢

转载自blog.csdn.net/qq_30993595/article/details/83856471