不管是客戶端還是服務(wù)端,頭部都要先調(diào)用
sp < IServiceManager > sm = defaultServiceManager();
defaultServiceManager()都干了什么,它返回的是什么實(shí)例呢?
該函數(shù)定義在frameworks/native/libs/binder/IserviceManager.cpp:33
sp<IServiceManager> defaultServiceManager()
{
if (gDefaultServiceManager != NULL) return gDefaultServiceManager;
{
AutoMutex _l(gDefaultServiceManagerLock);
while (gDefaultServiceManager == NULL) {
gDefaultServiceManager = interface_cast<IServiceManager>(
ProcessState::self()->getContextObject(NULL)); // 這里才是關(guān)鍵步驟
if (gDefaultServiceManager == NULL)
sleep(1);
}
}
return gDefaultServiceManager;
}
關(guān)鍵步驟可以分解為幾步:1、ProcessState::self(),2、ProcessState::getContextObject(…),3、interface_cast<IserviceManager>(…)
ProcessState::self()
frameworks/native/libs/binder/ProcessState.cpp:70
sp<ProcessState> ProcessState::self() // 這又是一個(gè)進(jìn)程單體
{
Mutex::Autolock _l(gProcessMutex);
if (gProcess != NULL) {
return gProcess;
}
gProcess = new ProcessState; // 首次創(chuàng)建在這里
return gProcess;
}
ProcessState的構(gòu)造函數(shù)很簡(jiǎn)單,frameworks/native/libs/binder/ProcessState.cpp:339
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的構(gòu)造函數(shù)主要完成兩件事:1、初始化列表里調(diào)用opern_driver(),打開了文件/dev/binder;2、將文件映射到內(nèi)存。ProcessState::self()返回單體實(shí)例。
ProcessState::getContextObject(…)
該函數(shù)定義在frameworks/native/libs/binder/ProcessState.cpp:85
sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
{
return getStrongProxyForHandle(0);
}
繼續(xù)深入,frameworks/native/libs/binder/ProcessState/cpp:179
sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
{
sp<IBinder> result;
AutoMutex _l(mLock);
handle_entry* e = lookupHandleLocked(handle); //正常情況下總會(huì)返回一個(gè)非空實(shí)例
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) { // 首次創(chuàng)建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)。有幾處細(xì)節(jié)可以再回頭關(guān)注一下:
ProcessState::lookupHandleLocked(int32_t handle)
該函數(shù)定義在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是一個(gè)數(shù)組
Vector<handle_entry>mHandleToObject;
該函數(shù)遍歷數(shù)組查找handle,如果沒找到則會(huì)向該數(shù)組中插入一個(gè)新元素,handle是數(shù)組下標(biāo)。新元素的binder、refs成員默認(rèn)均為NULL,在getStrongProxyForHandle(…)中會(huì)被賦值。
interface_cast<IserviceManager>(…)
interface_cast(…)函數(shù)在binder體系中非常常用,后面還會(huì)不斷遇見。該函數(shù)定義在frameworks/native/include/binder/IInterface.h:41
template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
return INTERFACE::asInterface(obj);
}
代入模板參數(shù)及實(shí)參后為:
IServiceManager::asInterface(new BpBinder(0));
該函數(shù)藏在宏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) { // 首次會(huì)走這里
intr = new BpServiceManager(obj);
}
}
return intr;
}
因此它返回的就是new BpServiceManager(new BpBinder(0))。
經(jīng)過層層抽絲剝繭之后,defaultServiceManager()的返回值即為new BpServiceManager(new BpBinder(0))。
我們?cè)夙樀揽匆幌翨pServiceManager的繼承關(guān)系以及構(gòu)造函數(shù),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(const sp<IBinder>& impl)
: BpInterface<IServiceManager>(impl)
{
}
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通過構(gòu)造函數(shù),沿著繼承關(guān)系一路將impl參數(shù)傳遞給基類BpRefBase,基類將它賦給數(shù)據(jù)成員mRemote。在defaultServiceManager()中傳給BpServiceManager構(gòu)造函數(shù)的參數(shù)是new BpBinder(0)。