我们还是以Main_MediaServer.cpp为切入点。
int main(int argc, char** argv) { sp<ProcessState> proc(ProcessState::self()); sp<IServiceManager> sm = defaultServiceManager(); LOGI("ServiceManager: %p", sm.get()); waitBeforeAdding( String16("media.audio_flinger") ); AudioFlinger::instantiate(); waitBeforeAdding( String16("media.player") ); MediaPlayerService::instantiate(); waitBeforeAdding( String16("media.camera") ); CameraService::instantiate(); waitBeforeAdding( String16("media.audio_policy") ); AudioPolicyService::instantiate(); ProcessState::self()->startThreadPool(); IPCThreadState::self()->joinThreadPool(); }
从第一句看起走吧,sp<ProcessState>在这儿你可以理解成一个ProcessState的指针而已,然后定义了一个proc的指针变量。
我们再看看ProcessState::self(),通过函数名称大家就能够猜到是一个单例模式,用self来创建一个进程内的全程对象,我们看一下代码。
sp<ProcessState> ProcessState::self() { if (gProcess != NULL) return gProcess; AutoMutex _l(gProcessMutex); if (gProcess == NULL) gProcess = new ProcessState; return gProcess; }
是吧!结果就是返回一个ProcessState对象。
那AutoMutex是何方神圣呢,这儿我们就不看代码了,避免走的太远,我直接告诉大家,就是一个线程同步的机制。
相关的实现代码 : frameworks/base/include/utils/threads.h,有兴趣的鞋童可以看一看。
好了接下来我们看看ProcessState的构造函数又做了什么呢?
ProcessState::ProcessState() : mDriverFD(open_driver()) , mVMStart(MAP_FAILED) , mManagesContexts(false) , mBinderContextCheckFunc(NULL) , mBinderContextUserData(NULL) , mThreadPoolStarted(false) , mThreadPoolSeq(1) { if (mDriverFD >= 0) { // XXX Ideally, there should be a specific define for whether we // have mmap (or whether we could possibly have the kernel module // availabla). #if !defined(HAVE_WIN32_IPC) // mmap the binder, providing a chunk of virtual address space to receive transactions. mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0); if (mVMStart == MAP_FAILED) { // *sigh* LOGE("Using /dev/binder failed: unable to mmap transaction memory.\n"); close(mDriverFD); mDriverFD = -1; } #else mDriverFD = -1; #endif } LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver could not be opened. Terminating."); }
第一句就是Binder比较核心的东西open_driver()。
static int open_driver() { int fd = open("/dev/binder", O_RDWR); if (fd >= 0) { fcntl(fd, F_SETFD, FD_CLOEXEC); int vers; status_t result = ioctl(fd, BINDER_VERSION, &vers); if (result == -1) { LOGE("Binder ioctl to obtain version failed: %s", strerror(errno)); close(fd); fd = -1; } if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) { LOGE("Binder driver protocol does not match user space protocol!"); close(fd); fd = -1; } size_t maxThreads = 15; result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads); if (result == -1) { LOGE("Binder ioctl to set max threads failed: %s", strerror(errno)); } } else { LOGW("Opening '/dev/binder' failed: %s\n", strerror(errno)); } return fd; }
这个地方有两个比较重要的概念,第一个就是打开Binder驱动,获取FD,第二个就是指一个Binder进程支持的线程最大值。
好我们回到ProcessState的构造函数,可以看到除了初始化了一些成员变量以外就是对Binder设置一个虚拟内存,划分这个内存的目的就是在于客户端和服务端进行通信时的数据保存。
我们接着看Main_MediaServer main函数的第二句 sp<IServiceManager> sm = defaultServiceManager();
看一下定义:
sp<IServiceManager> defaultServiceManager() { if (gDefaultServiceManager != NULL) return gDefaultServiceManager; { AutoMutex _l(gDefaultServiceManagerLock); if (gDefaultServiceManager == NULL) { gDefaultServiceManager = interface_cast<IServiceManager>( ProcessState::self()->getContextObject(NULL)); } } return gDefaultServiceManager; }
这儿又是一个单例,我们先看一下ProcessState::self()->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) { // We need to create a new BpBinder if there isn't currently one, OR we // are unable to acquire a weak reference on this current one. See comment // in getWeakProxyForHandle() for more info about this. IBinder* b = e->binder; if (b == NULL || !e->refs->attemptIncWeak(this)) { b = new BpBinder(handle); e->binder = b; if (b) e->refs = b->getWeakRefs(); result = b; } else { // This little bit of nastyness is to allow us to add a primary // reference to the remote proxy when this team doesn't have one // but another team is sending the handle to us. result.force_set(b); e->refs->decWeak(this); } } return result; } ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle) { const size_t N=mHandleToObject.size(); if (N <= (size_t)handle) { handle_entry e; e.binder = NULL; e.refs = NULL; status_t err = mHandleToObject.insertAt(e, N, handle+1-N); if (err < NO_ERROR) return NULL; } return &mHandleToObject.editItemAt(handle); }
从上面的代码我们可以知道getContextObject(NULL)返回了一个handle==0的BpBinder。
其实这儿我们已引出了和Binder通信的一个Binder对象BpBinder,它是客户端的Binder代理,客户端要和Binder通信必须借助它,那么和客户端对应的服务端应该也有一个负责和Binder通信的组件吧?不急我们带着问题继续走。
那我们再看看interface_cast<IServiceManager>是怎么定义的?
它定义在IIterface.h,IServiceManager.cpp怎么引用到IIterface里面的,可以参数一下我的另一篇文章:
template<typename INTERFACE> inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj) { return INTERFACE::asInterface(obj); }
我们传的是IServiceManager进去,现在又给调回来了,所以我们又要到IServiceManager中找asInterface这个方法,结果没有找到。
其实大家忽略了一个像MFC的东西
在IServiceManager.h里面引用了一个如下的宏函数:
DECLARE_META_INTERFACE(ServiceManager);
#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接收一个IBinder的指针对象的地址,如果大家返回上面的代码来看,我们这前传入的参数是BpBinder,而BpBinder就是继承了IBinder,返回的是IServiceManager。接着我们看一下看一下这个asInterface的实现吧!
IServiceManager.cpp中也调用了IIterface.h中的宏定义:
IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager");
#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返回的就是BpServiceManager,所以前面defaultServiceManager获得的就是这个对像了,于是我们又去查一下它是个什么东西?
class BpServiceManager : public BpInterface<IServiceManager> { public: BpServiceManager(const sp<IBinder>& impl) : BpInterface<IServiceManager>(impl) { } virtual sp<IBinder> getService(const String16& name) const { unsigned n; for (n = 0; n < 5; n++){ sp<IBinder> svc = checkService(name); if (svc != NULL) return svc; LOGI("Waiting for service %s...\n", String8(name).string()); sleep(1); } return NULL; } 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(); } virtual status_t addService(const String16& name, const sp<IBinder>& service) { Parcel data, reply; data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor()); data.writeString16(name); data.writeStrongBinder(service); status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply); return err == NO_ERROR ? reply.readExceptionCode() : err; } virtual Vector<String16> listServices() { Vector<String16> res; int n = 0; for (;;) { Parcel data, reply; data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor()); data.writeInt32(n++); status_t err = remote()->transact(LIST_SERVICES_TRANSACTION, data, &reply); if (err != NO_ERROR) break; res.add(reply.readString16()); } return res; } };
注意BpServiceManager的构造函数中的初始化BpInterface<IServiceManager>(impl),impl是BpBinder,我们看看它被赋值给谁了,BpRefBase中的mRemote,而我们在BpServiceManager中调用的remote()就是返回的mRemote。