• Android—ATMS启动


    在SystemServer启动的时候会去执行run函数,函数里面有startBootstrapServices();是去启动引导级服务

    主要启动以下10个服务:

    • Installer
    • DeviceIdentifiersPolicyService
    • UriGrantsManagerService
    • ActivityTaskManagerService
    • ActivityManagerService
    • PowerManagerService
    • ThermalManagerService
    • RecoverySystemService
    • LightsService
    • DisplayManagerService

    还有在启动这些服务之前会去启动Watchdog,它的作用就是去监听SystemServer是否发生死锁,会就把SystemServer进程杀掉。

    本文重点是ActivityManagerService

    frameworks\base\services\java\com\android\server\SystemServer.java:

    1. Installer installer = mSystemServiceManager.startService(Installer.class);
    2. // Activity manager runs the show.
    3. traceBeginAndSlog("StartActivityManager");
    4. // TODO: Might need to move after migration to WM.
    5. ActivityTaskManagerService atm = mSystemServiceManager.startService(
    6. ActivityTaskManagerService.Lifecycle.class).getService();
    7. mActivityManagerService = ActivityManagerService.Lifecycle.startService(
    8. mSystemServiceManager, atm);
    9. mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    10. mActivityManagerService.setInstaller(installer);
    11. mWindowManagerGlobalLock = atm.getGlobalLock();
    12. traceEnd();

    上面是SystemServer的startBootstrapServices函数中关于ActivityManagerService的内容,

    1.mSystemServiceManager.startService(Installer.class);

    1. public SystemService startService(String className) {
    2. final Class serviceClass;
    3. try {
    4. serviceClass = (Class)Class.forName(className);
    5. } catch (ClassNotFoundException ex) {
    6. ....
    7. }
    8. return startService(serviceClass);
    9. }
    10. public extends SystemService> T startService(Class serviceClass) {
    11. try {
    12. final String name = serviceClass.getName();
    13. .....
    14. final T service;
    15. try {
    16. Constructor constructor = serviceClass.getConstructor(Context.class);
    17. service = constructor.newInstance(mContext);
    18. } catch (InstantiationException ex) {
    19. .....
    20. }
    21. startService(service);
    22. return service;
    23. } finally {
    24. Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    25. }
    26. }
    27. public void startService(@NonNull final SystemService service) {
    28. // Register it.
    29. mServices.add(service);
    30. // Start it.
    31. long time = SystemClock.elapsedRealtime();
    32. try {
    33. service.onStart();
    34. } catch (RuntimeException ex) {
    35. throw new RuntimeException("Failed to start service " + service.getClass().getName()
    36. + ": onStart threw an exception", ex);
    37. }
    38. warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
    39. }

    mSystemServiceManager.startService(Installer.class);一路跟下来就是去反射获取Installer对象然后调用它的onStart方法,且Installer类继承了SystemService。

    1. @Override
    2. public void onStart() {
    3. if (mIsolated) {
    4. mInstalld = null;
    5. } else {
    6. connect();
    7. }
    8. }
    9. private void connect() {
    10. IBinder binder = ServiceManager.getService("installd");
    11. if (binder != null) {
    12. try {
    13. binder.linkToDeath(new DeathRecipient() {
    14. @Override
    15. public void binderDied() {
    16. Slog.w(TAG, "installd died; reconnecting");
    17. connect();
    18. }
    19. }, 0);
    20. } catch (RemoteException e) {
    21. binder = null;
    22. }
    23. }
    24. if (binder != null) {
    25. mInstalld = IInstalld.Stub.asInterface(binder);
    26. try {
    27. invalidateMounts();
    28. } catch (InstallerException ignored) {
    29. }
    30. } else {
    31. Slog.w(TAG, "installd not found; trying again");
    32. BackgroundThread.getHandler().postDelayed(() -> {
    33. connect();
    34. }, DateUtils.SECOND_IN_MILLIS);
    35. }
    36. }
    37. public void invalidateMounts() throws InstallerException {
    38. if (!checkBeforeRemote()) return;
    39. try {
    40. mInstalld.invalidateMounts();
    41. } catch (Exception e) {
    42. throw InstallerException.from(e);
    43. }
    44. }

    onStart里面去调用了connect,然后获取installd服务的BInder对象,最后执行了该Binder对象的invalidateMounts方法。我们可以知道mInstalld对象的服务名叫installd,全局搜一下。

    frameworks\native\cmds\installd\InstalldNativeService.h:

    1. class InstalldNativeService : public BinderService, public os::BnInstalld {
    2. public:
    3. static status_t start();
    4. static char const* getServiceName() { return "installd"; }
    5. ....
    6. }

    发现这个就是我们找的mInstalld对象所对应的类,接下来进入cpp文件查看它的方法。


    可以看出installd服务的方法基本都是在操作应用数据的,apk应用的安装和卸载主要是由它来完成。

    1. binder::Status InstalldNativeService::invalidateMounts() {
    2. ENFORCE_UID(AID_SYSTEM);
    3. std::lock_guard lock(mMountsLock);
    4. mStorageMounts.clear();
    5. #if !BYPASS_QUOTA
    6. if (!InvalidateQuotaMounts()) {
    7. return error("Failed to read mounts");
    8. }
    9. #endif
    10. std::ifstream in("/proc/mounts");
    11. if (!in.is_open()) {
    12. return error("Failed to read mounts");
    13. }
    14. std::string source;
    15. std::string target;
    16. std::string ignored;
    17. while (!in.eof()) {
    18. std::getline(in, source, ' ');
    19. std::getline(in, target, ' ');
    20. std::getline(in, ignored);
    21. #if !BYPASS_SDCARDFS
    22. if (target.compare(0, 21, "/mnt/runtime/default/") == 0) {
    23. LOG(DEBUG) << "Found storage mount " << source << " at " << target;
    24. mStorageMounts[source] = target;
    25. }
    26. #endif
    27. }
    28. return ok();
    29. }

    invalidateMounts就是去查看设备挂载的存储空间是否可读等,以此判断自己能否对应用存储空间进行操作。

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

    ActivityTaskManagerService简称ATM,Android10中引入新功能,用来管理Activity的启动、调度等功能。

    我们从上面知道了startService会实例化对应Service,然后调用onStart方法,这里直接看ActivityTaskManagerService.Lifecycle的onStart方法

    1. public static final class Lifecycle extends SystemService {
    2. private final ActivityTaskManagerService mService;
    3. public Lifecycle(Context context) {
    4. super(context);
    5. mService = new ActivityTaskManagerService(context);
    6. }
    7. @Override
    8. public void onStart() {
    9. publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
    10. mService.start();
    11. }
    12. ....
    13. public ActivityTaskManagerService getService() {
    14. return mService;
    15. }
    16. }

    Lifecycle是ActivityTaskManagerService的内部类,也继承了SystemService,而且内部持有外部类ActivityTaskManagerService的对象,可以看到Lifecycle构造函数里面也构建了外部类对象,并且在onStart的时候也调了它的start方法。

    我们看一下ActivityTaskManagerService有什么内容:

    1. public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
    2. final Context mUiContext;
    3. final ActivityThread mSystemThread;
    4. final ActivityTaskManagerInternal mInternal;
    5. //ActivityStackSupervisor 原本是ATM中用来管理Activity启动和调度的核心类
    6. public ActivityStackSupervisor mStackSupervisor;
    7. //Activity 容器的根节点
    8. RootActivityContainer mRootActivityContainer;
    9. //WMS 负责窗口的管理
    10. WindowManagerService mWindowManager;
    11. WindowProcessController mHomeProcess;
    12. public ActivityTaskManagerService(Context context) {
    13. //拿到System Context
    14. mContext = context;
    15. mFactoryTest = FactoryTest.getMode();
    16. //取出的是ActivityThread的静态变量sCurrentActivityThread
    17. //这意味着mSystemThread与SystemServer中的ActivityThread一致
    18. mSystemThread = ActivityThread.currentActivityThread();
    19. //拿到System UI Context
    20. mUiContext = mSystemThread.getSystemUiContext();
    21. mLifecycleManager = new ClientLifecycleManager();
    22. //拿到LocalService的对象
    23. mInternal = new LocalService();
    24. GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
    25. }
    26. }

    接下来看publishBinderService

    1. protected final void publishBinderService(String name, IBinder service) {
    2. publishBinderService(name, service, false);
    3. }
    4. protected final void publishBinderService(String name, IBinder service,
    5. boolean allowIsolated) {
    6. publishBinderService(name, service, allowIsolated, DUMP_FLAG_PRIORITY_DEFAULT);
    7. }
    8. protected final void publishBinderService(String name, IBinder service,
    9. boolean allowIsolated, int dumpPriority) {
    10. ServiceManager.addService(name, service, allowIsolated, dumpPriority);
    11. }

    frameworks\base\core\java\android\os\ServiceManager.java:

    1. @UnsupportedAppUsage
    2. public static void addService(String name, IBinder service, boolean allowIsolated,
    3. int dumpPriority) {
    4. try {
    5. getIServiceManager().addService(name, service, allowIsolated, dumpPriority);
    6. } catch (RemoteException e) {
    7. Log.e(TAG, "error in addService", e);
    8. }
    9. }
    10. @UnsupportedAppUsage
    11. private static IServiceManager getIServiceManager() {
    12. if (sServiceManager != null) {
    13. return sServiceManager;
    14. }
    15. // Find the service manager
    16. sServiceManager = ServiceManagerNative
    17. .asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));
    18. return sServiceManager;
    19. }
    20. public static final native IBinder getContextObject();

    可以看到publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);跟到后面是            getIServiceManager().addService(name, service, allowIsolated, dumpPriority);
    这个ServiceManager是通过BinderInternal.getContextObject()获取IBinder对象然后再asInterface封装成IServiceManager,跟我们之前分析的Binder非常相似,这里也只是一个BpBinder而已,不是真正处理工作的地方。

    我们全局搜一下哪里动态注册了这个getContextObject方法,

    frameworks\base\core\java\com\android\internal\os\BinderInternal.java:

    { "getContextObject", "()Landroid/os/IBinder;", (void*)android_os_BinderInternal_getContextObject }

    1. static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
    2. {
    3. sp b = ProcessState::self()->getContextObject(NULL);
    4. return javaObjectForIBinder(env, b);
    5. }

    果然这里就是去调用了ProcessState的getContextObject方法,不熟悉这里的可以去看前文:

    Android_Binder—分析MediaServer解析服务的初始化和注册

    ProcessState的getContextObject方法就是返回了一个BPBinder。

    1. //如果参数是JavaBBinder,返回用于创建它的Java对象。
    2. //否则返回IBinder的绑定代理。如果传递了之前的呼叫
    3. //如果原来的绑定代理仍然存在,则返回原来的绑定代理。
    4. jobject javaObjectForIBinder(JNIEnv* env, const sp& val)
    5. {
    6. if (val == NULL) return NULL;
    7. if (val->checkSubclass(&gBinderOffsets)) {
    8. // It's a JavaBBinder created by ibinderForJavaObject. Already has Java object.
    9. jobject object = static_cast(val.get())->object();
    10. LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);
    11. return object;
    12. }
    13. BinderProxyNativeData* nativeData = new BinderProxyNativeData();
    14. nativeData->mOrgue = new DeathRecipientList;
    15. nativeData->mObject = val;
    16. jobject object = env->CallStaticObjectMethod(gBinderProxyOffsets.mClass,
    17. gBinderProxyOffsets.mGetInstance, (jlong) nativeData, (jlong) val.get());
    18. if (env->ExceptionCheck()) {
    19. // In the exception case, getInstance still took ownership of nativeData.
    20. return NULL;
    21. }
    22. BinderProxyNativeData* actualNativeData = getBPNativeData(env, object);
    23. if (actualNativeData == nativeData) {
    24. // Created a new Proxy
    25. uint32_t numProxies = gNumProxies.fetch_add(1, std::memory_order_relaxed);
    26. uint32_t numLastWarned = gProxiesWarned.load(std::memory_order_relaxed);
    27. if (numProxies >= numLastWarned + PROXY_WARN_INTERVAL) {
    28. // Multiple threads can get here, make sure only one of them gets to
    29. // update the warn counter.
    30. if (gProxiesWarned.compare_exchange_strong(numLastWarned,
    31. numLastWarned + PROXY_WARN_INTERVAL, std::memory_order_relaxed)) {
    32. ALOGW("Unexpectedly many live BinderProxies: %d\n", numProxies);
    33. }
    34. }
    35. } else {
    36. delete nativeData;
    37. }
    38. return object;
    39. }

    这个方法注释已经写得很清楚了,因为我们这里传进去的是一个BPBinder而不是JavaBBinder,所以返回的是由这个BPBinder对象生成的BinderProxy(Java)对象,BpBinder对象地址保存到BinderProxy.mObject成员变量,实现了Java对象拥有了native对象的引用。

            sServiceManager = ServiceManagerNative
                    .asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));

    分析完 getContextObject,allowBlocking没什么作用,我们继续看ServiceManagerNative.asInterface, 

    1. static public IServiceManager asInterface(IBinder obj)
    2. {
    3. if (obj == null) {
    4. return null;
    5. }
    6. IServiceManager in =
    7. (IServiceManager)obj.queryLocalInterface(descriptor);
    8. if (in != null) {
    9. return in;
    10. }
    11. return new ServiceManagerProxy(obj);
    12. }
    13. /**
    14. * Retrieve a local interface - always null in case of a proxy
    15. */
    16. public IInterface queryLocalInterface(String descriptor) {
    17. return null;
    18. }

    我们可以知道这个IBinder是BinderProxy,我们要知道一个代理对象的queryLocalInterface方法一直是返回null,所以最终返回的是ServiceManagerProxy对象。

                getIServiceManager().addService(name, service, allowIsolated, dumpPriority);

    所以getIServiceManager()就是获取一个BpServiceManager然后封装成ServiceManagerProxy,接下来我们看看addService

    1. @UnsupportedAppUsage
    2. public static void addService(String name, IBinder service, boolean allowIsolated,
    3. int dumpPriority) {
    4. try {
    5. getIServiceManager().addService(name, service, allowIsolated, dumpPriority);
    6. } catch (RemoteException e) {
    7. Log.e(TAG, "error in addService", e);
    8. }
    9. }

    frameworks\base\core\java\android\os\ServiceManagerNative.java:

    1. public ServiceManagerProxy(IBinder remote) {
    2. mRemote = remote;
    3. }
    4. public void addService(String name, IBinder service, boolean allowIsolated, int dumpPriority)
    5. throws RemoteException {
    6. Parcel data = Parcel.obtain();
    7. Parcel reply = Parcel.obtain();
    8. data.writeInterfaceToken(IServiceManager.descriptor);
    9. data.writeString(name);
    10. data.writeStrongBinder(service);
    11. data.writeInt(allowIsolated ? 1 : 0);
    12. data.writeInt(dumpPriority);
    13. mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0);
    14. reply.recycle();
    15. data.recycle();
    16. }

    这里就是熟悉的Binder通讯了,明显可以看出这个ServiceManagerProxy就是代理调用transact方法,mRemote就是BinderProxy,分析它的transcat方法。

    1. public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
    2. ....
    3. try {
    4. return transactNative(code, data, reply, flags);
    5. } finally {
    6. ....
    7. }
    8. }
    9. public native boolean transactNative(int code, Parcel data, Parcel reply,
    10. int flags) throws RemoteException;

    {"transactNative",      "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", (void*)android_os_BinderProxy_transact}

    1. static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
    2. jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
    3. {
    4. ....
    5. IBinder* target = getBPNativeData(env, obj)->mObject.get();
    6. ....
    7. status_t err = target->transact(code, *data, reply, flags);
    8. ....
    9. if (err == NO_ERROR) {
    10. return JNI_TRUE;
    11. } else if (err == UNKNOWN_TRANSACTION) {
    12. return JNI_FALSE;
    13. }
    14. return JNI_FALSE;
    15. }

    这里又从 BinderProxy中拿回Native层的BPBinder调用它的transact方法。

    所以publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);就是把ActivityTaskManagerService添加到ServiceManager里面。相比于Native就是多了一层ServiceManagerProxy和BinderProxy用来连接Java与Native。

            @Override
            public void onStart() {
                publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
                mService.start();
            }

    接下来分析mService.start();

    1. private void start() {
    2. LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
    3. }

     这个 LocalServices和mInternal是什么呢?

    1. /**
    2. * 该类的使用方式与ServiceManager类似,只是这里注册的服务不是Binder对象,
    3. * 只能在同一个进程中使用。
    4. *
    5. * 一旦所有服务都转换为SystemService接口,这个类就可以被SystemServiceManager吸收。
    6. */
    7. public final class LocalServices {
    8. private LocalServices() {}
    9. private static final ArrayMap, Object> sLocalServiceObjects =
    10. new ArrayMap, Object>();
    11. /**
    12. * Returns a local service instance that implements the specified interface.
    13. *
    14. * @param type The type of service.
    15. * @return The service object.
    16. */
    17. @SuppressWarnings("unchecked")
    18. public static T getService(Class type) {
    19. synchronized (sLocalServiceObjects) {
    20. return (T) sLocalServiceObjects.get(type);
    21. }
    22. }
    23. /**
    24. * Adds a service instance of the specified interface to the global registry of local services.
    25. */
    26. public static void addService(Class type, T service) {
    27. synchronized (sLocalServiceObjects) {
    28. if (sLocalServiceObjects.containsKey(type)) {
    29. throw new IllegalStateException("Overriding service registration");
    30. }
    31. sLocalServiceObjects.put(type, service);
    32. }
    33. }
    34. .....
    35. }

    LocalServices就是一个存放服务在SystemServer进程的地方,SystemServer进程下的服务可以获取其他服务来实现自己的功能。

    mInternal的话我们看

    1. public Lifecycle(Context context) {
    2. super(context);
    3. mService = new ActivityTaskManagerService(context);
    4. }
    5. @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
    6. public ActivityTaskManagerService(Context context) {
    7. mContext = context;
    8. mFactoryTest = FactoryTest.getMode();
    9. mSystemThread = ActivityThread.currentActivityThread();
    10. mUiContext = mSystemThread.getSystemUiContext();
    11. mLifecycleManager = new ClientLifecycleManager();
    12. mInternal = new LocalService();
    13. GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
    14. }
    15. final class LocalService extends ActivityTaskManagerInternal

    所以mInternal就是ActivityTaskManagerInternal对象。

    ATMS启动

    1. 调用publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);把自己添加到ServiceManager里面。
    2. LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);把自己的内部类LocalService添加进LocalServices中方便同进程其他服务调用。

  • 相关阅读:
    WiFi在Settings中的热点开启流程小结
    Aop注解+Redis解决SpringBoot接口幂等性(源码自取)
    洛谷千题详解 | P1010 [NOIP1998 普及组] 幂次方【C++、Java、Python、Pascal语言】
    [附源码]计算机毕业设计SpringBoot四川景区管理系统
    LeetCode 第6题:Z字形变换(Python3解法)
    Java从入门到架构师__常用工具&常用API&本地缓存&RestTemplate
    Java 编码那些事(二)
    MHA高可用配置及故障切换
    力扣561. 数组拆分
    华为数通方向HCIP-DataCom H12-821题库(单选题:261-280)
  • 原文地址:https://blog.csdn.net/weixin_41939525/article/details/125987821