無論是客戶端仍是服務端,頭部都要先調用android
sp < IServiceManager > sm = defaultServiceManager();
defaultServiceManager()都幹了什麼,它返回的是什麼實例呢?數組
該函數定義在frameworks/native/libs/binder/IserviceManager.cpp:33ide
sp<IServiceManager> defaultServiceManager() { if (gDefaultServiceManager != NULL) return gDefaultServiceManager; { AutoMutex _l(gDefaultServiceManagerLock); while (gDefaultServiceManager == NULL) { gDefaultServiceManager = interface_cast<IServiceManager>( ProcessState::self()->getContextObject(NULL)); // 這裏纔是關鍵步驟 if (gDefaultServiceManager == NULL) sleep(1); } } return gDefaultServiceManager; }
關鍵步驟能夠分解爲幾步:一、ProcessState::self(),二、ProcessState::getContextObject(…),三、interface_cast<IserviceManager>(…)函數
frameworks/native/libs/binder/ProcessState.cpp:70 ui
sp<ProcessState> ProcessState::self() // 這又是一個進程單體 { Mutex::Autolock _l(gProcessMutex); if (gProcess != NULL) { return gProcess; } gProcess = new ProcessState; // 首次建立在這裏 return gProcess; }
ProcessState的構造函數很簡單,frameworks/native/libs/binder/ProcessState.cpp:339this
ProcessState::ProcessState() : mDriverFD(open_driver()) // 這裏打開了/dev/binder文件,並返回文件描述符 , mVMStart(MAP_FAILED) , mThreadCountLock(PTHREAD_MUTEX_INITIALIZER) , mThreadCountDecrement(PTHREAD_COND_INITIALIZER) , mExecutingThreadsCount(0) , mMaxThreads(DEFAULT_MAX_BINDER_THREADS) , 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* ALOGE("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."); }
ProcessState的構造函數主要完成兩件事:一、初始化列表裏調用opern_driver(),打開了文件/dev/binder;二、將文件映射到內存。ProcessState::self()返回單體實例。spa
該函數定義在frameworks/native/libs/binder/ProcessState.cpp:85code
sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/) { return getStrongProxyForHandle(0); }
繼續深刻,frameworks/native/libs/binder/ProcessState/cpp:179orm
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)) { if (handle == 0) { // 首次建立b爲NULL,handle爲0 // Special case for context manager... // The context manager is the only object for which we create // a BpBinder proxy without already holding a reference. // Perform a dummy transaction to ensure the context manager // is registered before we create the first local reference // to it (which will occur when creating the BpBinder). // If a local reference is created for the BpBinder when the // context manager is not present, the driver will fail to // provide a reference to the context manager, but the // driver API does not return status. // // Note that this is not race-free if the context manager // dies while this code runs. // // TODO: add a driver API to wait for context manager, or // stop special casing handle 0 for context manager and add // a driver API to get a handle to the context manager with // proper reference counting. Parcel data; status_t status = IPCThreadState::self()->transact( 0, IBinder::PING_TRANSACTION, data, NULL, 0); if (status == DEAD_OBJECT) return NULL; } b = new BpBinder(handle); e->binder = b; if (b) e->refs = b->getWeakRefs(); result = b; // 返回的是BpBinder(0) } 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; }
所以getStrongProxyForHandle(0)返回的就是new BpBinder(0)。有幾處細節能夠再回頭關注一下:blog
該函數定義在frameworks/native/libs/binder/ProcessState.cpp:166
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); }
成員變量mHandleToObject是一個數組
Vector<handle_entry>mHandleToObject;
該函數遍歷數組查找handle,若是沒找到則會向該數組中插入一個新元素,handle是數組下標。新元素的binder、refs成員默認均爲NULL,在getStrongProxyForHandle(…)中會被賦值。
interface_cast(…)函數在binder體系中很是經常使用,後面還會不斷碰見。該函數定義在frameworks/native/include/binder/IInterface.h:41
template<typename INTERFACE> inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj) { return INTERFACE::asInterface(obj); }
代入模板參數及實參後爲:
IServiceManager::asInterface(new BpBinder(0));
該函數藏在宏IMPLEMENT_META_INTERFACE中,frameworks/native/libs/binder/IServiceManager.cpp:185
IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager");
展開後爲:
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; }
所以它返回的就是new BpServiceManager(new BpBinder(0))。通過層層抽絲剝繭以後,defaultServiceManager()的返回值即爲new BpServiceManager(new BpBinder(0)),請記住這個結論。
咱們再順道看一下BpServiceManager的繼承關係以及構造函數,frameworks/native/libs/binder/IServiceManager.cpp:126
class BpServiceManager : public BpInterface<IServiceManager>
frameworks/native/libs/binder/IInterface.h:62
template<typename INTERFACE> class BpInterface : public INTERFACE, public BpRefBase
BpServiceManager繼承自BpInterface,後者繼承自BpRefBase。
frameworks/native/libs/binder/IServiceManager.cpp:129
BpServiceManager繼承自BpInterface,後者繼承自BpRefBase。 frameworks/native/libs/binder/IServiceManager.cpp:129
frameworks/native/include/binder/IInterface.h:134
template<typename INTERFACE> inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote) : BpRefBase(remote) { }
frameworks/native/libs/binder/Binder.cpp:241
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. } }
BpServiceManager經過構造函數,沿着繼承關係一路將impl參數傳遞給基類BpRefBase,基類將它賦給數據成員mRemote。在defaultServiceManager()中傳給BpServiceManager構造函數的參數是new BpBinder(0)。