Android请求注册服务过程源码分析

来源:互联网 发布:typescript python 编辑:程序博客网 时间:2024/05/18 00:08

http://blog.csdn.net/yangwen123/article/details/9075171


目录(?)[+]

在ServiceManager 进程启动源码分析中详细介绍了ServiceManager进程是如何启动,如何成为Android系统的服务大管家。客户端在请求服务前,必须将服务注册到ServiceManger中,这样客户端在请求服务的时候,才能够查找到指定的服务。本文开始将以CameraService服务的注册为例来介绍服务注册的整个过程。

CameraService服务的注册过程包括五个步骤:

1)客户进程向ServiceManager进程发送IPC服务注册信息;

2)ServiceManager进程接收客户进程发送过来的IPC数据;

3)ServiceManager进程登记注册服务;

4)ServiceManager向客户进程发送IPC返回信息;

5)客户进程接收ServiceManager进程发送过来的IPC数据;


本文主要分析客户端进程是如何向ServiceManager进程发送IPC服务注册信息的。服务分为Java服务和本地服务两种,因此服务注册也存在两种方式:Java层服务注册和C++层服务注册。

Java层服务注册过程

例如注册电源管理服务:ServiceManager.addService(Context.POWER_SERVICE, power);

通过ServiceManager类的addService()函数来注册某个服务,addService函数的实现如下:

[java] view plain copy
  1. public static void addService(String name, IBinder service) {  
  2.     try {  
  3.         getIServiceManager().addService(name, service, false);  
  4.     } catch (RemoteException e) {  
  5.         Log.e(TAG, "error in addService", e);  
  6.     }  
  7. }  

通过getIServiceManager()获取ServiceManager的代理对ServiceManagerProxy,并调用代理对象的addService函数来注册服务。

获取代理对象ServiceManagerProxy

[java] view plain copy
  1. private static IServiceManager getIServiceManager() {  
  2.     if (sServiceManager != null) {  
  3.         return sServiceManager;  
  4.     }  
  5.     // 获取ServiceManagerProxy对象实例  
  6.     sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());  
  7.     return sServiceManager;  
  8. }  

Java层通过以下两个步骤来获取ServiceManager的代理对象的引用:

1) BinderInternal.getContextObject() 创建一个Java层的BinderProxy对象,该对象与C++层的BpBinder一一对应;

2) ServiceManagerNative.asInterface(obj) 创建一个Java层面的ServiceManagerProxy代理对象,作用与C++层的BpServiceManager相同。

函数首先创建BpBinder,然后使用BpBinder对象来创建一个Java层的BinderProxy对象,最后通过BinderProxy对象来构造ServiceManagerProxy实例对象。

BpBinder ---> BinderProxy ---> ServiceManagerProxy

BpBinder创建过程

在了解BpBinder的创建过程前,首先介绍一下Android Binder通信框架类之间的关系,如下图所示:

从以上类图可以看到,BpBinder和BBinder共同继承与IBinder类,BpBinder是客户端进程中的Binder代理对象,BBinder是服务进程中用于IPC通信的工具对象,BpBinder类通过IPCThreadState类来与Binder驱动交互,访问服务进程中的BBinder,BpBinder代表了客户进程,BBinder代表了服务进程,数据从BpBinder发送到BBinder的整个过程就是Android系统的整个Binder通信过程,BpBinder与BBinder负责IPC通信,和上层业务并无关系。Android系统的Binder通信实现了RPC远程调用,BpXXX和BnXXX则负责RPC远程调用的业务,XXX就代表不同的服务业务。BpXXX和BnXXX都实现了IXXX接口,IXXX定义了业务接口函数,BpXXX则是客户进程对服务进程中的BnXXX的影子对象,客户进程在调用服务进程中的某个接口函数时,只需调用BpXXX中的对应函数即可,BpXXX屏蔽了进程间通信的整个过程,让远程函数调用看起来和本地调用一样,这就是Android系统的Binder设计思想。进程要与Binder驱动交互,必须通过ProcessState对象来实现,ProcessState在每个使用了Binder通信的进程中唯一存在,其成员变量mDriverFD保存来/dev/binder设备文件句柄。对于某个服务来说,可能同时接受多个客户端的RPC访问,因此Android系统就设计了一个Binder线程池,每个Binder线程负责处理一个客户端的请求,对于每个Binder线程都存在一个属于自己的唯一IPCThreadState对象,IPCThreadState对象封装来Binder线程访问Binder驱动的接口,同一个进程中的所有Binder线程所持有的IPCThreadState对象使用线程本地存储来保存。

BinderInternal类的静态函数getContextObject()是一个本地函数

[java] view plain copy
  1. public static final native IBinder getContextObject()  

其对应的JNI函数为:

[cpp] view plain copy
  1. static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)  
  2. {   
  3.     sp<IBinder> b = ProcessState::self()->getContextObject(NULL); -->new BpBinder(0)  
  4.     //new BpBinder(0) ----->new BinderProxy()  
  5.     return javaObjectForIBinder(env, b);  
  6. }  

函数首先使用单例模式获取ProcessState对象,并调用其函数getContextObject()来创建BpBinder对象,最后使用javaObjectForIBinder函数创建BinderProxy对象。整个过程包括以下几个步骤:

1.构造ProcessState对象实例;

2.创建BpBinder对象;

3.创建BinderProxy对象;

构造ProcessState对象实例

frameworks\base\libs\binder\ProcessState.cpp 
采用单例模式为客户端进程创建ProcessState对象:

[cpp] view plain copy
  1. sp<ProcessState> ProcessState::self()  
  2. {  
  3.     if (gProcess != NULL) return gProcess;  
  4.     AutoMutex _l(gProcessMutex);  
  5.     if (gProcess == NULL) gProcess = new ProcessState;  
  6.     return gProcess;  
  7. }  

构造ProcessState对象

[cpp] view plain copy
  1. ProcessState::ProcessState()  
  2.     : mDriverFD(open_driver()) //打开Binder设备驱动  
  3.     , mVMStart(MAP_FAILED)  
  4.     , mManagesContexts(false)  
  5.     , mBinderContextCheckFunc(NULL)  
  6.     , mBinderContextUserData(NULL)  
  7.     , mThreadPoolStarted(false)  
  8.     , mThreadPoolSeq(1)  
  9. {  
  10.     if (mDriverFD >= 0) {  
  11. #if !defined(HAVE_WIN32_IPC)  
  12.         // mmap the binder, providing a chunk of virtual address space to receive transactions.  
  13.         mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);  
  14.         if (mVMStart == MAP_FAILED) {  
  15.             LOGE("Using /dev/binder failed: unable to mmap transaction memory.\n");  
  16.             close(mDriverFD);  
  17.             mDriverFD = -1;  
  18.         }  
  19. #else  
  20.         mDriverFD = -1;  
  21. #endif  
  22.     }  
  23.     if (mDriverFD < 0) {  
  24.         // Need to run without the driver, starting our own thread pool.  
  25.     }  
  26. }  

在构造ProcessState对象时,将打开Binder驱动,并将Binder驱动设备文件句柄保存在成员变量mDriverFD 中。同时将Binder设备文件句柄映射到客户端进程的地址空间中,映射的起始地址保存在mVMStart变量中,映射的空间大小为(1024*1024) - (2* 4096)

创建BpBinder对象

[cpp] view plain copy
  1. sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& caller)  
  2. {  
  3.     return getStrongProxyForHandle(0); //ServiceManager的handle = 0  
  4. }  

函数直接调用getStrongProxyForHandle函数来创建ServiceManager的Binder代理对象BpBinder,由于ServiceManager服务对应的Handle值为0,因此这里的参数设置为0.

[cpp] view plain copy
  1. sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)  
  2. {  
  3.     sp<IBinder> result;  
  4.   AutoMutex _l(mLock);  
  5.   //根据句柄值查询  
  6.     handle_entry* e = lookupHandleLocked(handle);  
  7.     //如果从表中查找到了对应的handle  
  8.     if (e != NULL) {  
  9.         // We need to create a new BpBinder if there isn't currently one, OR we  
  10.         // are unable to acquire a weak reference on this current one.  See comment  
  11.         // in getWeakProxyForHandle() for more info about this.  
  12.         // 取handle_entry 中的binder成员  
  13.         IBinder* b = e->binder;  
  14.         if (b == NULL || !e->refs->attemptIncWeak(this)) {  
  15.             b = new BpBinder(handle); //根据句柄值创建一个BpBinder  
  16.             e->binder = b;  
  17.             if (b) e->refs = b->getWeakRefs();  
  18.             result = b;  
  19.         } else {  
  20.             // This little bit of nastyness is to allow us to add a primary  
  21.             // reference to the remote proxy when this team doesn't have one  
  22.             // but another team is sending the handle to us.  
  23.             result.force_set(b);  
  24.             e->refs->decWeak(this);  
  25.         }  
  26.     }  
  27.     return result;  
  28. }  

根据句柄获取相应的Binder代理,返回BpBinder对象,该函数主要是根据handle值从表中查找对应的handle_entry,并返回该结构的成员binder的值。查找过程如下:

[cpp] view plain copy
  1. ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)  
  2. {  
  3.     const size_t N=mHandleToObject.size();  
  4.     if (N <= (size_t)handle) {  
  5.         handle_entry e;  
  6.         e.binder = NULL;  
  7.         e.refs = NULL;  
  8.         status_t err = mHandleToObject.insertAt(e, N, handle+1-N);  
  9.         if (err < NO_ERROR) return NULL;  
  10.     }  
  11.     return &mHandleToObject.editItemAt(handle);  
  12. }  

为了理解整个查找过程,必须先了解各个数据结构直接的关系,下面通过一个图了描述数据存储结构:


在ProcessState的成员变量mHandleToObject中存储了进程所使用的BpBinder,Handle值是BpBinder所对应的handle_entry在表mHandleToObject中的索引。

查找过程实质上就是从mHandleToObject向量中查找相应句柄的Binder代理对象。

创建BinderProxy对象

在介绍BinderProxy对象前,依然先介绍一下在Java层的Binder通信类的设计框架,Java层的Binder通信是建立在C++层的Binder设计框架上的,为了让开发者在使用Java语言开发应用程序时方便使用Android系统的RPC调用,在Java层也设计了一套框架,用于实现Java层的Binder通信。

Java层的Binder通信框架设计和C++层的设计基本类似,也是分为通信层也业务层,通信层包括客户进程的BinderProxy和服务进程的Binder;业务层包括客户进程的Proxy和服务进程的Stub的子类XXXService。同时这些类与C++的设计类有一定的映射关系,如下图所示:

使用函数javaObjectForIBinder来创建一个BinderProxy对象,并在保存BpBinder的持久对象,同样为了能更深入地理解整个创建过程,我们需要先理解BinderProxy数据结构与BpBinder数据结构直接的关系,它们之间的关系如下图所示:

 

 

Java类在JNI层的数据对应关系:

[cpp] view plain copy
  1. jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)  
  2. {  
  3.     //val == new BpBinder(0)  
  4.   if (val == NULL) return NULL;  
  5.   //BpBinder 中返回false  
  6.     if (val->checkSubclass(&gBinderOffsets)) {  //false  
  7.         jobject object = static_cast<JavaBBinder*>(val.get())->object();  
  8.         LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);  
  9.         return object;  
  10.     }  
  11.     AutoMutex _l(mProxyLock);  
  12.   //BpBinder的findObject函数实际在ObjectManager中查找JNI层的BinderProxy,即gBinderProxyOffsets  
  13.   jobject object = (jobject)val->findObject(&gBinderProxyOffsets);  
  14.     //如果已经保存,则删除原来的gBinderProxyOffsets  
  15.   if (object != NULL) {  
  16.         //调用WeakReference类的get方法  
  17.         jobject res = env->CallObjectMethod(object, gWeakReferenceOffsets.mGet);  
  18.         if (res != NULL) {  
  19.             LOGV("objectForBinder %p: found existing %p!\n", val.get(), res);  
  20.             return res;  
  21.         }  
  22.         LOGDEATH("Proxy object %p of IBinder %p no longer in working set!!!", object, val.get());  
  23.         android_atomic_dec(&gNumProxyRefs);  
  24.         //从BpBinder的ObjectManager中删除JNI层的gBinderProxyOffsets  
  25.         val->detachObject(&gBinderProxyOffsets);  
  26.         env->DeleteGlobalRef(object);  
  27.     }  
  28.   //在JNI层构造一个Java层的BinderProxy  
  29.   object = env->NewObject(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mConstructor);  
  30.     if (object != NULL) {  
  31.         LOGDEATH("objectForBinder %p: created new proxy %p !\n", val.get(), object);  
  32.         // 将本地BpBinder对象保存在BinderProxy的成员变量mObject中  
  33.         env->SetIntField(object, gBinderProxyOffsets.mObject, (int)val.get());  
  34.         val->incStrong(object);  
  35.         // 创建一个类型为WeakReference的对象,BinderProxy的成员变量mSelf就是WeakReference类实例对象  
  36.       jobject refObject = env->NewGlobalRef(env->GetObjectField(object, gBinderProxyOffsets.mSelf));  
  37.         //将新创建的BinderProxy对象注册到BpBinder的ObjectManager中,同时注册一个回收函数proxy_cleanup,当BinderProxy对象撤销时,释放资源  
  38.       val->attachObject(&gBinderProxyOffsets, refObject,jnienv_to_javavm(env), proxy_cleanup);  
  39.         // Also remember the death recipients registered on this proxy  
  40.         sp<DeathRecipientList> drl = new DeathRecipientList;  
  41.         drl->incStrong((void*)javaObjectForIBinder);  
  42.         env->SetIntField(object, gBinderProxyOffsets.mOrgue, reinterpret_cast<jint>(drl.get()));  
  43.         // 增加Proxy对象的引用计数  
  44.         android_atomic_inc(&gNumProxyRefs);  
  45.         //当创建的Proxy对象超过200个时,调用BinderIntenal的ForceGc进行垃圾回收  
  46.         incRefsCreated(env);  
  47.     }  
  48.     return object;  
  49. }  

gBinderProxyOffsetsJNI层中存储Java层的BinderProxy类信息的结构,refObjectJNI层创建的WeakReference对象的全局引用

[cpp] view plain copy
  1. void BpBinder::attachObject(const void* objectID, void* object, void* cleanupCookie,  
  2.     object_cleanup_func func)  
  3. {  
  4.     AutoMutex _l(mLock);  
  5.   LOGV("Attaching object %p to binder %p (manager=%p)", object, this, &mObjects);  
  6.   //调用ObjectManager的attach函数来完成存储  
  7.     mObjects.attach(objectID, object, cleanupCookie, func);  
  8. }  

 

[cpp] view plain copy
  1. void BpBinder::ObjectManager::attach(const void* objectID, void* object, void*   cleanupCookie,IBinder::object_cleanup_func func)  
  2. {  
  3.     entry_t e;  
  4.     e.object = object;  
  5.     e.cleanupCookie = cleanupCookie;  
  6.     e.func = func;  
  7.     if (mObjects.indexOfKey(objectID) >= 0) {//如果列表中已经存在该gBinderProxyOffsets  
  8.         LOGE("Trying to attach object ID %p to binder ObjectManager %p with object %p, but object ID already in use",objectID, this,  object);  
  9.         return;  
  10.     }  
  11.     mObjects.add(objectID, e); //不存在,则添加gBinderProxyOffsets和refObject的键值对  
  12. }  

将Java层的BinderProxy对象对应的JNI层的gBinderProxyOffsets以键值对的形式存储在BpBinder的ObjectManager中。

ServiceManagerProxy对象的创建过程

使用BinderProxy对象来构造ServiceManagerProxy对象:

[cpp] view plain copy
  1. static public IServiceManager asInterface(IBinder obj)  
  2. {  
  3.     if (obj == null) {  
  4.         return null;  
  5.     }  
  6.     IServiceManager in =(IServiceManager)obj.queryLocalInterface(descriptor);  
  7.     if (in != null) {  
  8.         return in;  
  9.     }  
  10.     return new ServiceManagerProxy(obj);  
  11. }  

采用单例模式来构造ServiceManagerProxy对象

[java] view plain copy
  1. public ServiceManagerProxy(IBinder remote) {  
  2.     mRemote = remote;  
  3. }  

构造过程比较简单,就是将创建的BinderProxy对象赋值给ServiceManagerProxy的成员变量mRemote。

使用ServiceManagerProxy注册服务

[java] view plain copy
  1. public void addService(String name, IBinder service, boolean allowIsolated)  
  2.         throws RemoteException {  
  3.     Parcel data = Parcel.obtain(); //发送的数据包  
  4.     Parcel reply = Parcel.obtain(); //接收的数据包  
  5.     //写入需要发送的数据  
  6.     data.writeInterfaceToken(IServiceManager.descriptor);  
  7.     data.writeString(name);  
  8.     data.writeStrongBinder(service);  
  9.     data.writeInt(allowIsolated ? 1 : 0);  
  10.     //数据传输过程  
  11.     mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0);  
  12.     reply.recycle();  
  13.     data.recycle();  
  14. }  

ServiceManagerProxy实现的代理作用就是将数据的处理与数据的传输分开,在代理层仅仅实现数据的打包与解包工作,而真正的数据发送完全交个BinderProxy来完成。

在ServiceManagerProxy对象构造过程中,将BinderProxy对象直接赋给了ServiceManagerProxy的成员变量mRemote了,因此上面调用的transact函数调用的是BinderProxy类的transact函数:

[cpp] view plain copy
  1. public native boolean transact(int code, Parcel data, Parcel reply,  
  2.         int flags) throws RemoteException;  

这是一个本地函数,其对于的JNI实现函数为:

[cpp] view plain copy
  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.     if (dataObj == NULL) {  
  6.         jniThrowNullPointerException(env, NULL);  
  7.         return JNI_FALSE;  
  8.     }  
  9.     //将Java中的Parcel转换为C++中的Parcel对象  
  10.     Parcel* data = parcelForJavaObject(env, dataObj);  
  11.     if (data == NULL) {  
  12.         return JNI_FALSE;  
  13.     }  
  14.     //将Java中的Parcel转换为C++中的Parcel对象  
  15.     Parcel* reply = parcelForJavaObject(env, replyObj);  
  16.     if (reply == NULL && replyObj != NULL) {  
  17.         return JNI_FALSE;  
  18.     }  
  19.     //从BinderProxy的成员变量mObject中取得对应的BpBinder对象  
  20.     IBinder* target = (IBinder*)env->GetIntField(obj, gBinderProxyOffsets.mObject);  
  21.     if (target == NULL) {  
  22.         jniThrowException(env, "java/lang/IllegalStateException""Binder has been finalized!");  
  23.         return JNI_FALSE;  
  24.     }  
  25.   
  26.     ALOGV("Java code calling transact on %p in Java object %p with code %d\n",  
  27.             target, obj, code);  
  28.   
  29.     // Only log the binder call duration for things on the Java-level main thread.  
  30.     // But if we don't  
  31.     const bool time_binder_calls = should_time_binder_calls();  
  32.   
  33.     int64_t start_millis;  
  34.     if (time_binder_calls) {  
  35.         start_millis = uptimeMillis();  
  36.     }  
  37.     //调用BpBinder对象的transact函数来发送数据  
  38.     status_t err = target->transact(code, *data, reply, flags);  
  39.     //if (reply) printf("Transact from Java code to %p received: ", target); reply->print();  
  40.     if (time_binder_calls) {  
  41.         conditionally_log_binder_call(start_millis, target, code);  
  42.     }  
  43.   
  44.     if (err == NO_ERROR) {  
  45.         return JNI_TRUE;  
  46.     } else if (err == UNKNOWN_TRANSACTION) {  
  47.         return JNI_FALSE;  
  48.     }  
  49.     signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/);  
  50.     return JNI_FALSE;  
  51. }  

在创建BinderProxy对象一节中,BinderProxy对象创建后,会将其对应的BpBinder对象保存在BinderProxy的成员变量mObject中,在这里就直接从mObject中取出BpBinder对象来发送数据。

[cpp] view plain copy
  1. status_t BpBinder::transact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)  
  2. {  
  3.     // Once a binder has died, it will never come back to life.  
  4.     if (mAlive) {  
  5.         //间接调用IPCThreadState的transact函数来发送数据  
  6.         status_t status = IPCThreadState::self()->transact(mHandle, code, data, reply, flags);  
  7.         if (status == DEAD_OBJECT) mAlive = 0;  
  8.         return status;  
  9.     }  
  10.     return DEAD_OBJECT;  
  11. <p>}</p>  

本地服务注册过程

C++层注册服务:SurfaceFlinger::instantiate();

各个C++本地服务继承BinderService,BinderService类是一个模板类,其instantiate函数定义如下:

[cpp] view plain copy
  1. static void instantiate() { publish(); }  

 

[cpp] view plain copy
  1. static status_t publish(bool allowIsolated = false) {  
  2.     //取得ServiceManager的代理对象  
  3.     sp<IServiceManager> sm(defaultServiceManager());  
  4.     //注册服务  
  5.     return sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated);  
  6. }  

BpServiceManager对象获取过程

[cpp] view plain copy
  1. sp<IServiceManager> defaultServiceManager(){  
  2.     if (gDefaultServiceManager != NULL) return gDefaultServiceManager;  
  3.     {  
  4.         AutoMutex _l(gDefaultServiceManagerLock);  
  5.         if (gDefaultServiceManager == NULL) {  
  6.             gDefaultServiceManager = interface_cast<IServiceManager>(  
  7.                 ProcessState::self()->getContextObject(NULL));  
  8.         }  
  9.     }  
  10.     return gDefaultServiceManager;  
  11. }  

通过interface_cast<IServiceManager>(ProcessState::self()->getContextObject(NULL))获取servicemanager代理对象的引用,通过以下三个步骤来实现:

1) ProcessState::self() 得到ProcessState实例对象;

2) ProcessState->getContextObject(NULL) 得到BpBinder对象;

3) interface_cast<IServiceManager>(const sp<IBinder>& obj使用BpBinder对象来创建服务代理对象BpXXX

前面两个步骤ProcessState::self()->getContextObject(NULL)已经在前面详细介绍了,它返回一个BpBinder(0)对象实例。因此:

[cpp] view plain copy
  1. gDefaultServiceManager = interface_cast<IServiceManager>(BpBinder(0));  

interface_cast是一个模版函数
frameworks\base\include\binder\IInterface.h

[cpp] view plain copy
  1. template<typename INTERFACE>  
  2. inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)  
  3. {  
  4.   return INTERFACE::asInterface(obj);  
  5.   //return IServiceManager::asInterface(obj);  
  6. }  

因此interface_cast函数的实现实际上是调用相应接口的asInterface函数来完成的,对于IServiceManager接口即调用IServiceManager::asInterface(obj)

通过宏DECLARE_META_INTERFACE声明了ServiceManager的接口函数

[cpp] view plain copy
  1. DECLARE_META_INTERFACE(ServiceManager);  

DECLARE_META_INTERFACE 的定义:

[cpp] view plain copy
  1. #define DECLARE_META_INTERFACE(INTERFACE)               \  
  2.     static const android::String16 descriptor;                         \  
  3.     static android::sp<I##INTERFACE> asInterface(                  \  
  4.             const android::sp<android::IBinder>& obj);              \  
  5.     virtual const android::String16& getInterfaceDescriptor() const;      \  
  6.     I##INTERFACE();                                          \  
  7.   virtual ~I##INTERFACE();                                   \  

因此对于ServiceManager的接口函数声明如下:

[cpp] view plain copy
  1. static const android::String16 descriptor;                           
  2. static android::sp<IServiceManager> asInterface(const android::sp<android::IBinder>& obj);                
  3. virtual const android::String16& getInterfaceDescriptor() const;        
  4. IServiceManager();                                            
  5. virtual ~IServiceManager();    

通过宏IMPLEMENT_META_INTERFACE定义ServiceManager的接口函数实现

[cpp] view plain copy
  1. IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager");  

IMPLEMENT_META_INTERFACE的定义:

[cpp] view plain copy
  1. #define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)      \  
  2.     const android::String16 I##INTERFACE::descriptor(NAME);        \  
  3.     const android::String16&                                      \  
  4.             I##INTERFACE::getInterfaceDescriptor() const {          \  
  5.         return I##INTERFACE::descriptor;                          \  
  6.     }                                                          \  
  7.     android::sp<I##INTERFACE> I##INTERFACE::asInterface(         \  
  8.             const android::sp<android::IBinder>& obj)                \  
  9.     {                                                          \  
  10.         android::sp<I##INTERFACE> intr;                          \  
  11.         if (obj != NULL) {                                       \  
  12.             intr = static_cast<I##INTERFACE*>(                   \  
  13.                 obj->queryLocalInterface(                         \  
  14.                         I##INTERFACE::descriptor).get());         \  
  15.             if (intr == NULL) {                                  \  
  16.                 intr = new Bp##INTERFACE(obj);                 \  
  17.             }                                                 \  
  18.         }                                                     \  
  19.         return intr;                                             \  
  20.     }                                                         \  
  21.     I##INTERFACE::I##INTERFACE() { }                         \  
  22.     I##INTERFACE::~I##INTERFACE() { }                        \  

对于ServiceManager的接口函数实现如下:

[cpp] view plain copy
  1. const android::String16 IServiceManager::descriptor(NAME);         
  2. const android::String16&                                       
  3.         IServiceManager::getInterfaceDescriptor() const {          
  4.     return IServiceManager::descriptor;                            
  5. }                                                           
  6. android::sp<IServiceManager> IServiceManager::asInterface(        
  7.         const android::sp<android::IBinder>& obj)                
  8. {                                                            
  9.     android::sp<IServiceManager> intr;                           
  10.     if (obj != NULL) {                                     
  11.         intr = static_cast<IServiceManager*>(obj->queryLocalInterface(IServiceManager::descriptor).get());        
  12.         if (intr == NULL) {                                  
  13.             intr = new BpServiceManager(obj);                
  14.         }                                                
  15.     }                                                  
  16.     return intr;                                            
  17. }                                                          
  18. IServiceManager::IServiceManager() { }                          
  19. IServiceManager::~IServiceManager() { }                         

Obj是BpBinder对象,BpBinder继承IBinder类,在子类BpBinder中并未重写父类的queryLocalInterface接口函数,因此obj->queryLocalInterface() 实际上是调用父类IBinder的queryLocalInterface()函数,在IBinder类中:

[cpp] view plain copy
  1. sp<IInterface>  IBinder::queryLocalInterface(const String16& descriptor)  
  2. {  
  3.     return NULL;  
  4. }  

因此通过调用 IServiceManager::asInterface()函数即可创建ServiceManager的代理对象BpServiceManager = new BpServiceManager(new BpBinder(0)),BpServiceManager的构造实际上是对通信层的封装,为上层屏蔽进程间通信的细节。

BpServiceManager的构造过程:

[cpp] view plain copy
  1. BpServiceManager(const sp<IBinder>& impl): BpInterface<IServiceManager>(impl)  
  2. {  
  3. }  

BpServiceManager的构造过程中并未做任何实现,在构造BpServiceManager对象之前,必须先构造父类对象BpInterfaceBpInterface的构造函数采用了模板函数实现:

[cpp] view plain copy
  1. template<typename INTERFACE>  
  2. inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote): BpRefBase(remote)  
  3. {  
  4. }  

由于BpInterface 同时继承于BpRefBase及相应的接口,如IServiceManager,因此在构造BpInterface 的过程中必先构造其父类对象:

对于父类BpRefBase的构造过程如下:

[cpp] view plain copy
  1. BpRefBase::BpRefBase(const sp<IBinder>& o): mRemote(o.get()), mRefs(NULL), mState(0)  
  2. {  
  3.     extendObjectLifetime(OBJECT_LIFETIME_WEAK);  
  4.     if (mRemote) {  
  5.         mRemote->incStrong(this);           // Removed on first IncStrong().  
  6.         mRefs = mRemote->createWeak(this);  // Held for our entire lifetime.  
  7.     }  
  8. }  

最终把ServiceManger对应的BpBinder(0)赋给了mRemote,在客户端向ServiceManager发送请求过程中,首先通过ServiceManager的代理对象BpServiceManager来包装数据,接着调用BpBinder将数据发送给服务端ServiceManager

BpServiceManager服务注册过程

[cpp] view plain copy
  1. virtual status_t addService(const String16& name, const sp<IBinder>& service,  
  2.         bool allowIsolated)  
  3. {  
  4.     //数据打包过程  
  5.     Parcel data, reply;  
  6.     data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());  
  7.     data.writeString16(name);  
  8.     data.writeStrongBinder(service);  
  9.     data.writeInt32(allowIsolated ? 1 : 0);  
  10.     //使用BpBinder来发送数据  
  11.     status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);  
  12.     return err == NO_ERROR ? reply.readExceptionCode() : err;  
  13. }  

函数首先将要发送的数据打包在parcel对象中,然后调用BpBinder对象来发送数据。

[cpp] view plain copy
  1. status_t BpBinder::transact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)  
  2. {  
  3.     // Once a binder has died, it will never come back to life.  
  4.     if (mAlive) {  
  5.         //间接调用IPCThreadState的transact函数来发送数据  
  6.         status_t status = IPCThreadState::self()->transact(mHandle, code, data, reply, flags);  
  7.         if (status == DEAD_OBJECT) mAlive = 0;  
  8.         return status;  
  9.     }  
  10.     return DEAD_OBJECT;  
  11. }  


在这里和Java层的服务注册过程殊途同归了,都是通过IPCThreadState类来和Binder驱动交换,将IPC数据发送给ServiceManger进程。本文分析了用户空间中Binder通信架构设计及IPC数据的封装过程,在接下来的Android IPC数据在内核空间中的发送过程分析将进入Binder驱动分析IPC数据的传输过程。


0 0
原创粉丝点击