以MediaServer为例剖析Android Binder通信机制
代码位置:
frameworks/base/av/media/mediaserver/main_mediaserver.cpp
int main(int argc __unused, char **argv __unused)
{
InitPlayer();
signal(SIGPIPE, SIG_IGN);
sp<ProcessState> proc(ProcessState::self());
sp<IServiceManager> sm(defaultServiceManager());
ALOGI("ServiceManager: %p", sm.get());
InitializeIcuOrDie();
MediaPlayerService::instantiate();
ResourceManagerService::instantiate();
registerExtensions();
ProcessState::self()->startThreadPool();
IPCThreadState::self()->joinThreadPool();
}
ProcessState
先看 sp<ProcessState> proc(ProcessState::self()); 从ProcessState::self看起
//该函数是一个单例模式,初始状态下gProcess为空,会创建ProcessState对象并返回
sp<ProcessState> ProcessState::self()
{
Mutex::Autolock _l(gProcessMutex);
if (gProcess != NULL) {
return gProcess;
}
gProcess = new ProcessState;
return gProcess;
}
既然返回了ProcessState的对象,那自然得看下ProcessState的构造函数了; 在ProcessState的初始化列表中打开了binder节点(open_driver())
ProcessState::ProcessState()
: mDriverFD(open_driver())
, mVMStart(MAP_FAILED)
, mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
, mThreadCountDecrement(PTHREAD_COND_INITIALIZER)
, mExecutingThreadsCount(0)
, mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
, mStarvationStartTimeMs(0)
, mManagesContexts(false)
, mBinderContextCheckFunc(NULL)
, mBinderContextUserData(NULL)
, mThreadPoolStarted(false)
, mThreadPoolSeq(1)
{
if (mDriverFD >= 0) {
// 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;
}
}
}
open_driver的部分实现如下:
static int open_driver()
{
int fd = open("/dev/binder", O_RDWR | O_CLOEXEC);
......
}
defaultServiceManager
然后继续查看sp<IServiceManager> sm(defaultServiceManager()); defaultServiceManager的实现在IServiceManager.cpp中,该函数会返回一个IServiceManager, 同样也是一个单例模式
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的getContextObject函数,参数为null, 也就是0
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) {
IBinder* b = e->binder;
if (b == NULL || !e->refs->attemptIncWeak(this)) {
if (handle == 0) {
Parcel data;
status_t status = IPCThreadState::self()->transact(
0, IBinder::PING_TRANSACTION, data, NULL, 0);
if (status == DEAD_OBJECT)
return NULL;
}
//可以看到,其实就是返回了一个BpBinder对象
b = new BpBinder(handle);
//将binder存储到handle为0的句柄中去了
e->binder = b;
if (b) e->refs = b->getWeakRefs();
result = b;
}
看一下BpBinder, 似乎没什么特别的
BpBinder::BpBinder(int32_t handle)
: mHandle(handle)
, mAlive(1)
, mObitsSent(0)
, mObituaries(NULL)
{
ALOGV("Creating BpBinder %p handle %d\n", this, mHandle);
extendObjectLifetime(OBJECT_LIFETIME_WEAK);
IPCThreadState::self()->incWeakHandle(handle);
}
继续再回去看
gDefaultServiceManager = interface_cast<IServiceManager>(ProcessState::self()->getContextObject(NULL));
现在其实就是
gDefaultServiceManager = interface_cast<IServiceManager>(new BpBinder(0));
那么问题来了,BpBinder对象是如何转换成IServiceManager对象呢
继续查看下interface_cast, 函数位于IInterface.h
template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
return INTERFACE::asInterface(obj);
}
所以现在就变成了
IServiceManager::asInterface(new BpBinder(0));
这个时候再看一眼IServiceManager, 位于文件IServiceManager.h中有这样一个宏
DECLARE_META_INTERFACE(ServiceManager);
DECLARE_META_INTERFACE定义在IInterface.h中
#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();
翻译一下就是
//定义一个描述的字符串
static const android::String16 descriptor;
//定义adInterface函数
static android::sp<IServiceManager> asInterface(
const android::sp<android::IBinder> &obj);
//返回上面那个string
virtual const android::String16 &getInterfaceDescriptor() const;
定义构造函数和析构函数
IServiceManager();
virtual ~IServiceManager();
既然定义了,那肯定需要实现,在IServiceManager中是如何实现的呢;在IServiceManager中有这么一行宏
IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager");
继续看IMPLEMENT_META_INTERFACE的实现,也是在IInterface.h中
#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() { } \
继续翻译一下
const android::String16 IServiceManager::descriptor("android.os.IServiceManager");
const android::String16&IServiceManager::getInterfaceDescriptor() const {
return IServiceManager::descriptor;
}
android::sp<IServiceManager> IServiceManager::asInterface(
const android::sp<android::IBinder> &boj)
{
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;
}
IServiceManager::IServiceManager(){}
IServiceManager::~IServiceManager(){}
最后再看一下BpServiceManager就明白了, BpServiceManager的父类正是BpInterface<IServiceManager>, 到这里关于BpBinder对象是如何转换为IServiceManager的已经很清楚了
class BpServiceManager : public BpInterface<IServiceManager>
{
public:
BpServiceManager(const sp<IBinder>& impl)
: BpInterface<IServiceManager>(impl)
{
}
......
}
那么上文说到,返回了BpServiceManager对象,那么就继续看看BpServiceManager的构造函数中干了什么,可以看到在构造函数的初始化列表中调用了基类BpInterface的构造函数
template<typename INTERFACE>
inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)
: BpRefBase(remote)
{
}
BpInterface调用了基类BpRefBase的构造函数,该函数位于Binder.cpp中; 在BpRefBase的初始化列表中mRemote(o.get()), 最终就是mRemote = new BpBinder(0);
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.
}
}
参考:
1.《深入理解Android 卷1》
代码来源:Firefly-RK3399 Android 7.1
网友评论