为了更好的理解过程,我们挑选Native中的MediaServer进行分析。
@init.rc(google-code\system\core\rootdir\init.rc) service media /system/bin/mediaserver class main user media group audio camera inet net_bt net_bt_admin net_bw_acct drmrpc ioprio rt 4这个脚本包含了几个重要信息:
@Android.mk(google-code\frameworks\av\media\mediaserver\) LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_SRC_FILES:= main_mediaserver.cpp LOCAL_MODULE:= mediaserver在这个脚本中,将main_mediaserver.cpp加载为mediaserver模块,因此,main_mediaserver.cpp文件就是我们要找的入口文件,而这个文件中的main函数就是我们要找的入口函数:
@main_mediaserver.cpp int main(int argc, char** argv) { sp<ProcessState> proc(ProcessState::self()); //得到ServiceManager sp<IServiceManager> sm = defaultServiceManager(); //三个Service自身的初始化 AudioFlinger::instantiate(); MediaPlayerService::instantiate(); CameraService::instantiate(); AudioPolicyService::instantiate(); ProcessState::self()->startThreadPool(); IPCThreadState::self()->joinThreadPool(); }
下面我们就来详细看一下整个Service启动的流程。
@ProcessState.cpp(google-code\frameworks\native\libs\binder\) sp<ProcessState> ProcessState::self() { if (gProcess != NULL) return gProcess; AutoMutex _l(gProcessMutex); if (gProcess == NULL) gProcess = new ProcessState; return gProcess; }这里我们看到, ProcessState是一个单例模式,所有的进程共享同一个ProcessState对象。如果初始化过了(gProcess!=NULL),就直接返回给客户端使用即可,没有的话需要创建ProcessState对象。这里我们假设当前没有被初始化过,那么就会调用他的构造函数:
ProcessState::ProcessState() : mDriverFD(open_driver()) , mVMStart(MAP_FAILED) , mManagesContexts(false) , mBinderContextCheckFunc(NULL) , mBinderContextUserData(NULL) , mThreadPoolStarted(false) , mThreadPoolSeq(1) { if (mDriverFD >= 0) { //映射内存 mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0); if (mVMStart == MAP_FAILED) { close(mDriverFD); mDriverFD = -1; } } }在他的初始化过程中,主要完成了两个重要步骤:
由此,就完成了ProcessState的初始化工作。
sp<IServiceManager> sm = defaultServiceManager();那么是如何得到ServiceManager对象呢?得到的对象就是ServiceManager本身吗?我们从代码中找答案。
@IServiceManager.cpp(google-code\frameworks\native\libs\binder\) sp<IServiceManager> defaultServiceManager() { if (gDefaultServiceManager != NULL) return gDefaultServiceManager; AutoMutex _l(gDefaultServiceManagerLock); if (gDefaultServiceManager == NULL) { //得到ServiceManager gDefaultServiceManager = interface_cast<IServiceManager>( ProcessState::self()->getContextObject(NULL)); } return gDefaultServiceManager; }这里我们发现,defaultServiceManager()也是单例模式,就是说,如果其他Service已经申请到了ServiceManager,其他Service就可以直接使用,这里我们假设是第一次申请,那么就要通过下面方法申请:
gDefaultServiceManager = interface_cast<IServiceManager>( ProcessState::self()->getContextObject(NULL));这个步骤稍微复杂,我们拆开分析:
ProcessState::self()->getContextObject(NULL) interface_cast<IServiceManager>()
上面第一步可以得到ServiceManager的BpBinder对象,第二步把得到的BpBinder对象转换为IServiceManager对象,下面我们逐步分析这两个过程。
ProcessState::self()->getContextObject(NULL)在第二节中我们介绍过,ProcessState::self()的过程就是完成ProcessState的初始化,然后返回ProcessState对象,因此,上面的代码相当于:
ProcessState->getContextObject(NULL);我们来看这个过程:
@ProcessState.cpp sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& caller) { return getStrongProxyForHandle(0); }继续看getStrongProxyForHandle(),记住,传递下去的参数为0:
sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle) { sp<IBinder> result; //从数组中查找handle_entry,不存在的话就创建一个 handle_entry* e = lookupHandleLocked(handle); if (e != NULL) { IBinder* b = e->binder; if (b == NULL || !e->refs->attemptIncWeak(this)) { //new一个BpBinder返回给调用者 b = new BpBinder(handle); e->binder = b; if (b) e->refs = b->getWeakRefs(); result = b; } else { result.force_set(b); e->refs->decWeak(this); } } return result; }在这一步中,要先通过lookupHandleLocked()去查找当前handle的handle_entry对象,如果没有找到的话就会创建一个handle_entry,用于后续的Service使用,而且新建的handle_entry的binder变量为空,当前我们假设得到的就是新建的handle_entry对象,那么由于其e->binder为空,因此将会new一个BpBinder的对象作为其binder变量。
sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle) { return new BpBinder(handle); }也就是说, 我们通过getStrongProxyForHandle()得到的就是BpBinder对象,不仅如此,而且我们得到的是 handle为0的BpBinder对象。
ProcessState::self()->getContextObject(NULL)我们得到的是BpBinder(0)的对象。
下面我们来看如何将这个对象转换为ServiceManager对象。
gDefaultServiceManager = interface_cast<IServiceManager>( ProcessState::self()->getContextObject(NULL));转换为:
gDefaultServiceManager = interface_cast<IServiceManager>(BpBinder(0));下面我们来分析interface_cast是如何将BpBinder对象进行转换的。
@IInterface.h(google-code\frameworks\native\include\binder\) template<typename INTERFACE> inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj) { return INTERFACE::asInterface(obj); }这里要补充一下函数模版的知识。上面这个函数组成了一个标准的函数模版功能。
gDefaultServiceManager = interface_cast<IServiceManager>(BpBinder(0));其实包含了4个信息:
sp<IServiceManager> interface_cast(const sp<IBinder>& obj) { return IServiceManager::asInterface(obj); }这里要求asInterface的参数obj是IBinder,而我们前面分析过我们得到的BpBinder对象就是IBinder类型的ServiceManager。因此,当初的:
gDefaultServiceManager = interface_cast<IServiceManager>(BpBinder(0));将会等价于:
gDefaultServiceManager = IServiceManager::asInterface(BpBinder(0));下面我们来看IServiceManager的asInterface()函数。
@IServiceManager.h class IServiceManager : public IInterface { DECLARE_META_INTERFACE(ServiceManager); };我们查看这个宏控的定义:
@IInterface.h(google-code\frameworks\native\include\binder\) #define DECLARE_META_INTERFACE(INTERFACE) \ static const android::String16 descriptor; \ static android::sp<I##INTERFACE> asInterface( \ const android::sp<android::IBinder>& obj); \ virtual const android::String16& getInterfaceDescriptor() const; \ I##INTERFACE(); \ virtual ~I##INTERFACE();这是一个宏定义可以看出,其中的asInterface()函数被宏定义为了:
static android::sp<I##INTERFACE> asInterface(const android::sp<android::IBinder>& obj);替换掉INTERFACE可以得到:
static android::sp<IServiceManager> asInterface(const android::sp<android::IBinder>& obj);也就是说,这段宏声明了asInterface函数,但是asInterface的定义呢?
#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME) \ const android::String16 I##INTERFACE::descriptor(NAME); \ const android::String16& \ I##INTERFACE::getInterfaceDescriptor() const { \ return I##INTERFACE::descriptor; \ } \ 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); \ } \ } \ return intr; \ } \ I##INTERFACE::I##INTERFACE() { } \ I##INTERFACE::~I##INTERFACE() { }这里面就包含了asInterface的定义:
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); \ } \ } \ return intr; \ } \同样的,我们替换掉INTERFACE,得到如下真实的定义:
android::sp<IServiceManager> IServiceManager::asInterface( const android::sp<android::IBinder>& obj) { android::sp<IServiceManager> intr; if (obj != NULL) { intr = static_cast<IServiceManager*>(obj->queryLocalInterface(IServiceManager::descriptor).get()); if (intr == NULL) { intr = new BpServiceManager(obj); } } return intr; }
也就是说,经过函数模版的转换,我们得到的是BpServiceManager对象。而且初始化该对象时,我们传递了BpBinder(0)。
class BpServiceManager : public BpInterface<IServiceManager> { }这说明BpInterface继承自BpInterface这个类模版(作用与函数模版类似)
template<typename INTERFACE> class BpInterface : public INTERFACE, public BpRefBase { };替换掉INTERFACE后得到:
class BpInterface : public IServiceManager, public BpRefBase { };说明BpInterface继承了两个父类:IServiceManager和BpRefBase。
@IServiceManager.cpp BpServiceManager(const sp<IBinder>& impl) : BpInterface<IServiceManager>(impl) { }构造函数中会用BpBinder(0)初始化其父类BpInterface,我们来看其父类的构造函数:
template<typename INTERFACE> inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote) : BpRefBase(remote) { }这又是一个函数模版,其相当于:
inline BpInterface<IServiceManager>::BpInterface(const sp<IBinder>& remote) : BpRefBase(remote) { }我们看到,BpInterface的构造函数中又用BpBinder(0)去初始化其父类BpRefBase对象:
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. } }在这里,我们又把BpBinder(0)这个对象传递给了BpRefBase对象的mRemote变量(并且增加这个对象的(指针的)强引用计数,这已属于SP/WP智能指针的知识范畴,我们不做详细分析)。
class IServiceManager : public IInterface { public: //这个宏定义已经分析过,其中包含asInterface的信息 DECLARE_META_INTERFACE(ServiceManager); //得到一个Service virtual sp<IBinder> getService( const String16& name) const = 0; //检测Service virtual sp<IBinder> checkService( const String16& name) const = 0; //添加一个Service virtual status_t addService( const String16& name, const sp<IBinder>& service, bool allowIsolated = false) = 0; virtual Vector<String16> listServices() = 0; enum { GET_SERVICE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION, CHECK_SERVICE_TRANSACTION, ADD_SERVICE_TRANSACTION, LIST_SERVICES_TRANSACTION, }; };然后我们来看BpServiceManager的定义:
class BpServiceManager : public BpInterface<IServiceManager> { virtual sp<IBinder> getService(const String16& name) const{} virtual sp<IBinder> checkService( const String16& name) const{} virtual status_t addService(const String16& name, const sp<IBinder>& service, bool allowIsolated){} virtual Vector<String16> listServices(){} };正如我们所料,BpServiceManager确实实现了这些方法。通过这些方法,我们就可以对ServiceManager这一Service发送各种请求,比如得到、检查、添加一个Service。
下面用一张图来总结一下得到ServiceManager代理对象的过程:
@IServiceManager.cpp virtual status_t addService(const String16& name, const sp<IBinder>& service, bool allowIsolated) { Parcel data, reply; data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor()); data.writeString16(name); data.writeStrongBinder(service); data.writeInt32(allowIsolated ? 1 : 0); status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply); return err == NO_ERROR ? reply.readExceptionCode() : err; }我们看到,在ADD_SERVICE_TRANSACTION中,把要添加的Service的名字和IBinder对象放入Parcel类型的data中,然后调用remote()函数发送出去,同时标记当前数据的作用是ADD_SERVICE_TRANSACTION。
@Binder.h inline IBinder* remote() { return mRemote; }原来remote()在内部把mRemote返回了出来。
BpBinder(0)->transact()现在我们再回到BpBinder中继续分析:
@BpBinder.cpp status_t BpBinder::transact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { if (mAlive) { //转移到IPCThreadState中的transact status_t status = IPCThreadState::self()->transact( mHandle, code, data, reply, flags); if (status == DEAD_OBJECT) mAlive = 0; return status; } return DEAD_OBJECT; }在这里又把transact()转移到了IPCThreadState中的transact(),并且 此时的handle为0:
status_t IPCThreadState::transact(int32_t handle,uint32_t code,const Parcel& data,Parcel* reply,uint32_t flags) { status_t err = data.errorCheck(); flags |= TF_ACCEPT_FDS; if (err == NO_ERROR) { //封装数据 err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL); } if ((flags & TF_ONE_WAY) == 0) { if (reply) { err = waitForResponse(reply); } else { Parcel fakeReply; err = waitForResponse(&fakeReply); } } else { err = waitForResponse(NULL, NULL); } return err; }在transact()中,先通过errorCheck()检查数据错误信息,然后通过writeTransactionData()封装数据,最后通过waitForResponse()把数据发送出去。
status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags, int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer) { binder_transaction_data tr; tr.target.handle = handle; tr.code = code; tr.flags = binderFlags; tr.cookie = 0; tr.sender_pid = 0; tr.sender_euid = 0; //错误检测 const status_t err = data.errorCheck(); if (err == NO_ERROR) { tr.data_size = data.ipcDataSize(); tr.data.ptr.buffer = data.ipcData(); tr.offsets_size = data.ipcObjectsCount()*sizeof(size_t); tr.data.ptr.offsets = data.ipcObjects(); } else if (statusBuffer) { tr.flags |= TF_STATUS_CODE; *statusBuffer = err; tr.data_size = sizeof(status_t); tr.data.ptr.buffer = statusBuffer; tr.offsets_size = 0; tr.data.ptr.offsets = NULL; } else { return (mLastError = err); } //这里的cmd内容是BC_TRANSACTION mOut.writeInt32(cmd); mOut.write(&tr, sizeof(tr)); return NO_ERROR; }原来,数据封装的结果就是把在mOut中写入两个数据:命令和内容。在这里,命令就是BC_TRANSACTION,而数据就是“addService”。
status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult) { int32_t cmd; while (1) { //发送数据 if ((err=talkWithDriver()) < NO_ERROR) break; //检测接收的数据有效性 err = mIn.errorCheck(); if (err < NO_ERROR) break; if (mIn.dataAvail() == 0) continue; //得到返回数据的内容 cmd = mIn.readInt32(); //根据返回命令做不同处理 switch (cmd) { case BR_TRANSACTION_COMPLETE: case BR_DEAD_REPLY: case BR_FAILED_REPLY: case BR_ACQUIRE_RESULT: case BR_REPLY: default: } } return err; }发送数据是通过talkWithDriver()来完成的:
@IPCThreadState.cpp status_t IPCThreadState::talkWithDriver(bool doReceive) { binder_write_read bwr; const bool needRead = mIn.dataPosition() >= mIn.dataSize(); const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0; //准备写入的数据 bwr.write_size = outAvail; bwr.write_buffer = (long unsigned int)mOut.data(); if (doReceive && needRead) { //准备要读取的数据 bwr.read_size = mIn.dataCapacity(); bwr.read_buffer = (long unsigned int)mIn.data(); } else { bwr.read_size = 0; bwr.read_buffer = 0; } bwr.write_consumed = 0; bwr.read_consumed = 0; status_t err; do { //通过ioctl发送和接收数据 if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0) err = NO_ERROR; else err = -errno; } while (err == -EINTR); if (err >= NO_ERROR) { if (bwr.write_consumed > 0) { //清空mOut if (bwr.write_consumed < (ssize_t)mOut.dataSize()) mOut.remove(0, bwr.write_consumed); else mOut.setDataSize(0); } //把返回值放入mIn中 if (bwr.read_consumed > 0) { mIn.setDataSize(bwr.read_consumed); mIn.setDataPosition(0); } return NO_ERROR; } return err; }我们看到,在talkWithDriver()中构建了binder_write_read类型的数据,并把要写入的命令从mOut拿出放入write_buffer中,并准备read_buffer用来接收数据。最终通过ioctl()的方式与远程Binder进行数据交互。
virtual sp<IBinder> getService(const String16& name) const { unsigned n; for (n = 0; n < 5; n++){ //调用了checkService() sp<IBinder> svc = checkService(name); if (svc != NULL) return svc; sleep(1); } return NULL; }继续看checkService()过程:
virtual sp<IBinder> checkService( const String16& name) const { Parcel data, reply; data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor()); data.writeString16(name); //传输数据 remote()->transact(CHECK_SERVICE_TRANSACTION, data, &reply); //得到回应 return reply.readStrongBinder(); }我们看到,整个过程和addService()的类型是极其相似的,不同的是,在调用remote()的transact()时发送的是CHECK_SERVICE_TRANSACTION命令。而且在transact()函数之后,我们从reply中读取了返回值。而这个返回值就是我们要得到的远程Service的IBinder对象。
int main(int argc, char** argv) { //ProcessState初始化 sp<ProcessState> proc(ProcessState::self()); //得到ServiceManager的IServiceManager对象 sp<IServiceManager> sm = defaultServiceManager(); AudioFlinger::instantiate(); MediaPlayerService::instantiate(); CameraService::instantiate(); AudioPolicyService::instantiate(); ProcessState::self()->startThreadPool(); IPCThreadState::self()->joinThreadPool(); }在前面的分析过程中,我们完成了ProcessState的初始化、并得到了ServiceManager的代理对象BpServiceManager,接下来是对AudioFlinger、MediaPlayerService、CameraService、AudioFlinger四个服务的初始化过程,由于这些Service本身不属于本文讨论的范围,因此我们挑选MediaPlayerService来简要看一下其初始化的流程。
@MediaPlayerService.cpp(google-code\frameworks\av\media\libmediaplayerservice\) void MediaPlayerService::instantiate() { defaultServiceManager()->addService( String16("media.player"), new MediaPlayerService()); }我们看到,MediaPlayerService初始化的过程就是把自己注册为"media.player"Service的过程,同时把MediaPlayerService对象传递给ServiceManager。
class MediaPlayerService : public BnMediaPlayerService{}上面的继承关系说明,MediaPlayerService是BnMediaPlayerService的子类,我们再来看BnMediaPlayerService的属性:
class BnMediaPlayerService: public BnInterface<IMediaPlayerService>{}然后看BnInterface模版的定义:
@IInterface.h template<typename INTERFACE> class BnInterface : public INTERFACE, public BBinder { };从继承关系上我们看出,BnInterface模版实现了双继承,其同时继承了BBinder和INTERFACE,而BBinder就是IBinder的子类:
class BBinder : public IBinder{}
也就是说,作为一个Service,向ServiceManager注册自己时,需要把继承自IXXXService和BBinder的传递给ServiceManager,注册完自己,Service就需要搭建自己的循环机制去检测客户端的请求了。
ProcessState::self()->startThreadPool(); IPCThreadState::self()->joinThreadPool();我们先来看一下ProcessState的startThreadPool()方法:
@ProcessState.cpp void ProcessState::startThreadPool() { AutoMutex _l(mLock); if (!mThreadPoolStarted) { mThreadPoolStarted = true; spawnPooledThread(true); } }我们来看spawnPooledThread(),需要注意,传进去的参数为true:
void ProcessState::spawnPooledThread(bool isMain) { if (mThreadPoolStarted) { int32_t s = android_atomic_add(1, &mThreadPoolSeq); char buf[16]; snprintf(buf, sizeof(buf), "Binder_%X", s); sp<Thread> t = new PoolThread(isMain); t->run(buf); } }在spawnPooledThread()中创建了一个线程(PoolThread)并运行,我们来看这个线程:
@ProcessState.cpp class PoolThread : public Thread { public: PoolThread(bool isMain) : mIsMain(isMain) { } protected: virtual bool threadLoop() { IPCThreadState::self()->joinThreadPool(mIsMain); return false; } const bool mIsMain; };这里可以看到,在startThreadPool()的内部,创建了一个新的线程,并在线程中调用IPCThreadState的joinThreadPool()方法。而在main函数的最后也是调用的IPCThreadState的joinThreadPool()方法,这就说明,搭建消息检测机制是在IPCThreadState的joinThreadPool()中实现的,下面我们就来看其具体过程。
@IPCThreadState.cpp(google-code\frameworks\native\libs\binder\) IPCThreadState* IPCThreadState::self() { //第一次调用gHaveTLS为false if (gHaveTLS) { restart: const pthread_key_t k = gTLS; //当前线程再次获取IPCThreadState时,可以用key取出当前线程的IPCThreadState对象 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k); if (st) return st; return new IPCThreadState; } if (gShutdown) return NULL; pthread_mutex_lock(&gTLSMutex); if (!gHaveTLS) { //创建当前线程的key if (pthread_key_create(&gTLS, threadDestructor) != 0) { pthread_mutex_unlock(&gTLSMutex); return NULL; } gHaveTLS = true; } pthread_mutex_unlock(&gTLSMutex); goto restart; }再来看其构造函数:
IPCThreadState::IPCThreadState() : mProcess(ProcessState::self()), mMyThreadId(androidGetTid()), mStrictModePolicy(0), mLastTransactionBinderFlags(0) { //把当前的IPCThreadState对象保存在key中 pthread_setspecific(gTLS, this); clearCaller(); mIn.setDataCapacity(256); mOut.setDataCapacity(256); }从上面初始化流程中可以看出IPCThreadState是单例模式。简要来说,一个线程第一次调用IPCThreadState时,由于gHaveTLS变量为false,因此会通过pthread_key_create创建当前线程的key,并在IPCThreadState的构造函数中,把当前new出来的IPCThreadState对象保存在key中,下次当前线程再调用IPCThreadState时,可以通过key将IPCThreadState对象取出来使用,以保证同一个线程只能拥有一份IPCThreadState对象。
@IPCThreadState.cpp void IPCThreadState::joinThreadPool(bool isMain) { //向Binder驱动发送命令,要进入/注册 Loop状态了 mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER); status_t result; do { int32_t cmd; //清除接收缓存,准备接收数据 if (mIn.dataPosition() >= mIn.dataSize()) { size_t numPending = mPendingWeakDerefs.size(); if (numPending > 0) { for (size_t i = 0; i < numPending; i++) { RefBase::weakref_type* refs = mPendingWeakDerefs[i]; refs->decWeak(mProcess.get()); } mPendingWeakDerefs.clear(); } numPending = mPendingStrongDerefs.size(); if (numPending > 0) { for (size_t i = 0; i < numPending; i++) { BBinder* obj = mPendingStrongDerefs[i]; obj->decStrong(mProcess.get()); } mPendingStrongDerefs.clear(); } } //与Binder交换数据,发送命令并读取返回值 result = talkWithDriver(); if (result >= NO_ERROR) { size_t IN = mIn.dataAvail(); if (IN < sizeof(int32_t)) continue; cmd = mIn.readInt32(); //处理返回值 result = executeCommand(cmd); } if(result == TIMED_OUT && !isMain) { break; } } while (result != -ECONNREFUSED && result != -EBADF); //退出Loop状态 mOut.writeInt32(BC_EXIT_LOOPER); talkWithDriver(false); }在上面这个过程中,主要执行逻辑在于while-do循环中,在这个循环体中,先清除接收缓存,然后通过talkWithDriver向Binder发送/接收数据,最后再去解析(executeCommand)得到的返回值。而在进入while-do之前,需要告诉Binder自己需要进入/注册Loop状态,并在while-do之后,告诉Binder自己退出了Loop的状态。
status_t IPCThreadState::talkWithDriver(bool doReceive) { //确认Binder已经打开 if (mProcess->mDriverFD <= 0) { return -EBADF; } binder_write_read bwr; const bool needRead = mIn.dataPosition() >= mIn.dataSize(); const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0; bwr.write_size = outAvail; bwr.write_buffer = (long unsigned int)mOut.data(); if (doReceive && needRead) { //准备接收缓存 bwr.read_size = mIn.dataCapacity(); bwr.read_buffer = (long unsigned int)mIn.data(); } else { bwr.read_size = 0; bwr.read_buffer = 0; } if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR; bwr.write_consumed = 0; bwr.read_consumed = 0; status_t err; do { //通过ioctl()与Binder交换数据 if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0) err = NO_ERROR; else err = -errno; if (mProcess->mDriverFD <= 0) { err = -EBADF; } } while (err == -EINTR); if (err >= NO_ERROR) { if (bwr.write_consumed > 0) { if (bwr.write_consumed < (ssize_t)mOut.dataSize()) mOut.remove(0, bwr.write_consumed); else mOut.setDataSize(0); } //将接收数据放入mIn中 if (bwr.read_consumed > 0) { mIn.setDataSize(bwr.read_consumed); mIn.setDataPosition(0); } return NO_ERROR; } return err; }整个数据交换过程还是比较清晰的,就是通过ioctl()来完成的。下面来看数据的处理过程,其要处理的数据是放在mIn中的。
status_t IPCThreadState::executeCommand(int32_t cmd) { BBinder* obj; RefBase::weakref_type* refs; status_t result = NO_ERROR; switch (cmd) { case BR_ERROR: break; case BR_OK: break; case BR_ACQUIRE: break; case BR_RELEASE: break; case BR_INCREFS: break; case BR_DECREFS: break; case BR_ATTEMPT_ACQUIRE: break; case BR_TRANSACTION: break; case BR_DEAD_BINDER: break; case BR_CLEAR_DEATH_NOTIFICATION_DONE: break; case BR_FINISHED: break; case BR_NOOP: break; case BR_SPAWN_LOOPER: break; default: break; } return result; }这里的分支分为两个重要的部分,一部分是BR_ACQUIRE、BR_RELEASE、BR_INCREFS、BR_DEAD_BINDER四个消息,主要作用是通过调用相应对象的incStrong、incWeak等方法添加或减少相应智能指针的引用计数。
status_t IPCThreadState::executeCommand(int32_t cmd) { BBinder* obj; RefBase::weakref_type* refs; status_t result = NO_ERROR; switch (cmd) { case BR_ERROR: break; case BR_OK: break; case BR_ACQUIRE: break; case BR_RELEASE: break; case BR_INCREFS: break; case BR_DECREFS: break; case BR_ATTEMPT_ACQUIRE: break; case BR_TRANSACTION: { binder_transaction_data tr; //读取从Binder驱动得到的客户端请求数据,并放到tr中 result = mIn.read(&tr, sizeof(tr)); if (result != NO_ERROR) break; Parcel buffer; //将tr数据封装到Parcel型的buffer中 buffer.ipcSetDataReference( reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer), tr.data_size, reinterpret_cast<const size_t*>(tr.data.ptr.offsets), tr.offsets_size/sizeof(size_t), freeBuffer, this); const pid_t origPid = mCallingPid; const uid_t origUid = mCallingUid; //记录当前客户端的进程信息 mCallingPid = tr.sender_pid; mCallingUid = tr.sender_euid; int curPrio = getpriority(PRIO_PROCESS, mMyThreadId); if (gDisableBackgroundScheduling) { if (curPrio > ANDROID_PRIORITY_NORMAL) { //设置线程优先级 setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL); } } else { if (curPrio >= ANDROID_PRIORITY_BACKGROUND) { set_sched_policy(mMyThreadId, SP_BACKGROUND); } } Parcel reply; if (tr.target.ptr) { sp<BBinder> b((BBinder*)tr.cookie); //把数据转交给相应Service const status_t error = b->transact(tr.code, buffer, &reply, tr.flags); if (error < NO_ERROR) reply.setError(error); } else { const status_t error = the_context_object->transact(tr.code, buffer, &reply, tr.flags); if (error < NO_ERROR) reply.setError(error); } if ((tr.flags & TF_ONE_WAY) == 0) { sendReply(reply, 0); } else { LOG_ONEWAY("NOT sending reply to %d!", mCallingPid); } mCallingPid = origPid; mCallingUid = origUid; } break; default: break; } return result; }在这个过程中,我们发现IPCThreadState把从mIn读取的tr型数据重新封装到Parcel类型的buffer中之后,调用目标Service的BBinder对象的transact()函数将数据转交给相应的Service。
defaultServiceManager()->addService(String16("media.player"), new MediaPlayerService());从上面的我们看到在调用addService()时,把MediaPlayerService对象传递给了ServiceManager,并且在第五节中分析过,这个MediaPlayerService对象的本质是IMediaPlayerService和BBinder的子类,因此这里得到的BBinder就是MediaPlayerService的父类对象。
3、while循环中得到请求后,调用executeCommand将客户端请求重新打包成Parcel数据发送给Service的BBinder对象。
@Binder.cpp(google-code\frameworks\native\libs\binder\) status_t BBinder::transact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { data.setDataPosition(0); status_t err = NO_ERROR; switch (code) { case PING_TRANSACTION: reply->writeInt32(pingBinder()); break; default: //调用onTransact方法 err = onTransact(code, data, reply, flags); break; } if (reply != NULL) { reply->setDataPosition(0); } return err; }在transact()内部调用了onTransact()的方法,而这里的onTransact()方法被BBinder的子类BnMediaPlayerService所实现:
@IMediaPlayerService.cpp(google-code\frameworks\av\media\libmedia\) status_t BnMediaPlayerService::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch (code) { case CREATE: { } break; case DECODE_URL: { } break; case DECODE_FD: { } break; case CREATE_MEDIA_RECORDER: { } break; case CREATE_METADATA_RETRIEVER: { } break; case GET_OMX: { } break; case MAKE_CRYPTO: { } break; case MAKE_HDCP: { } break; case ADD_BATTERY_DATA: { } break; case PULL_BATTERY_DATA: { } break; case LISTEN_FOR_REMOTE_DISPLAY: { } break; default: return BBinder::onTransact(code, data, reply, flags); } }至此,BBinder对象就把对Service的请求发送给了BnMediaPlayerService,接下来我们挑选一个case继续跟踪:
status_t BnMediaPlayerService::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch (code) { case CREATE: { //权限检查 CHECK_INTERFACE(IMediaPlayerService, data, reply); //得到调用者的pid pid_t pid = data.readInt32(); sp<IMediaPlayerClient> client = interface_cast<IMediaPlayerClient>(data.readStrongBinder()); int audioSessionId = data.readInt32(); //调用create() sp<IMediaPlayer> player = create(pid, client, audioSessionId); reply->writeStrongBinder(player->asBinder()); return NO_ERROR; } break; } }在CREATE分支的内部,调用了create()方法,由于MediaPlayerService是BnMediaPlayerService的子类,因此create()方法是在BnMediaPlayerService中实现的:
@MediaPlayerService.cpp(google-code\frameworks\av\media\libmediaplayerservice\) sp<IMediaPlayer> MediaPlayerService::create(pid_t pid, const sp<IMediaPlayerClient>& client, int audioSessionId) { int32_t connId = android_atomic_inc(&mNextConnId); //创建客户端对象 sp<Client> c = new Client(this,pid,connId,client,audioSessionId,IPCThreadState::self()->getCallingUid()); //把客户端对象返回给申请者 return c; }在create()内部,MediaPlayerService将会常见一个client的对象返回给申请者。
也就是说,一个客户端是如何把请求发送到Binder驱动呢?
@stream.cpp(google-code\frameworks\av\cmds\stagefright\stream.cpp) int main(int argc, char **argv) { sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder = sm->getService(String16("media.player")); sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder); sp<IMediaPlayer> player = service->create(getpid(), client, 0); }在这个main中,通过getService()得到了MediaPlayerService的远程代理对象binder,然后经过interface_cast模版转换成IMediaPlayer类型的service,最后调用其create()方法。
2、调用代理对象service的方法,是如何发送到binder驱动的?
sp<IBinder> binder = sm->getService(String16("media.player")); sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);下面我们先来看一下通过ServiceManager的getService()方法得到的binder对象究竟是什么属性。
@IServiceManager.cpp virtual sp<IBinder> getService(const String16& name) const { unsigned n; for (n = 0; n < 5; n++){ //调用checkService()方法 sp<IBinder> svc = checkService(name); if (svc != NULL) return svc; sleep(1); } return NULL; }在getService()的内部调用了checkService()方法,并把返回值给了客户端,来看checkService():
virtual sp<IBinder> checkService( const String16& name) const { Parcel data, reply; data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor()); data.writeString16(name); //调用ServiceManager的CHECK_SERVICE_TRANSACTION命令 remote()->transact(CHECK_SERVICE_TRANSACTION, data, &reply); return reply.readStrongBinder(); }我们看到,客户端得到的对象需要经过两步:
@service_manager.c int svcmgr_handler(struct binder_state *bs,struct binder_txn *txn,struct binder_io *msg,struct binder_io *reply){ switch(txn->code) { case SVC_MGR_GET_SERVICE: case SVC_MGR_CHECK_SERVICE: s = bio_get_string16(msg, &len); //查找目标Service ptr = do_find_service(bs, s, len, txn->sender_euid); if (!ptr) break; //构建返回值 bio_put_ref(reply, ptr); return 0; case SVC_MGR_ADD_SERVICE: case SVC_MGR_LIST_SERVICES: default: } return 0; }我们看到,对于“得到一个Service”这样的请求,ServiceManager会先通过do_find_service()去查找目标Service,然后通过bio_put_ref()构建返回值,我们直接来看其构建的返回值:
@binder.c void bio_put_ref(struct binder_io *bio, void *ptr) { struct binder_object *obj; if (ptr) //分配结构体内存 obj = bio_alloc_obj(bio); else obj = bio_alloc(bio, sizeof(*obj)); if (!obj) return; obj->flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS; //标记类型为BINDER_TYPE_HANDLE obj->type = BINDER_TYPE_HANDLE; obj->pointer = ptr; obj->cookie = 0; }记得,这里标记的返回值type是BINDER_TYPE_HANDLE。
@Parcel.cpp sp<IBinder> Parcel::readStrongBinder() const { sp<IBinder> val; unflatten_binder(ProcessState::self(), *this, &val); return val; }看来在Parcel中是通过unflatten_binder()去生成IBinder对象的:
status_t unflatten_binder(const sp<ProcessState>& proc, const Parcel& in, sp<IBinder>* out) { //读取ServiceManager给出的返回值 const flat_binder_object* flat = in.readObject(false); if (flat) { switch (flat->type) { case BINDER_TYPE_BINDER: *out = static_cast<IBinder*>(flat->cookie); return finish_unflatten_binder(NULL, *flat, in); case BINDER_TYPE_HANDLE: //在ServiceManager构建返回值时用的就是这个type *out = proc->getStrongProxyForHandle(flat->handle); return finish_unflatten_binder( static_cast<BpBinder*>(out->get()), *flat, in); } } return BAD_TYPE; }在Parcel解析ServiceManager返回值的过程中,需要根据返回值的类型去做不同的操作,我们在7.1.1的bio_put_ref()方法中看到,当初标记的type是BINDER_TYPE_HANDLE,因此Parcel将会利用ProcessState继续解析返回值:
@ProcessState.cpp sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle) { sp<IBinder> result; //先去查找,看有没有目标Service的缓存 handle_entry* e = lookupHandleLocked(handle); if (e != NULL) { IBinder* b = e->binder; if (b == NULL || !e->refs->attemptIncWeak(this)) { //看到了吧,客户端得到的是IBinder对象其实就是BpBinder对象 b = new BpBinder(handle); e->binder = b; if (b) e->refs = b->getWeakRefs(); result = b; } else { result.force_set(b); e->refs->decWeak(this); } } return result; }到这里,我们终于找到了客户端得到的IBinder类型数据,就是BpBinder对象!
现在我们得到了IBinder类型的BpBinder对象,但是客户端拿到这个对象还不能直接调用到相应Service的方法,需要经过interface_cast的转换才可以使用。并且这个函数模版在3.2节已经介绍的很清晰,经过interface_cast的转换,我们将会得到相应的BpXXXService对象。对于当前环境来说,得到的就是BpMediaPlayerService对象。
@IMediaPlayerService.cpp(google-code\frameworks\av\media\libmedia\IMediaPlayerService.cpp) virtual sp<IMediaPlayer> create( pid_t pid, const sp<IMediaPlayerClient>& client, int audioSessionId) { Parcel data, reply; data.writeInterfaceToken(IMediaPlayerService::getInterfaceDescriptor()); data.writeInt32(pid); data.writeStrongBinder(client->asBinder()); data.writeInt32(audioSessionId); //调用BpBinder的transact() remote()->transact(CREATE, data, &reply); return interface_cast<IMediaPlayer>(reply.readStrongBinder()); }这里我们再次强调,客户端得到BpMediaPlayerService对象之后,无论调用其任何方法,都将会被封装为Parcel类型的数据,然后用remote()->transact()这种形式发送,并通过transact()不同参数来区分不同的方法,而且这里的remote()就是相应的BpBinder对象。