失眠必读系列——AMS 如何注册

272 阅读3分钟

WechatIMG156.png

源码调用链

System Server启动时会在内部启动很多系统服务,其中就包括AMS,我们直接看源码吧:

/frameworks/base/services/java/com/android/server/SystemServer.java

public static void main(String[] args) {
    new SystemServer().run();
}
private void run() {
    ……
    startBootstrapServices();
    ……
}
private void startBootstrapServices() {
    ……
    mActivityManagerService.setSystemProcess();//844行
    ……
}

/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public void setSystemProcess() {
    ……
    ServiceManager.addService(Context.ACTIVITY_SERVICE, **this**, ……);//这个this就是AMS
    ……
}

/frameworks/base/core/java/android/os/ServiceManager.java

public static void addService(String name, IBinder service) {
    addService(name, service, false, IServiceManager.DUMP_FLAG_PRIORITY_DEFAULT);
}
public static void addService(String name, IBinder service, boolean allowIsolated) {
    addService(name, service, allowIsolated, IServiceManager.DUMP_FLAG_PRIORITY_DEFAULT);
}
public static void addService(String name, IBinder service, boolean allowIsolated,int dumpPriority) {
    try {
        getIServiceManager().addService(name, service, allowIsolated, dumpPriority);
    } catch (RemoteException e) {
        Log.e(TAG, "error in addService", e);
    }
}
private static IServiceManager getIServiceManager() {
    if (sServiceManager != null) {
        return sServiceManager;
    }
    // Find the service manager
    sServiceManager = ServiceManagerNative.asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));
    return sServiceManager;

}

/frameworks/base/core/java/com/android/internal/os/BinderInternal.java

public static final native IBinder getContextObject();

/frameworks/base/core/jni/android_util_Binder.cpp

static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
{
    sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
    return javaObjectForIBinder(env, b);
}

/frameworks/native/libs/binder/ProcessState.cpp

//单例模式创建ProcessState实例
sp<ProcessState> ProcessState::self()
{
    Mutex::Autolock _l(gProcessMutex);
    if (gProcess != nullptr) {
        return gProcess;
    }
    gProcess = new ProcessState(kDefaultDriver);
    return gProcess;
}

ProcessState::ProcessState(const char *driver)
    : mDriverName(String8(driver))
    , mDriverFD(open_driver(driver))
  ……
{
……
    mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
……
}

//1.打开binder设备,与内核中的binder驱动交互
//2.通过ioctl命令设置binder驱动最大的线程数
#define DEFAULT_MAX_BINDER_THREADS 15
static int open_driver(const char *driver)
{
    int fd = open(driver, O_RDWR | O_CLOEXEC);
    ……
    size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
    result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
    ……
    return fd;
}

sp<IBinder> ProcessState::getContextObject(const sp<IBinder>&)
{
    return getStrongProxyForHandle(0);
}

//得出BinderInternal.getContextObject()返回BpBinder对象
//接着继续分析 javaObjectForIBinder(env, b)
sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
{
    ……
    if (b == nullptr || !e->refs->attemptIncWeak(this)) {
        ……
        b = BpBinder::create(handle);
        ……
    }
    ……
}

/frameworks/base/core/jni/android_util_Binder.cpp

//创建BinderProxy对象,其中mObject记录了BpBinder对象
jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
{
    ……
    BinderProxyNativeData* nativeData = new BinderProxyNativeData();
    nativeData->mOrgue = new DeathRecipientList;
    nativeData->mObject = val;
    jobject object = env->CallStaticObjectMethod(gBinderProxyOffsets.mClass,
    gBinderProxyOffsets.mGetInstance, (jlong) nativeData, (jlong) val.get());
    ……
}

回到ServiceManager /frameworks/base/core/java/android/os/ServiceManager.java

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

/frameworks/base/core/java/android/os/ServiceManagerNative.java

static public IServiceManager asInterface(IBinder obj)
{
    if (obj == null) {return null;}
    IServiceManager in = (IServiceManager)obj.queryLocalInterface(descriptor);
    if (in != null) {return in;}
    return new ServiceManagerProxy(obj);
}

得出 sServiceManager 是ServiceManagerProxy对象,其中有addService方法

class ServiceManagerProxy implements IServiceManager {
    public ServiceManagerProxy(IBinder remote) {
        mRemote = remote;
    }

    public void addService(String name, IBinder service, boolean allowIsolated, int dumpPriority)throws RemoteException {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IServiceManager.descriptor);
        data.writeString(name);
        //这里service是AMS
        data.writeStrongBinder(service);
        data.writeInt(allowIsolated ? 1 : 0);
        data.writeInt(dumpPriority);
        //mRemote是BinderProxy对象
        mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0);
        reply.recycle();
        data.recycle();
    }
}

data.writeStrongBinder(service);

/frameworks/base/core/java/android/os/Parcel.java
writeStrongBinder()

/frameworks/base/core/jni/android_os_Parcel.cpp
android_os_Parcel_writeStrongBinder()

/frameworks/base/core/jni/android_util_Binder.cpp
parcel->writeStrongBinder(ibinderForJavaObject(env, object));

/frameworks/native/libs/binder/Parcel.cpp
status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
{
    return flatten_binder(ProcessState::self(), val, this);
}

status_t flatten_binder(……)
{
    flat_binder_object obj;
    ……
    obj.type = BINDER_TYPE_BINDER;
    obj.binder = reinterpret_cast<uintptr_t>(local->getWeakRefs());
    obj.cookie = reinterpret_cast<uintptr_t>(local);
    ……
    return finish_flatten_binder(binder, obj, out); 
}
inline static status_t finish_flatten_binder(……)
{
    return out->writeObject(flat, false);
}

AMS的信息保存在了flat_binder_object对象中,然后将flat_binder_object写入out

摘自网络:www.jianshu.com/p/9d1c8a0f3…
Parcel 是用来封装进程间通信数据的, Java 层中的每一个 Parcel 对象在 C++层中都有一个对应的 Parcel 对象, 后者的地址就保存在前者的成员变量 mObject 中. 当将进程间通信的数据封装在一个 Java 层的 Parcel 对象时, 这个 Java 层中的 Parcel 对象就会通过其成员变量 mObject 找到与它对应的运行在 C++ 层中的 Parcel 对象.并且将这些进程间通信数据封装到 C++ 层中的 Parcel 对象里面去.

/frameworks/base/core/java/android/os/BinderProxy.java

public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
    ……
    return transactNative(code, data, reply, flags);
    ……
}

public native boolean transactNative(int code, Parcel data, Parcel reply, int flags) throws RemoteException;

/frameworks/base/core/jni/android_util_Binder.cpp

static jboolean android_os_BinderProxy_transact( ){
    ……
    IBinder* target = getBPNativeData(env, obj)->mObject.get();
    ……
    status_t err = target->transact(code, *data, reply, flags);
    ……
}

对应上面javaObjectForIBinder方法,得知target是BpBinder对象

/frameworks/native/libs/binder/BpBinder.cpp

status_t BpBinder::transact(……)
{
    // Once a binder has died, it will never come back to life.
    if (mAlive) {
        status_t status = IPCThreadState::self()->transact(
            mHandle, code, data, reply, flags);
        if (status == DEAD_OBJECT) mAlive = 0;
        return status;
    }
    return DEAD_OBJECT;
}

/frameworks/native/libs/binder/IPCThreadState.cpp

status_t IPCThreadState::transact(……)
{
    ……
    err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, nullptr);
    ……
    err = waitForResponse(reply);
}

//将数据写入mOut
status_t IPCThreadState::writeTransactionData(……)
{
    binder_transaction_data tr;
    mOut.writeInt32(cmd);
    mOut.write(&tr, sizeof(tr));
    return NO_ERROR;
}

status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
{
  while (1) {
    //循环等待结果
    if ((err=talkWithDriver()) < NO_ERROR) break;
  }
}

status_t IPCThreadState::talkWithDriver(bool doReceive)
{
    ……
    do {
          #if defined(__ANDROID__)
            if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
                err = NO_ERROR;
            else
                err = -errno;
        } while (err == -EINTR);
    ……
}

ioctl进入内核层 /drivers/staging/android/binder.c

static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
    ……
    case BINDER_WRITE_READ: {
        ret = binder_thread_write(……)
    }
    ……
}

int binder_thread_write(……)
{
    ……
    case BC_TRANSACTION: {
        binder_transaction(proc, thread, &tr, cmd == BC_REPLY);
    break;
    }
    ……
}

static void binder_transaction(……)
{
    ……
    copy_from_user(……)
    copy_from_user(……)
    ……
    wake_up_interruptible(……)
}

唤醒SM /frameworks/native/cmds/servicemanager/service_manager.c

调用svcmgr_handler()

调用do_add_service方法添加服务

保存服务到svclist中

结尾:

失眠必读系列未完待续,有任何错误,虚心讨教,欢迎指正...


参考资料:
blog.csdn.net/super_marie…
www.jianshu.com/p/05398aff9…