AndroidT(13) AMS启动流程

上一篇文章中,我们分析了Zygote的启动流程,不知道大家有没有注意到在zygote.main函数中有这样一段代码
有兴趣的小伙伴可以看一下Zygote的启动流程

 if (startSystemServer) {
                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();
                    return;
                }
            }

在这里,会开始创建SystemServer,我们的故事就从这里开始。

forkSystemServer

在这个函数里,系统会根据传入的参数创建系统服务,返回值是一个线程,为systemServer创建了它的入口

private static Runnable forkSystemServer(String abiList, String socketName,
            ZygoteServer zygoteServer) {
        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_PTRACE,
                OsConstants.CAP_SYS_TIME,
                OsConstants.CAP_SYS_TTY_CONFIG,
                OsConstants.CAP_WAKE_ALARM,
                OsConstants.CAP_BLOCK_SUSPEND
        );
        //上面机器不能用的CAP记得删除,不然容器会在空的里面运行
        StructCapUserHeader header = new StructCapUserHeader(
                OsConstants._LINUX_CAPABILITY_VERSION_3, 0);
        StructCapUserData[] data;
        try {
            data = Os.capget(header);
        } catch (ErrnoException ex) {
            throw new RuntimeException("Failed to capget()", ex);
        }
        capabilities &= ((long) data[0].effective) | (((long) data[1].effective) << 32);

		
        //用命令参数启动系统服务
        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,3011",
                "--capabilities=" + capabilities + "," + capabilities,
                "--nice-name=system_server",
                "--runtime-args",
                "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
                "com.android.server.SystemServer",
        };
        ZygoteArguments parsedArgs;

        int pid;

        try {
        	//创建zygote的命令缓冲区,它从始至终只能存在一个
            ZygoteCommandBuffer commandBuffer = new ZygoteCommandBuffer(args);
            try {
                parsedArgs = ZygoteArguments.getInstance(commandBuffer);
            } catch (EOFException e) {
                throw new AssertionError("Unexpected argument error for forking system server", e);
            }
            commandBuffer.close();
            Zygote.applyDebuggerSystemProperty(parsedArgs);
            Zygote.applyInvokeWithSystemProperty(parsedArgs);

            if (Zygote.nativeSupportsMemoryTagging()) {
                /* The system server has ASYNC MTE by default, in order to allow
                 * system services to specify their own MTE level later, as you
                 * can't re-enable MTE once it's disabled. */
                Slog.e(TAG, "MTE debug sync mode");
                parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_SYNC;
            } else if (Zygote.nativeSupportsTaggedPointers()) {
                /* Enable pointer tagging in the system server. Hardware support for this is present
                 * in all ARMv8 CPUs. */
                parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_TBI;
            }

            /* Enable gwp-asan on the system server with a small probability. This is the same
             * policy as applied to native processes and system apps. */
            parsedArgs.mRuntimeFlags |= Zygote.GWP_ASAN_LEVEL_LOTTERY;

            if (shouldProfileSystemServer()) {
                parsedArgs.mRuntimeFlags |= Zygote.PROFILE_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);
        }

        /* For child process */
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }

            zygoteServer.closeServerSocket();
            return handleSystemServerProcess(parsedArgs);
        }

        return null;
    }

在上面做了这么多准备之后,接着就要去调用zygote.forkSystemServer函数了。它是启动系统服务器进程的特殊方法。

    static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
            int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
        ZygoteHooks.preFork();

        int pid = nativeForkSystemServer(
                uid, gid, gids, runtimeFlags, rlimits,
                permittedCapabilities, effectiveCapabilities);

        // Set the Java Language thread priority to the default value for new apps.
        Thread.currentThread().setPriority(Thread.NORM_PRIORITY);

        ZygoteHooks.postForkCommon();
        return pid;
    }

它的返回值为pid,如果是-1那就是发生了错误。

后面的步骤代码有点多,总体的流程是这样的ZygoteInit.java:main()->forkSystemServer()->Zygote.java:forkSystemServer()->nativeForkSystemServer()->com_android_internal_os_Zygote.cpp:com_android_internal_os_Zygote_nativeForkSystemServer()->ZygoteInit.java->handleSystemServerProcess()

一直到这里结束,就启动SystemServer了

SystemServer

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

 private void run() {
 		...
 		// Start services.
 		//在这里启动服务,然后通过这个调用startBootstrapServices()函数启动引导服务
        try {
            t.traceBegin("StartServices");
            //这里
            startBootstrapServices(t);
            /// M: For mtk systemserver
            sMtkSystemServerIns.startMtkBootstrapServices();
            startCoreServices(t);
            /// M: for mtk other service.
            sMtkSystemServerIns.startMtkCoreServices();
            startOtherServices(t);
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {
            t.traceEnd(); // StartServices
        }
		....
		//很多的引导服务之间相互纠缠,所以把他们都放在一个函数内一起启动,如果不是这种情况的话还是放其它函数里面去启动吧
		private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
		...
		 // TODO: Might need to move after migration to WM.
        ActivityTaskManagerService atm = mSystemServiceManager.startService(
                ActivityTaskManagerService.Lifecycle.class).getService();
        mActivityManagerService = ActivityManagerService.Lifecycle.startService(
                mSystemServiceManager, atm);
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);
        mWindowManagerGlobalLock = atm.getGlobalLock();
        t.traceEnd();

好了,让我们来理一下在SystemServer类中的顺序:main->run->startBootstrapServices
从startBootstrapServices的代码我们可以看到它的顺序是这个样子的

  1. 启动ActivityTaskManagerService(ATMS),在网上查找资料发现是Android10.0新加入的系统服务类,将Activity的调度管理相关转移到了其中,我们现在探究的不是这个类,就一笔带过好了。
  2. 启动AMS的生命周期,用的参数为ATMS和systemservicemanager。
  3. 设置SystemServiceManager参数
  4. 注册installer至AMS

启动AMS

ActivityTaskManagerService

ActivityTaskManagerService atm = mSystemServiceManager.startService(
                ActivityTaskManagerService.Lifecycle.class).getService();

在这里我们可以看到,系统并不是直接对ATMS进行初始化的,而是通过它里面的静态内部类Lifecycle

  public static final class Lifecycle extends SystemService {
        private final ActivityTaskManagerService mService;

        public Lifecycle(Context context) {
            super(context);
            mService = new ActivityTaskManagerService(context);
        }
        ...

我们在初始化Lifecycle的时候,因为它是静态内部类,所以它的肯定不依靠外部加载,在初始化它的时候,同时就会对ATMS进行初始化。

启动AMS生命周期

同样的,AMS也是通过Lifecycle来启动的,而不是直接调用AMS的构造方法。

mActivityManagerService = ActivityManagerService.Lifecycle.startService(
                mSystemServiceManager, atm);
public static final class Lifecycle extends SystemService {
        private final ActivityManagerService mService;
        private static ActivityTaskManagerService sAtm;

        public Lifecycle(Context context) {
            super(context);
            mService = new ActivityManagerService(context, sAtm);
        }

        public static ActivityManagerService startService(
                SystemServiceManager ssm, ActivityTaskManagerService atm) {
            sAtm = atm;
            return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
        }
        ...
    }    

在这里是调用了ssm的startService方法,带动AMS的Lifecycle方法去启动。于是就会创建一个新的ActivityManagerService

    public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
    	//安装默认的锁屏界面
        LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
        mInjector = new Injector(systemContext);
        mContext = systemContext;

        mFactoryTest = FactoryTest.getMode();
        //这里创建了系统的主线程ActivityThread
        mSystemThread = ActivityThread.currentActivityThread();
        mUiContext = mSystemThread.getSystemUiContext();

        Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
		
		//创建一个HandlerThread设为ServiceThread并启动它
        mHandlerThread = new ServiceThread(TAG,
                THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
        mHandlerThread.start();
        mHandler = new MainHandler(mHandlerThread.getLooper());
        mUiHandler = mInjector.getUiHandler(this);

        mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
                THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
        mProcStartHandlerThread.start();
        mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());

        mConstants = new ActivityManagerConstants(mContext, this, mHandler);
        final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
        mPlatformCompat = (PlatformCompat) ServiceManager.getService(
                Context.PLATFORM_COMPAT_SERVICE);
        mProcessList = mInjector.getProcessList(this);
        mProcessList.init(this, activeUids, mPlatformCompat);
        mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(),
                new LowMemDetector(this));
        mPhantomProcessList = new PhantomProcessList(this);
        mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);

        //设置广播参数常量
        final BroadcastConstants foreConstants = new BroadcastConstants(
                Settings.Global.BROADCAST_FG_CONSTANTS);
        foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;

        final BroadcastConstants backConstants = new BroadcastConstants(
                Settings.Global.BROADCAST_BG_CONSTANTS);
        backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;

        final BroadcastConstants offloadConstants = new BroadcastConstants(
                Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
        offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
        // by default, no "slow" policy in this queue
        offloadConstants.SLOW_TIME = Integer.MAX_VALUE;

        mEnableOffloadQueue = SystemProperties.getBoolean(
                "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);

		//创建了三种广播队列:foreground,background,offload
        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "foreground", foreConstants, false);
        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "background", backConstants, true);
        mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
                "offload", offloadConstants, true);
        mBroadcastQueues[0] = mFgBroadcastQueue;
        mBroadcastQueues[1] = mBgBroadcastQueue;
        mBroadcastQueues[2] = mOffloadBroadcastQueue;

        mServices = new ActiveServices(this);
        mCpHelper = new ContentProviderHelper(this, true);
        //实例化watchdog
        mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
        mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
        mUidObserverController = new UidObserverController(mUiHandler);

        final File systemDir = SystemServiceManager.ensureSystemDir();

        // 将电池统计服务的创建移至活动管理器服务(AMS)之外。
        //这里的实现方法按照本人的理解应该是将这个服务转移到backgroundThread创建
        //而AMS中管理的服务本应该在同一个线程池
        mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
                BackgroundThread.get().getHandler());
        mBatteryStatsService.getActiveStatistics().readLocked();
        mBatteryStatsService.scheduleWriteToDisk();
        mOnBattery = DEBUG_POWER ? true
                : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
        mBatteryStatsService.getActiveStatistics().setCallback(this);
        mOomAdjProfiler.batteryPowerChanged(mOnBattery);

        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));

        mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);

        mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);

        mUserController = new UserController(this);

        mPendingIntentController = new PendingIntentController(
                mHandlerThread.getLooper(), mUserController, mConstants);

        mUseFifoUiScheduling = SystemProperties.getInt("sys.use_fifo_ui", 0) != 0;

        mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);

		//初始化ATMS
        mActivityTaskManager = atm;
        mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
                DisplayThread.get().getLooper());
        mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);

        mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);

		//加入watchdog
        Watchdog.getInstance().addMonitor(this);
        Watchdog.getInstance().addThread(mHandler);

        //将后台线程绑定至小核
        updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
        try {
            Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
                    Process.THREAD_GROUP_SYSTEM);
            Process.setThreadGroupAndCpuset(
                    mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(),
                    Process.THREAD_GROUP_SYSTEM);
        } catch (Exception e) {
            Slog.w(TAG, "Setting background thread cpuset failed");
        }

        mInternal = new LocalService();
        mPendingStartActivityUids = new PendingStartActivityUids(mContext);
        mTraceErrorLogger = new TraceErrorLogger();
    }

在调用构造函数的同时,也会通过onStart方法调用ActivityManagerService的start函数

private void start() {
		//移除所有的线程组
        removeAllProcessGroups();

		//部署电池状态信息收集服务,它会收集一切可能影响电池寿命的信息
        mBatteryStatsService.publish();
        //关于应用程序操作的信息和控制
        mAppOpsService.publish();
        Slog.d("AppOps", "AppOpsService published");
        LocalServices.addService(ActivityManagerInternal.class, mInternal);
        LocalManagerRegistry.addManager(ActivityManagerLocal.class,
                (ActivityManagerLocal) mInternal);
        mActivityTaskManager.onActivityManagerInternalAdded();
        mPendingIntentController.onActivityManagerInternalAdded();
        mAppProfiler.onActivityManagerInternalAdded();
        /// M: ANR Debug Mechanism
        mAnrManager.startAnrManagerService(MY_PID);
        /// M: DuraSpeed
        mAmsExt.startDuraSpeedService(mContext);
    }
    ...
    public void setInstaller(Installer installer) {
        mInstaller = installer;
    }

除此之外,在SystemServer中还调用了AMS的其他函数,初始化或启动一些其他的系统服务

 		t.traceBegin("InitPowerManagement");
        mActivityManagerService.initPowerManagement();
        t.traceEnd();
 		......
 // Set up the Application instance for the system process and get started.
        t.traceBegin("SetSystemProcess");
        mActivityManagerService.setSystemProcess();
        t.traceEnd();
        

这两函数分别调用用来初始化电源管理和其他服务

	public void initPowerManagement() {
        	mActivityTaskManager.onInitPowerManagement();
        	mBatteryStatsService.initPowerManagement();
        	mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
    	}
    ......
    public void setSystemProcess() {
        try {
        	//注册服务activity
            ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                    DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
            //注册进程状态服务
            ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
            //内存
            ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
                    DUMP_FLAG_PRIORITY_HIGH);
            //图像信息
            ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
            //数据库信息
            ServiceManager.addService("dbinfo", new DbBinder(this));
            //cpu信息
            mAppProfiler.setCpuInfoService();
            //权限信息
            ServiceManager.addService("permission", new PermissionController(this));
            //线程信息
            ServiceManager.addService("processinfo", new ProcessInfoService(this));
            //缓存信息
            ServiceManager.addService("cacheinfo", new CacheBinder(this));

            /// M: ANR Debug Mechanism
            mAnrManager.AddAnrManagerService();
            /// M: DuraSpeed
            mAmsExt.addDuraSpeedService();

            ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                    "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
            mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
			
			//创建ProcessRecord维护线程信息,会记录当前运行的特定线程的所有信息
            synchronized (this) {
                ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
                        false,
                        0,
                        new HostingRecord("system"));
                //设置持久性
                app.setPersistent(true);
                //将这个PID设为常量
                app.setPid(MY_PID);
                app.mState.setMaxAdj(ProcessList.SYSTEM_ADJ);
                app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
                addPidLocked(app);
                updateLruProcessLocked(app, false, null);
                updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
            }

            /// M: Dynamically enable AMS logs @{
            mAmsExt.enableAmsLog(mProcessList.mLruProcesses);
            /// @}
           /// M: CTA requirement(Auto boot manager)
           CtaManagerFactory.getInstance().makeCtaManager().addAutoBootService(mContext);
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(
                    "Unable to find android system package", e);
        }
		
		//启动后会在后台运行观察应用的操作
        // Start watching app ops after we and the package manager are up and running.
        mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
                new IAppOpsCallback.Stub() {
                    @Override public void opChanged(int op, int uid, String packageName) {
                        if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
                            if (getAppOpsManager().checkOpNoThrow(op, uid, packageName)
                                    != AppOpsManager.MODE_ALLOWED) {
                                runInBackgroundDisabled(uid);
                            }
                        }
                    }
                });

        final int[] cameraOp = {AppOpsManager.OP_CAMERA};
        mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() {
            @Override
            public void opActiveChanged(int op, int uid, String packageName, String attributionTag,
                    boolean active, @AttributionFlags int attributionFlags,
                    int attributionChainId) {
                cameraActiveChanged(uid, active);
            }
        });
    }

总结

  1. 首先,在zygote被创建之后会fork出systemServer进程
  2. SystemServer在被创建之后会调用run函数,接着因为很多系统服务相互纠缠连接所以会调用startBootstrapServices函数将一堆服务初始化,在这里我们知道的一点是它一般不是通过直接使用构造函数进行创建而是通过系统服务内部的静态内部类Lifecycle去进行初始化,这样做的好处大家可以探讨一下。
  3. AMS在启动之后会依次加载一些资源,对一些资源进行创建,例如电池和应用的监控。
  4. 接下来还会启用startOtherServices() 完成AMS的后续工作

你可能感兴趣的:(android,java,开发语言)