Android Binder机制 - defaultServiceManager()源码分析

Android 使用Binder进程间通信时,需要先使用defaultServiceManager方法获取ServiceManager,通过ServiceManager的addService或getService来与Binder驱动程序进行交互。下面分析下defaultServiceManager的实现过程。

先看defaultServiceManager牵扯的所有类的一个类图,里面有各个类对应的路径:

这里写图片描述

defaultServiceManager的实现是在frameworks\native\libs\binder\IServiceManager.cpp中:

sp<IServiceManager> defaultServiceManager()
{
    if (gDefaultServiceManager != NULL) return gDefaultServiceManager;

    {
        AutoMutex _l(gDefaultServiceManagerLock);
        while (gDefaultServiceManager == NULL) {
            gDefaultServiceManager = interface_cast<IServiceManager>(
                ProcessState::self()->getContextObject(NULL));
            if (gDefaultServiceManager == NULL)
                sleep(1);
        }
    }

    return gDefaultServiceManager;
}

从上述代码中可以看出gDefaultServiceManager是使用单例模式,也就是通过interface_cast<IServiceManager>(ProcessState::self()->getContextObject(NULL));来实现的。

首先看下传入的参数ProcessState::self()->getContextObject(NULL)代表什么,ProcessState的路径是frameworks\native\libs\binder\ProcessState.cpp,

sp<ProcessState> ProcessState::self()
{
    Mutex::Autolock _l(gProcessMutex);
    if (gProcess != NULL) {
        return gProcess;
    }
    gProcess = new ProcessState;
    return gProcess;
}

ProcessState::self()也是单例模式,第一次进去会实例化一个ProcessState对象,看下构造函数:

ProcessState::ProcessState()
    : mDriverFD(open_driver()) //打开Binder驱动,并将文件描述符FD赋给mDriverFD
   ......
{
    if (mDriverFD >= 0) {
        // 映射mDriverFD 到内存中
        mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
        if (mVMStart == MAP_FAILED) {
            // *sigh*
            ALOGE("Using /dev/binder failed: unable to mmap transaction memory.\n");
            close(mDriverFD);
            mDriverFD = -1;
        }
    }

    LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver could not be opened.  Terminating.");
}

//打开驱动
static int open_driver()
{
    //打开Binder驱动对应的文件,Linux中一切事物皆文件
    int fd = open("/dev/binder", O_RDWR | O_CLOEXEC);
    if (fd >= 0) {
        int vers = 0;
        //告诉内核Binder的版本号
        status_t result = ioctl(fd, BINDER_VERSION, &vers);
        ......
        size_t maxThreads = DEFAULT_MAX_BINDER_THREADS; //默认值为15
        //告诉内核支持的最大线程数
        result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
        ......
    }
    return fd;
}

ProcessState::self()也就是获取一个持有Binder驱动文件描述符的ProcessState,下面看下其getContextObject(NULL)函数的实现。

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

sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
{
    sp<IBinder> result;
    AutoMutex _l(mLock);
    handle_entry* e = lookupHandleLocked(handle);

    if (e != NULL) {
            //创建BpBinder对象,handle为0
            b = new BpBinder(handle);
            e->binder = b;
            if (b) e->refs = b->getWeakRefs();
            result = b;
        } else {
           ......
        }
    }
    return result;
}

从上述代码可以看出,getContextObject(NULL)函数就是创建一个BpBinder对象,handle为0。
到这里defaultServiceManager = interface_cast(ProcessState::self()->getContextObject(NULL));
= interface_cast(new BpBinder(0));

下面看下interface_cast的实现,其代码在IInterface.h中

template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
    return INTERFACE::asInterface(obj);
}
//这是一个模板函数,展开即为:
inline sp<IServiceManager > interface_cast(const sp<IBinder>& obj)
{
    return IServiceManager ::asInterface(obj);
}

//IServiceManager的asInterface是通过DECLARE_META_INTERFACE(ServiceManager);来声明的,使用的是其父类IInterface的宏定义
class IServiceManager : public IInterface
{
public:
    DECLARE_META_INTERFACE(ServiceManager);
}

#define DECLARE_META_INTERFACE(INTERFACE)
    static const android::String16 descriptor;
    //声明asInterface函数
    static android::sp<I##INTERFACE> asInterface( 
            const android::sp<android::IBinder>& obj);
    virtual const android::String16& getInterfaceDescriptor() const;
    I##INTERFACE();
    virtual ~I##INTERFACE();


#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)
......  
    android::sp<I##INTERFACE> I##INTERFACE::asInterface(
            const android::sp<android::IBinder>& obj)
    {
        android::sp<I##INTERFACE> intr; 
        if (obj != NULL) {
            intr = static_cast<I##INTERFACE*>(
                obj->queryLocalInterface( 
                        I##INTERFACE::descriptor).get()); 
            if (intr == NULL) {
                intr = new Bp##INTERFACE(obj); //展开即为intr = new BpServiceManager(obj);
            }
        }
        return intr;
    }

//看下BpServiceManager的构造函数,它是将参数new BpBinder(0)传给其父类
BpServiceManager(const sp<IBinder>& impl)
        : BpInterface<IServiceManager>(impl)
{
}

//将参数继续传给父类
template<typename INTERFACE>
inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)
    : BpRefBase(remote)
{
}

//将参数new BpBinder(0)赋给mRemote变量,ServiceManager通过mRemote在Binder中addService或getService
BpRefBase::BpRefBase(const sp<IBinder>& o)
    : mRemote(o.get()), mRefs(NULL), mState(0)
{
    extendObjectLifetime(OBJECT_LIFETIME_WEAK);

    if (mRemote) {
        mRemote->incStrong(this);           // Removed on first IncStrong().
        mRefs = mRemote->createWeak(this);  // Held for our entire lifetime.
    }
}

根据上述代码可知IServiceManager ::asInterface(obj)即创建一个BpServiceManager对象。

到这里defaultServiceManager = new BpServiceManager(new BpBinder(0));

总结一下,defaultServiceManager就是使用new BpBinder(0)来创建BpServiceManager对象,new BpBinder(0)赋给mRemote变量,当Binder server端调用ServiceManager::addService注册服务时,也就是使用remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);来与Binder驱动程序进行交互,remote()方法即返回mRemote变量。

remote()函数在BpRefBase类中定义

作者:lb377463323
出处:http://blog.csdn.net/lb377463323
原文链接:http://blog.csdn.net/lb377463323/article/details/78275730
转载请注明出处!

猜你喜欢

转载自blog.csdn.net/lb377463323/article/details/78275730