Android源码之Binder(五)

Service组件在启动时,需要将自己注册到ServiceManager中,而Client组件在使用Service组件提供的服务之前,也需要通过ServiceManager来获得Service组件的代理对象。由于ServiceManager本身也是一个Service组件,因此其他的Service组件和Client组件在使用它提供的服务之前,也需要先获得它的代理对象。

我们就来看一下ServiceManager代理对象的获取过程。

我们先来看一下Binder库中最底层的接口IServiceManager的定义:

classIServiceManager:publicIInterface

{

public:

DECLARE_META_INTERFACE(ServiceManager);

[//DECLARE_META_INTERFACE(ServiceManager)

DECLARE_META_INTERFACE是一个宏,这个宏声明了几个很重要的函数。DECLARE_META_INTERFACE定义在IInterface.h文件中,定义如下:

#defineDECLARE_META_INTERFACE(INTERFACE)\

staticconstandroid::String16descriptor;\

staticandroid::sp<I##INTERFACE>asInterface(\

constandroid::sp<android::IBinder>&obj);\

virtualconstandroid::String16&getInterfaceDescriptor()const;\

I##INTERFACE();\

virtual~I##INTERFACE();\

在DECLARE_META_INTERFACE宏中除了定义构造和析构函数之外,还定义了一个String类型的变量descriptor,表示该接口的描述。

getInterfaceDescriptor用于返回该接口的表示,也就是descriptor。

除此之外,还定义了一个asInterface函数,这个函数是干什么的呢?请各位客官向下看...

在IInterface.h文件中,还定义了一个IMPLEMENT_META_INTERFACE宏,由名字看和DECLARE_META_INTERFACE是相对应的。

IMPLEMENT_META_INTERFACE的定义如下:

#defineIMPLEMENT_META_INTERFACE(INTERFACE,NAME)\

constandroid::String16I##INTERFACE::descriptor(NAME);\

constandroid::String16&\

I##INTERFACE::getInterfaceDescriptor()const{\

returnI##INTERFACE::descriptor;\

}\

android::sp<I##INTERFACE>I##INTERFACE::asInterface(\

constandroid::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=newBp##INTERFACE(obj);\

}\

}\

returnintr;\

}\

I##INTERFACE::I##INTERFACE(){}\

I##INTERFACE::~I##INTERFACE(){}\

IMPLEMENT_META_INTERFACE宏确实是和DECLARE_META_INTERFACE对应的,连里面的函数都是一样的!

IMPLEMENT_META_INTERFACE宏最重要的是asInterface函数。我们重点分析asInterface函数:

asInterface的作用是将一个Binder接口返回一个用户定义接口(在这里就是IServiceManager):

asInterface函数的参数是一个Binder本地对象或者一个Binder代理对象。

不管传入的什么,都会先调用queryLocalInterface函数。queryLocalInterface函数其实是在IBinder接口中定义的,默认的实现如下:

sp<IInterface>IBinder::queryLocalInterface(constString16&descriptor)

{

returnNULL;

}

queryLocalInterface函数默认返回NULL,而BnInterface重写了queryLocalInterface函数,定义如下:

template<typenameINTERFACE>

inlinesp<IInterface>BnInterface<INTERFACE>::queryLocalInterface(

constString16&_descriptor)

{

if(_descriptor==INTERFACE::descriptor)returnthis;

returnNULL;

}

BnInterface的queryLocalInterface实现是将自己返回。

而BpBinder没有重写queryLocalInterface函数,所以调用BpBinder的queryLocalInterface就会返回NULL。

如果传递的是一个Binder本地对象,则可以直接调用queryLocalInterface函数后直接转换,否则就根据BpBinder构造一个BpInterface,并返回。

]//DECLARE_META_INTERFACE(ServiceManager)

/**

*Retrieveanexistingservice,blockingforafewseconds

*ifitdoesn'tyetexist.

*/

virtualsp<IBinder>getService(constString16&name)const=0;

/**

*Retrieveanexistingservice,non-blocking.

*/

virtualsp<IBinder>checkService(constString16&name)const=0;

/**

*Registeraservice.

*/

virtualstatus_taddService(constString16&name,

constsp<IBinder>&service,

boolallowIsolated=false)=0;

/**

*Returnlistofallexistingservices.

*/

virtualVector<String16>listServices()=0;

enum{

GET_SERVICE_TRANSACTION=IBinder::FIRST_CALL_TRANSACTION,

CHECK_SERVICE_TRANSACTION,

ADD_SERVICE_TRANSACTION,

LIST_SERVICES_TRANSACTION,

};

};

对于一般的Service组件来说,Client进程首先要通过Binder驱动程序来获得它的一个句柄值,然后才可以根据这个句柄值创建一个Binder代理对象,然后将这个Binder代理对象封装成一个实现了特定接口的代理对象。

由于ServiceManager的句柄值恒为0,因此,获取它的一个代理对象的过程就省去了与Binder驱动程序交互的过程。

在实际的编码中,我们一般是通过调用一个defaultServiceManager()函数来得到ServiceManagerBinder代理对象。

defaultServiceManager函数定义如下:

sp<IServiceManager>defaultServiceManager()

{

if(gDefaultServiceManager!=NULL)returngDefaultServiceManager;

[//if(gDefaultServiceManager!=NULL)returngDefaultServiceManager

gDefaultServiceManager和gDefaultServiceManagerLock是两个全局变量,保证每个进程只有一个ServiceManager对象。

这两个变量都是定义在Static.h文件中

]//if(gDefaultServiceManager!=NULL)returngDefaultServiceManager

{

AutoMutex_l(gDefaultServiceManagerLock);

if(gDefaultServiceManager==NULL){

gDefaultServiceManager=interface_cast<IServiceManager>(ProcessState::self()->getContextObject(NULL));

[//gDefaultServiceManager=interface_cast<IServiceManager>(ProcessState::self()->getContextObject(NULL));

如果gDefaultServiceManager为null,则调用ProcessState的getContextObject函数来得到ServiceManager代理对象:

getContextObject函数的定义如下:

sp<IBinder>ProcessState::getContextObject(constsp<IBinder>&caller)

{

returngetStrongProxyForHandle(0);

[//returngetStrongProxyForHandle(0)

这里调用getStrongProxyForHandle函数来查找具体的Binder代理对象,只不过传入了一个特殊参数0.

getStrongProxyForHandle函数定义如下:

sp<IBinder>ProcessState::getStrongProxyForHandle(int32_thandle)

{

sp<IBinder>result;

AutoMutex_l(mLock);

handle_entry*e=lookupHandleLocked(handle);

[//handle_entry*e=lookupHandleLocked(handle)

这里会调用lookupHandleLocked来根据句柄值查找得到一个Binder代理对象,并返回一个handle_entry结构体。

structhandle_entry{

IBinder*binder;

RefBase::weakref_type*refs;

};

lookupHandleLocked函数的定义如下:

ProcessState::handle_entry*ProcessState::lookupHandleLocked(int32_thandle)

{

constsize_tN=mHandleToObject.size();

[//constsize_tN=mHandleToObject.size()

这里的mHandleToObject保存了所有的Binder代理对象

Vector<handle_entry>mHandleToObject;

]//constsize_tN=mHandleToObject.size()

if(N<=(size_t)handle){

[//if(N<=(size_t)handle)

这里的句柄值就是在mHandleToObject的索引值

]//if(N<=(size_t)handle)

handle_entrye;

e.binder=NULL;

e.refs=NULL;

status_terr=mHandleToObject.insertAt(e,N,handle+1-N);

if(err<NO_ERROR)returnNULL;

}

return&mHandleToObject.editItemAt(handle);

}

]//handle_entry*e=lookupHandleLocked(handle)

if(e!=NULL){

//WeneedtocreateanewBpBinderifthereisn'tcurrentlyone,ORwe

//areunabletoacquireaweakreferenceonthiscurrentone.Seecomment

//ingetWeakProxyForHandle()formoreinfoaboutthis.

IBinder*b=e->binder;

if(b==NULL||!e->refs->attemptIncWeak(this)){

b=newBpBinder(handle);

[//b=newBpBinder(handle)

这里如果发现之前没有保存过该Binder代理对象,或者弱引用小于0,表示该Binder代理对象已经失效,则会创建一个新的Binder代理对象。

BpBinder类的定义如下:

classBpBinder:publicIBinder

{

public:

BpBinder(int32_thandle);

[//BpBinder(int32_thandle)

BpBinder的构造函数如下:

BpBinder::BpBinder(int32_thandle)

:mHandle(handle)

[//mHandle(handle)

这里mHandle就保存了Service组件的句柄值。

]//mHandle(handle)

,mAlive(1)

,mObitsSent(0)

,mObituaries(NULL)

{

ALOGV("CreatingBpBinder%phandle%d\n",this,mHandle);

extendObjectLifetime(OBJECT_LIFETIME_WEAK);

IPCThreadState::self()->incWeakHandle(handle);

}

]//BpBinder(int32_thandle)

inlineint32_thandle()const{returnmHandle;}

virtualconstString16&getInterfaceDescriptor()const;

virtualboolisBinderAlive()const;

virtualstatus_tpingBinder();

virtualstatus_tdump(intfd,constVector<String16>&args);

virtualstatus_ttransact(uint32_tcode,

constParcel&data,

Parcel*reply,

uint32_tflags=0);

virtualstatus_tlinkToDeath(constsp<DeathRecipient>&recipient,

void*cookie=NULL,

uint32_tflags=0);

virtualstatus_tunlinkToDeath(constwp<DeathRecipient>&recipient,

void*cookie=NULL,

uint32_tflags=0,

wp<DeathRecipient>*outRecipient=NULL);

virtualvoidattachObject(constvoid*objectID,

void*object,

void*cleanupCookie,

object_cleanup_funcfunc);

virtualvoid*findObject(constvoid*objectID)const;

virtualvoiddetachObject(constvoid*objectID);

virtualBpBinder*remoteBinder();

status_tsetConstantData(constvoid*data,size_tsize);

voidsendObituary();

classObjectManager

{

public:

ObjectManager();

~ObjectManager();

voidattach(constvoid*objectID,

void*object,

void*cleanupCookie,

IBinder::object_cleanup_funcfunc);

void*find(constvoid*objectID)const;

voiddetach(constvoid*objectID);

voidkill();

private:

ObjectManager(constObjectManager&);

ObjectManager&operator=(constObjectManager&);

structentry_t

{

void*object;

void*cleanupCookie;

IBinder::object_cleanup_funcfunc;

};

KeyedVector<constvoid*,entry_t>mObjects;

};

protected:

virtual~BpBinder();

virtualvoidonFirstRef();

virtualvoidonLastStrongRef(constvoid*id);

virtualboolonIncStrongAttempted(uint32_tflags,constvoid*id);

private:

constint32_tmHandle;

structObituary{

wp<DeathRecipient>recipient;

void*cookie;

uint32_tflags;

};

voidreportOneDeath(constObituary&obit);

boolisDescriptorCached()const;

mutableMutexmLock;

volatileint32_tmAlive;

volatileint32_tmObitsSent;

Vector<Obituary>*mObituaries;

ObjectManagermObjects;

Parcel*mConstantData;

mutableString16mDescriptorCache;

};

]//b=newBpBinder(handle)

e->binder=b;

if(b)e->refs=b->getWeakRefs();

result=b;

}else{

//Thislittlebitofnastynessistoallowustoaddaprimary

//referencetotheremoteproxywhenthisteamdoesn'thaveone

//butanotherteamissendingthehandletous.

result.force_set(b);

e->refs->decWeak(this);

}

}

returnresult;

}

]//returngetStrongProxyForHandle(0)

}

当调用getContextObject函数得到Binder代理对象之后,就可以调用interface_cast来将它转换成特定的接口

interface_cast是个全局的inline函数,定义在IInterface.h文件中,定义如下:

template<typenameINTERFACE>

inlinesp<INTERFACE>interface_cast(constsp<IBinder>&obj)

{

returnINTERFACE::asInterface(obj);

[//returnINTERFACE::asInterface(obj);

实际上就是调用asInterface函数,还记得asInterface函数么?asInterface是用IMPLEMENT_META_INTERFACE宏和DECLARE_META_INTERFACE宏实现的。详细信息见上面。

]//returnINTERFACE::asInterface(obj);

}

]//gDefaultServiceManager=interface_cast<IServiceManager>(ProcessState::self()->getContextObject(NULL));

}

}

returngDefaultServiceManager;

}

我们下面分析一下Service组件的启动过程。Service进程在启动时,会首先将自己的Service组件注册到ServiceManager中,接着就是启动Binder线程池来等待和处理Client进程的通信请求。

当我们得到了ServiceManager的代理对象之后,就会调用addService来注册Service组件。

这实际上是调用BpServiceManager类的成员函数addService来注册Service组件的,BpServiceManager的addService函数的定义如下:

virtualstatus_taddService(constString16&name,constsp<IBinder>&service,boolallowIsolated)

{

Parceldata,reply;

data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());

[//data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor())

首先调用writeInterfaceToken函数写入Service组件的描述。

//WriteRPCheaders.(previouslyjusttheinterfacetoken)

status_tParcel::writeInterfaceToken(constString16&interface)

{

writeInt32(IPCThreadState::self()->getStrictModePolicy()|STRICT_MODE_PENALTY_GATHER);

[//writeInt32(IPCThreadState::self()->getStrictModePolicy()|STRICT_MODE_PENALTY_GATHER);

]//writeInt32(IPCThreadState::self()->getStrictModePolicy()|STRICT_MODE_PENALTY_GATHER);

//currentlytheinterfaceidentificationtokenisjustitsnameasastring

returnwriteString16(interface);

[//returnwriteString16(interface)

接着调用writeString16函数来写入这个Service组件的描述。

status_tParcel::writeString16(constString16&str)

{

returnwriteString16(str.string(),str.size());

[//returnwriteString16(str.string(),str.size())

status_tParcel::writeString16(constchar16_t*str,size_tlen)

{

if(str==NULL)returnwriteInt32(-1);

status_terr=writeInt32(len);

if(err==NO_ERROR){

len*=sizeof(char16_t);

uint8_t*data=(uint8_t*)writeInplace(len+sizeof(char16_t));

if(data){

memcpy(data,str,len);

*reinterpret_cast<char16_t*>(data+len)=0;

returnNO_ERROR;

}

err=mError;

}

returnerr;

}

有writeString16函数可知,writeString16的实现原理就是先写入长度,然后拷贝数据。

]//returnwriteString16(str.string(),str.size())

}

]//returnwriteString16(interface)

}

]//data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor())

data.writeString16(name);

data.writeStrongBinder(service);

[//data.writeStrongBinder(service)

调用writeStrongBinder来写入一个Service组件。

status_tParcel::writeStrongBinder(constsp<IBinder>&val)

{

returnflatten_binder(ProcessState::self(),val,this);

[//returnflatten_binder(ProcessState::self(),val,this)

status_tflatten_binder(constsp<ProcessState>&proc,constsp<IBinder>&binder,Parcel*out)

{

flat_binder_objectobj;

obj.flags=0x7f|FLAT_BINDER_FLAG_ACCEPTS_FDS;

if(binder!=NULL){

IBinder*local=binder->localBinder();

[//IBinder*local=binder->localBinder()

localBinder函数其实是来自与BBinder类,BBinder的localBinder函数定义如下:

BBinder*BBinder::localBinder()

{

returnthis;

}

]//IBinder*local=binder->localBinder()

if(!local){

BpBinder*proxy=binder->remoteBinder();

if(proxy==NULL){

ALOGE("nullproxy");

}

constint32_thandle=proxy?proxy->handle():0;

obj.type=BINDER_TYPE_HANDLE;

obj.handle=handle;

obj.cookie=NULL;

}else{

obj.type=BINDER_TYPE_BINDER;

obj.binder=local->getWeakRefs();

[//obj.binder=local->getWeakRefs()

这里会调用getWeakRefs来返回一个Service组件的弱引用对象

]//obj.binder=local->getWeakRefs()

obj.cookie=local;

}

}else{

obj.type=BINDER_TYPE_BINDER;

obj.binder=NULL;

obj.cookie=NULL;

}

returnfinish_flatten_binder(binder,obj,out);

[//returnfinish_flatten_binder(binder,obj,out)

inlinestaticstatus_tfinish_flatten_binder(constsp<IBinder>&binder,constflat_binder_object&flat,Parcel*out)

{

returnout->writeObject(flat,false);

[//returnout->writeObject(flat,false)

status_tParcel::writeObject(constflat_binder_object&val,boolnullMetaData)

{

constboolenoughData=(mDataPos+sizeof(val))<=mDataCapacity;

constboolenoughObjects=mObjectsSize<mObjectsCapacity;

if(enoughData&&enoughObjects){

restart_write:

*reinterpret_cast<flat_binder_object*>(mData+mDataPos)=val;

//Needtowritemeta-data?

if(nullMetaData||val.binder!=NULL){

mObjects[mObjectsSize]=mDataPos;

acquire_object(ProcessState::self(),val,this);

mObjectsSize++;

}

//rememberifit'safiledescriptor

if(val.type==BINDER_TYPE_FD){

if(!mAllowFds){

returnFDS_NOT_ALLOWED;

}

mHasFds=mFdsKnown=true;

}

returnfinishWrite(sizeof(flat_binder_object));

}

if(!enoughData){

conststatus_terr=growData(sizeof(val));

if(err!=NO_ERROR)returnerr;

}

if(!enoughObjects){

size_tnewSize=((mObjectsSize+2)*3)/2;

size_t*objects=(size_t*)realloc(mObjects,newSize*sizeof(size_t));

if(objects==NULL)returnNO_MEMORY;

mObjects=objects;

mObjectsCapacity=newSize;

}

gotorestart_write;

}

]//returnout->writeObject(flat,false)

}

]//returnfinish_flatten_binder(binder,obj,out)

}

]//returnflatten_binder(ProcessState::self(),val,this)

}

]//data.writeStrongBinder(service)

data.writeInt32(allowIsolated?1:0);

status_terr=remote()->transact(ADD_SERVICE_TRANSACTION,data,&reply);

[//status_terr=remote()->transact(ADD_SERVICE_TRANSACTION,data,&reply)

这里就开始向Binder驱动程序传递数据了。

首先调用remote()函数,remote函数其实是从BpRefBase中继承来的,定义如下:

inlineIBinder*remote(){returnmRemote;}

BpRefBase类remote函数只是简单的返回成员变量mRemote,mRemote其实是个BpBinder类型的对象。因此这里调用transact实际调用的是BpBinder类的transact函数。

我们来看一下BpBinder类的transact函数的实现:

status_tBpBinder::transact(uint32_tcode,constParcel&data,Parcel*reply,uint32_tflags)

{

//Onceabinderhasdied,itwillnevercomebacktolife.

if(mAlive){

status_tstatus=IPCThreadState::self()->transact(mHandle,code,data,reply,flags);

[//status_tstatus=IPCThreadState::self()->transact(mHandle,code,data,reply,flags)

这里参数mHandle其实就是Binder本地对象的句柄值。

这里会调用IPCThreadState的transact函数来和Binder驱动进行数据交互:

status_tIPCThreadState::transact(int32_thandle,

uint32_tcode,constParcel&data,

Parcel*reply,uint32_tflags)

{

status_terr=data.errorCheck();

flags|=TF_ACCEPT_FDS;

IF_LOG_TRANSACTIONS(){

TextOutput::Bundle_b(alog);

alog<<"BC_TRANSACTIONthr"<<(void*)pthread_self()<<"/hand"

<<handle<<"/code"<<TypeCode(code)<<":"

<<indent<<data<<dedent<<endl;

}

if(err==NO_ERROR){

LOG_ONEWAY(">>>>SENDfrompid%duid%d%s",getpid(),getuid(),

(flags&TF_ONE_WAY)==0?"READREPLY":"ONEWAY");

err=writeTransactionData(BC_TRANSACTION,flags,handle,code,data,NULL);

[//err=writeTransactionData(BC_TRANSACTION,flags,handle,code,data,NULL)

这里调用writeTransactionData来写入binder_transaction_data数据

status_tIPCThreadState::writeTransactionData(int32_tcmd,uint32_tbinderFlags,int32_thandle,uint32_tcode,constParcel&data,status_t*statusBuffer)

{

binder_transaction_datatr;

tr.target.handle=handle;

tr.code=code;

tr.flags=binderFlags;

tr.cookie=0;

tr.sender_pid=0;

tr.sender_euid=0;

conststatus_terr=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();

}elseif(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);

}

mOut.writeInt32(cmd);

mOut.write(&tr,sizeof(tr));

[//mOut.write(&tr,sizeof(tr))

写入binder_transaction_data数据

]//mOut.write(&tr,sizeof(tr))

returnNO_ERROR;

}

]//err=writeTransactionData(BC_TRANSACTION,flags,handle,code,data,NULL)

}

if(err!=NO_ERROR){

if(reply)reply->setError(err);

return(mLastError=err);

}

if((flags&TF_ONE_WAY)==0){

#if0

if(code==4){//relayout

ALOGI(">>>>>>CALLINGtransaction4");

}else{

ALOGI(">>>>>>CALLINGtransaction%d",code);

}

#endif

if(reply){

err=waitForResponse(reply);

[//err=waitForResponse(reply)

这里调用waitForResponse来发送和得到Binder驱动程序的返回

status_tIPCThreadState::waitForResponse(Parcel*reply,status_t*acquireResult)

{

int32_tcmd;

int32_terr;

while(1){

if((err=talkWithDriver())<NO_ERROR)break;

[//if((err=talkWithDriver())<NO_ERROR)break

这里就调用talkWithDriver函数来和Binder驱动程序交互数据。

]//if((err=talkWithDriver())<NO_ERROR)break

err=mIn.errorCheck();

if(err<NO_ERROR)break;

if(mIn.dataAvail()==0)continue;

cmd=mIn.readInt32();

IF_LOG_COMMANDS(){

alog<<"ProcessingwaitForResponseCommand:"

<<getReturnString(cmd)<<endl;

}

switch(cmd){

caseBR_TRANSACTION_COMPLETE:

if(!reply&&!acquireResult)gotofinish;

break;

caseBR_DEAD_REPLY:

err=DEAD_OBJECT;

gotofinish;

caseBR_FAILED_REPLY:

err=FAILED_TRANSACTION;

gotofinish;

caseBR_ACQUIRE_RESULT:

{

ALOG_ASSERT(acquireResult!=NULL,"UnexpectedbrACQUIRE_RESULT");

constint32_tresult=mIn.readInt32();

if(!acquireResult)continue;

*acquireResult=result?NO_ERROR:INVALID_OPERATION;

}

gotofinish;

caseBR_REPLY:

{

binder_transaction_datatr;

err=mIn.read(&tr,sizeof(tr));

ALOG_ASSERT(err==NO_ERROR,"NotenoughcommanddataforbrREPLY");

if(err!=NO_ERROR)gotofinish;

if(reply){

if((tr.flags&TF_STATUS_CODE)==0){

reply->ipcSetDataReference(

reinterpret_cast<constuint8_t*>(tr.data.ptr.buffer),

tr.data_size,

reinterpret_cast<constsize_t*>(tr.data.ptr.offsets),

tr.offsets_size/sizeof(size_t),

freeBuffer,this);

}else{

err=*static_cast<conststatus_t*>(tr.data.ptr.buffer);

freeBuffer(NULL,

reinterpret_cast<constuint8_t*>(tr.data.ptr.buffer),

tr.data_size,

reinterpret_cast<constsize_t*>(tr.data.ptr.offsets),

tr.offsets_size/sizeof(size_t),this);

}

}else{

freeBuffer(NULL,

reinterpret_cast<constuint8_t*>(tr.data.ptr.buffer),

tr.data_size,

reinterpret_cast<constsize_t*>(tr.data.ptr.offsets),

tr.offsets_size/sizeof(size_t),this);

continue;

}

}

gotofinish;

default:

err=executeCommand(cmd);

if(err!=NO_ERROR)gotofinish;

break;

}

}

finish:

if(err!=NO_ERROR){

if(acquireResult)*acquireResult=err;

if(reply)reply->setError(err);

mLastError=err;

}

returnerr;

}

]//err=waitForResponse(reply)

}else{

ParcelfakeReply;

err=waitForResponse(&fakeReply);

}

#if0

if(code==4){//relayout

ALOGI("<<<<<<RETURNINGtransaction4");

}else{

ALOGI("<<<<<<RETURNINGtransaction%d",code);

}

#endif

IF_LOG_TRANSACTIONS(){

TextOutput::Bundle_b(alog);

alog<<"BR_REPLYthr"<<(void*)pthread_self()<<"/hand"

<<handle<<":";

if(reply)alog<<indent<<*reply<<dedent<<endl;

elsealog<<"(nonerequested)"<<endl;

}

}else{

err=waitForResponse(NULL,NULL);

}

returnerr;

}

]//status_tstatus=IPCThreadState::self()->transact(mHandle,code,data,reply,flags)

if(status==DEAD_OBJECT)mAlive=0;

returnstatus;

}

returnDEAD_OBJECT;

}

]//status_terr=remote()->transact(ADD_SERVICE_TRANSACTION,data,&reply)

returnerr==NO_ERROR?reply.readExceptionCode():err;

}

上面我们的分析都是集中在C++层的实现。接下来,我们分析一下Java层的Binder机制的实现:

和c++层一样,在使用系统的Binder机制的时候,首先需要获得ServiceManager的代理对象,这是通过调用Java层的ServiceManager类的getIServiceManager函数实现的:

privatestaticIServiceManagergetIServiceManager(){

if(sServiceManager!=null){

returnsServiceManager;

[//returnsServiceManager

sServiceManager是一个静态的IServiceManager对象,定义如下:

privatestaticIServiceManagersServiceManager;

IServiceManager定义在IServiceManager.java文件中,声明如下:

publicinterfaceIServiceManagerextendsIInterface

而IInterface的定义如下:

publicinterfaceIInterface

{

/**

*RetrievetheBinderobjectassociatedwiththisinterface.

*Youmustusethisinsteadofaplaincast,sothatproxyobjects

*canreturnthecorrectresult.

*/

publicIBinderasBinder();

[//publicIBinderasBinder()

IBinder接口定义在IBinder.java文件中:

publicinterfaceIBinder{

/**

*Thefirsttransactioncodeavailableforusercommands.

*/

intFIRST_CALL_TRANSACTION=0x00000001;

/**

*Thelasttransactioncodeavailableforusercommands.

*/

intLAST_CALL_TRANSACTION=0x00ffffff;

/**

*IBinderprotocoltransactioncode:pingBinder().

*/

intPING_TRANSACTION=('_'<<24)|('P'<<16)|('N'<<8)|'G';

/**

*IBinderprotocoltransactioncode:dumpinternalstate.

*/

intDUMP_TRANSACTION=('_'<<24)|('D'<<16)|('M'<<8)|'P';

/**

*IBinderprotocoltransactioncode:interrogatetherecipientside

*ofthetransactionforitscanonicalinterfacedescriptor.

*/

intINTERFACE_TRANSACTION=('_'<<24)|('N'<<16)|('T'<<8)|'F';

intTWEET_TRANSACTION=('_'<<24)|('T'<<16)|('W'<<8)|'T';

intLIKE_TRANSACTION=('_'<<24)|('L'<<16)|('I'<<8)|'K';

/**@hide*/

intSYSPROPS_TRANSACTION=('_'<<24)|('S'<<16)|('P'<<8)|'R';

intFLAG_ONEWAY=0x00000001;

/**

*Getthecanonicalnameoftheinterfacesupportedbythisbinder.

*/

publicStringgetInterfaceDescriptor()throwsRemoteException;

publicbooleanpingBinder();

publicbooleanisBinderAlive();

publicIInterfacequeryLocalInterface(Stringdescriptor);

publicvoiddump(FileDescriptorfd,String[]args)throwsRemoteException;

publicvoiddumpAsync(FileDescriptorfd,String[]args)throwsRemoteException;

publicbooleantransact(intcode,Parceldata,Parcelreply,intflags)

throwsRemoteException;

publicinterfaceDeathRecipient{

publicvoidbinderDied();

}

publicvoidlinkToDeath(DeathRecipientrecipient,intflags)

throwsRemoteException;

publicbooleanunlinkToDeath(DeathRecipientrecipient,intflags);

}

]//publicIBinderasBinder()

}

这貌似和C++层的设计很像啊!

]//returnsServiceManager

}

//Findtheservicemanager

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

[//sServiceManager=ServiceManagerNative.asInterface(BinderInternal.getContextObject())

这里会得到ServiceManager的代理对象来初始化sServiceManager.

调用BinderInternal.getContextObject()会得到ServiceManager的Java服务代理对象,接着调用ServiceManagerNative的asInterface将这个Java服务代理对象封装成一个ServiceManagerProxy对象.

我们首先分析BinderInternal.getContextObject()的实现:

publicstaticfinalnativeIBindergetContextObject();

getContextObject是个Native函数,实际上会调用android_util_Binder.cpp的android_os_BinderInternal_getContextObject函数,如下所示:

staticjobjectandroid_os_BinderInternal_getContextObject(JNIEnv*env,jobjectclazz)

{

sp<IBinder>b=ProcessState::self()->getContextObject(NULL);

[//sp<IBinder>b=ProcessState::self()->getContextObject(NULL)

这里会调用ProcessState对象的成员函数getContextObject来获得一个句柄值等于NULL,即等于0的Binder代理对象,即一个BpBinder对象.

]//sp<IBinder>b=ProcessState::self()->getContextObject(NULL)

returnjavaObjectForIBinder(env,b);

[//returnjavaObjectForIBinder(env,b)

这里会调用javaObjectForIBinder来将刚刚得到的BpBinder对象封装成一个Java服务代理对象.javaObjectForIBinder的函数实现如下:

jobjectjavaObjectForIBinder(JNIEnv*env,constsp<IBinder>&val)

{

if(val==NULL)returnNULL;

if(val->checkSubclass(&gBinderOffsets)){

[//if(val->checkSubclass(&gBinderOffsets))

这里gBinderOffsets定义在android_util_Binder.cpp文件中,是一个bindernative_offsets_t结构体对象:

staticstructbindernative_offsets_t

{

//Classstate.

jclassmClass;

[//jclassmClass

mClass指向Java层中的Binder类

]//jclassmClass

jmethodIDmExecTransact;

[//jmethodIDmExecTransact

mExecTransact指向mClass所指向Java层中的Binder类的成员函数execTransact

]//jmethodIDmExecTransact

//Objectstate.

jfieldIDmObject;

[//jfieldIDmObject

mObject指向mClass指向所Java层中的Binder类的成员变量mObject

]//jfieldIDmObject

}gBinderOffsets;

gBinderOffsets全局变量是在int_register_android_od_Binder中初始化的:

staticintint_register_android_os_Binder(JNIEnv*env)

{

jclassclazz=FindClassOrDie(env,kBinderPathName);

[//jclassclazz=FindClassOrDie(env,kBinderPathName)

constchar*constkBinderPathname="android/os/Binder";

这里clazz指向了Java层的Binder类

]//jclassclazz=FindClassOrDie(env,kBinderPathName)

gBinderOffsets.mClass=MakeGlobalRefOrDie(env,clazz);

gBinderOffsets.mExecTransact=GetMethodIDOrDie(env,clazz,"execTransact","(IJJI)Z");

gBinderOffsets.mObject=GetFieldIDOrDie(env,clazz,"mObject","J");

returnRegisterMethodsOrDie(

env,kBinderPathName,

gBinderMethods,NELEM(gBinderMethods));

}

]//if(val->checkSubclass(&gBinderOffsets))

//Oneofourown!

jobjectobject=static_cast<JavaBBinder*>(val.get())->object();

LOGDEATH("objectForBinder%p:it'sourown%p!\n",val.get(),object);

returnobject;

}

//Fortherestofthefunctionwewillholdthislock,toserialize

//looking/creationofJavaproxiesfornativeBinderproxies.

AutoMutex_l(mProxyLock);

//Someoneelse's...doweknowaboutit?

jobjectobject=(jobject)val->findObject(&gBinderProxyOffsets);

[//jobjectobject=(jobject)val->findObject(&gBinderProxyOffsets)

这里gBinderProxyOffsets是定义在android_util_Binder.cpp文件中,是一个binderproxy_offsets_t结构体对象:

staticstructbinderproxy_offsets_t

{

//Classstate.

jclassmClass;

[//jclassmClass

mClass指向Java层中的BinderProxy类

]//jclassmClass

jmethodIDmConstructor;

[//jmethodIDmConstructor

mConstructor指向BinderProxy类的构造函数

]//jmethodIDmConstructor

jmethodIDmSendDeathNotice;

[//jmethodIDmSendDeathNotice

mSendDeathNotice指向BinderProxy类的静态成员函数sendDeathNotice

]//jmethodIDmSendDeathNotice

//Objectstate.

jfieldIDmObject;

[//jfieldIDmObject

mObject指向BinderProxy的成员变量mObject

]//jfieldIDmObject

jfieldIDmSelf;

[//jfieldIDmSelf

mSelf指向BinderProxy的成员变量mSelf

]//jfieldIDmSelf

jfieldIDmOrgue;

}gBinderProxyOffsets;

全局变量gBinderProxyOffsets实在函数int_register_android_os_BinderProxy中初始化的:

staticintint_register_android_os_BinderProxy(JNIEnv*env)

{

jclassclazz=FindClassOrDie(env,"java/lang/Error");

gErrorOffsets.mClass=MakeGlobalRefOrDie(env,clazz);

clazz=FindClassOrDie(env,kBinderProxyPathName);

[//clazz=FindClassOrDie(env,kBinderProxyPathName)

constchar*constkBinderProxyPathname="android/os/BinderProxy";

clazz类指向Java层的BinderProxy类.

]//clazz=FindClassOrDie(env,kBinderProxyPathName)

gBinderProxyOffsets.mClass=MakeGlobalRefOrDie(env,clazz);

gBinderProxyOffsets.mConstructor=GetMethodIDOrDie(env,clazz,"<init>","()V");

gBinderProxyOffsets.mSendDeathNotice=GetStaticMethodIDOrDie(env,clazz,"sendDeathNotice",

"(Landroid/os/IBinder$DeathRecipient;)V");

gBinderProxyOffsets.mObject=GetFieldIDOrDie(env,clazz,"mObject","J");

gBinderProxyOffsets.mSelf=GetFieldIDOrDie(env,clazz,"mSelf",

"Ljava/lang/ref/WeakReference;");

gBinderProxyOffsets.mOrgue=GetFieldIDOrDie(env,clazz,"mOrgue","J");

clazz=FindClassOrDie(env,"java/lang/Class");

gClassOffsets.mGetName=GetMethodIDOrDie(env,clazz,"getName","()Ljava/lang/String;");

returnRegisterMethodsOrDie(

env,kBinderProxyPathName,

gBinderProxyMethods,NELEM(gBinderProxyMethods));

}

这里val是一个BpBinder对象,这里调用BpBinder的findObject函数定义如下:

void*BpBinder::findObject(constvoid*objectID)const

{

AutoMutex_l(mLock);

returnmObjects.find(objectID);

[//returnmObjects.find(objectID)

BpBinder类的mObjects成员变量是一个ObjectManager类型的对象.

ObjectManagermObjects;

关于ObjectManager的分析可以参考前面的分析.

]//returnmObjects.find(objectID)

}

]//jobjectobject=(jobject)val->findObject(&gBinderProxyOffsets)

if(object!=NULL){

jobjectres=jniGetReferent(env,object);

if(res!=NULL){

ALOGV("objectForBinder%p:foundexisting%p!\n",val.get(),res);

returnres;

}

LOGDEATH("Proxyobject%pofIBinder%pnolongerinworkingset!!!",object,val.get());

android_atomic_dec(&gNumProxyRefs);

val->detachObject(&gBinderProxyOffsets);

env->DeleteGlobalRef(object);

}

object=env->NewObject(gBinderProxyOffsets.mClass,gBinderProxyOffsets.mConstructor);

[//object=env->NewObject(gBinderProxyOffsets.mClass,gBinderProxyOffsets.mConstructor)

这里构造一个Java层的BinderProxy对象.

]//object=env->NewObject(gBinderProxyOffsets.mClass,gBinderProxyOffsets.mConstructor)

if(object!=NULL){

LOGDEATH("objectForBinder%p:creatednewproxy%p!\n",val.get(),object);

//Theproxyholdsareferencetothenativeobject.

env->SetLongField(object,gBinderProxyOffsets.mObject,(jlong)val.get());

[//env->SetLongField(object,gBinderProxyOffsets.mObject,(jlong)val.get())

这里将刚刚创建的Binder代理对象设置到Java层的BinderProxy的mObject成员变量中去.

]//env->SetLongField(object,gBinderProxyOffsets.mObject,(jlong)val.get())

val->incStrong((void*)javaObjectForIBinder);

//Thenativeobjectneedstoholdaweakreferencebacktothe

//proxy,sowecanretrievethesameproxyifitisstillactive.

jobjectrefObject=env->NewGlobalRef(

env->GetObjectField(object,gBinderProxyOffsets.mSelf));

val->attachObject(&gBinderProxyOffsets,refObject,

jnienv_to_javavm(env),proxy_cleanup);

//Alsorememberthedeathrecipientsregisteredonthisproxy

sp<DeathRecipientList>drl=newDeathRecipientList;

drl->incStrong((void*)javaObjectForIBinder);

env->SetLongField(object,gBinderProxyOffsets.mOrgue,reinterpret_cast<jlong>(drl.get()));

//Notethatanewobjectreferencehasbeencreated.

android_atomic_inc(&gNumProxyRefs);

incRefsCreated(env);

}

returnobject;

}

]//returnjavaObjectForIBinder(env,b)

}

程序执行完BinderInternal.getContextObject()我们就获得了一个句柄值为0的Java服务代理对象,接下来就可以调用ServiceManagerNative类的静态成员函数asInterface将它封装成一个ServiceManager的Java代理对象了.

ServiceManagerNative的asInterface函数实现如下:

staticpublicIServiceManagerasInterface(IBinderobj)

{

if(obj==null){

returnnull;

}

IServiceManagerin=(IServiceManager)obj.queryLocalInterface(descriptor);

[//IServiceManagerin=(IServiceManager)obj.queryLocalInterface(descriptor)

这里的obj是个BinderProxy对象,BinderProxy类定义在Binder.java文件中,它的queryLocalInterface函数返回null.

publicIInterfacequeryLocalInterface(Stringdescriptor){

returnnull;

}

]//IServiceManagerin=(IServiceManager)obj.queryLocalInterface(descriptor)

if(in!=null){

returnin;

}

returnnewServiceManagerProxy(obj);

[//returnnewServiceManagerProxy(obj)

这里会构造一个ServiceManagerProxy对象,并返回该对象.

publicServiceManagerProxy(IBinderremote){

mRemote=remote;

[//mRemote=remote

privateIBindermRemote;

]//mRemote=remote

}

]//returnnewServiceManagerProxy(obj)

}

]//sServiceManager=ServiceManagerNative.asInterface(BinderInternal.getContextObject())

returnsServiceManager;

}

aidl文件的Stub类继承了Binder类,因此,在创建具体的Java层的Binder本地对象的时候,会调用Binder类的构造函数来执行初始化操作.

Binder类的构造函数定义如下:

publicBinder(){

init();

[//init()

Binder的init函数是个native函数:

privatenativefinalvoidinit();

它的实现定义在android_util_Binder.cpp文件中android_os_Binder_init函数,定义如下:

staticvoidandroid_os_Binder_init(JNIEnv*env,jobjectobj)

{

JavaBBinderHolder*jbh=newJavaBBinderHolder();

[//JavaBBinderHolder*jbh=newJavaBBinderHolder()

这里创建一个JavaBBinderHolder对象. JavaBBinderHolder的定义如下:

classJavaBBinderHolder:publicRefBase

{

public:

sp<JavaBBinder>get(JNIEnv*env,jobjectobj)

{

AutoMutex_l(mLock);

sp<JavaBBinder>b=mBinder.promote();

if(b==NULL){

b=newJavaBBinder(env,obj);

[//b=newJavaBBinder(env,obj)

JavaBBinder类同样定义在android_util_Binder.cpp文件中,

classJavaBBinder:publicBBinder

JavaBBinder继承了Binder库中的BBinder类, 用来描述一个Binder本地对象.

]//b=newJavaBBinder(env,obj)

mBinder=b;

ALOGV("CreatingJavaBinder%p(refs%p)forObject%p,weakCount=%"PRId32"\n",

b.get(),b->getWeakRefs(),obj,b->getWeakRefs()->getWeakCount());

}

returnb;

}

sp<JavaBBinder>getExisting()

{

AutoMutex_l(mLock);

returnmBinder.promote();

}

private:

MutexmLock;

wp<JavaBBinder>mBinder;

};

]//JavaBBinderHolder*jbh=newJavaBBinderHolder()

if(jbh==NULL){

jniThrowException(env,"java/lang/OutOfMemoryError",NULL);

return;

}

ALOGV("JavaBinder%p:acquiringfirstrefonholder%p",obj,jbh);

jbh->incStrong((void*)android_os_Binder_init);

env->SetLongField(obj,gBinderOffsets.mObject,(jlong)jbh);

[//env->SetLongField(obj,gBinderOffsets.mObject,(jlong)jbh)

这里将刚刚创建的JavaBBinderHolder设置到gBinderOffsets中的mObject成员中,这样就设置到Java层的Binder类的mObject成员变量中.

这样运行在Java层中的服务就可以通过它的成员变量mObject来访问运行在C++层中的JavaBBinderHolder对象jbh了.

]//env->SetLongField(obj,gBinderOffsets.mObject,(jlong)jbh)

}

]//init()

if(FIND_POTENTIAL_LEAKS){

finalClass<?extendsBinder>klass=getClass();

if((klass.isAnonymousClass()||klass.isMemberClass()||klass.isLocalClass())&& (klass.getModifiers()&Modifier.STATIC)==0){

Log.w(TAG,"ThefollowingBinderclassshouldbestaticorleaksmightoccur:"+klass.getCanonicalName());

}

}

}

相关推荐