`
zzu_007
  • 浏览: 23915 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Android源码之Binder(五)

阅读更多
Service组件在启动时,需要将自己注册到Service Manager中,而Client组件在使用Service组件提供的服务之前,也需要通过Service Manager来获得Service组件的代理对象。由于Service Manager本身也是一个Service组件,因此其他的Service组件和Client组件在使用它提供的服务之前,也需要先获得它的代理对象。
我们就来看一下Service Manager代理对象的获取过程。
我们先来看一下Binder库中最底层的接口IServiceManager的定义:
class IServiceManager : public IInterface
{
public:
DECLARE_META_INTERFACE(ServiceManager);
[// DECLARE_META_INTERFACE(ServiceManager)
DECLARE_META_INTERFACE是一个宏,这个宏声明了几个很重要的函数。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();                                            \
在DECLARE_META_INTERFACE宏中除了定义构造和析构函数之外,还定义了一个String类型的变量descriptor,表示该接口的描述。
getInterfaceDescriptor用于返回该接口的表示,也就是descriptor。
除此之外,还定义了一个asInterface函数,这个函数是干什么的呢?请各位客官向下看...
在IInterface.h文件中,还定义了一个IMPLEMENT_META_INTERFACE宏,由名字看和DECLARE_META_INTERFACE是相对应的。
IMPLEMENT_META_INTERFACE的定义如下:
#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() { }                                   \

IMPLEMENT_META_INTERFACE宏确实是和DECLARE_META_INTERFACE对应的,连里面的函数都是一样的!
IMPLEMENT_META_INTERFACE宏最重要的是asInterface函数。我们重点分析asInterface函数:
asInterface的作用是将一个Binder接口返回一个用户定义接口(在这里就是IServiceManager):
asInterface函数的参数是一个Binder本地对象或者一个Binder代理对象。
不管传入的什么,都会先调用queryLocalInterface函数。queryLocalInterface函数其实是在IBinder接口中定义的,默认的实现如下:
sp<IInterface>  IBinder::queryLocalInterface(const String16& descriptor)
{
return NULL;
}
queryLocalInterface函数默认返回NULL, 而BnInterface重写了queryLocalInterface函数, 定义如下:
template<typename INTERFACE>
inline sp<IInterface> BnInterface<INTERFACE>::queryLocalInterface(
const String16& _descriptor)
{
if (_descriptor == INTERFACE::descriptor) return this;
return NULL;
}
BnInterface的queryLocalInterface实现是将自己返回。
而BpBinder没有重写queryLocalInterface函数,所以调用BpBinder的queryLocalInterface就会返回NULL。
如果传递的是一个Binder本地对象,则可以直接调用queryLocalInterface函数后直接转换,否则就根据BpBinder构造一个BpInterface,并返回。
]// DECLARE_META_INTERFACE(ServiceManager)

/**
* Retrieve an existing service, blocking for a few seconds
* if it doesn't yet exist.
*/
virtual sp<IBinder>         getService( const String16& name) const = 0;

/**
* Retrieve an existing service, non-blocking.
*/
virtual sp<IBinder>         checkService( const String16& name) const = 0;

/**
* Register a service.
*/
virtual status_t            addService( const String16& name,
const sp<IBinder>& service,
bool allowIsolated = false) = 0;

/**
* Return list of all existing services.
*/
virtual Vector<String16>    listServices() = 0;

enum {
GET_SERVICE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
CHECK_SERVICE_TRANSACTION,
ADD_SERVICE_TRANSACTION,
LIST_SERVICES_TRANSACTION,
};
};
对于一般的Service组件来说,Client进程首先要通过Binder驱动程序来获得它的一个句柄值,然后才可以根据这个句柄值创建一个Binder代理对象,然后将这个Binder代理对象封装成一个实现了特定接口的代理对象。
由于Service Manager的句柄值恒为0,因此,获取它的一个代理对象的过程就省去了与Binder驱动程序交互的过程。
在实际的编码中,我们一般是通过调用一个defaultServiceManager()函数来得到Service Manager Binder代理对象。
defaultServiceManager函数定义如下:
sp<IServiceManager> defaultServiceManager()
{
if (gDefaultServiceManager != NULL) return gDefaultServiceManager;
[// if (gDefaultServiceManager != NULL) return gDefaultServiceManager
gDefaultServiceManager和gDefaultServiceManagerLock是两个全局变量,保证每个进程只有一个Service Manager对象。
这两个变量都是定义在Static.h文件中
]// if (gDefaultServiceManager != NULL) return gDefaultServiceManager

{
AutoMutex _l(gDefaultServiceManagerLock);
if (gDefaultServiceManager == NULL) {
gDefaultServiceManager = interface_cast<IServiceManager>(ProcessState::self()->getContextObject(NULL));
[// gDefaultServiceManager = interface_cast<IServiceManager>(ProcessState::self()->getContextObject(NULL));
如果gDefaultServiceManager为null, 则调用ProcessState的getContextObject函数来得到Service Manager代理对象:
getContextObject函数的定义如下:
sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& caller)
{
return getStrongProxyForHandle(0);
[// return getStrongProxyForHandle(0)
这里调用getStrongProxyForHandle函数来查找具体的Binder代理对象,只不过传入了一个特殊参数0.
getStrongProxyForHandle函数定义如下:
sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
{
sp<IBinder> result;

AutoMutex _l(mLock);

handle_entry* e = lookupHandleLocked(handle);
[// handle_entry* e = lookupHandleLocked(handle)
这里会调用lookupHandleLocked来根据句柄值查找得到一个Binder代理对象,并返回一个handle_entry结构体。
struct handle_entry {
IBinder* binder;
RefBase::weakref_type* refs;
};
lookupHandleLocked函数的定义如下:
ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
{
const size_t N=mHandleToObject.size();
[// const size_t N=mHandleToObject.size()
这里的mHandleToObject保存了所有的Binder代理对象
Vector<handle_entry>mHandleToObject;
]// const size_t N=mHandleToObject.size()
if (N <= (size_t)handle) {
[// if (N <= (size_t)handle)
这里的句柄值就是在mHandleToObject的索引值
]// 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);
}

]// 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);
[// b = new BpBinder(handle)
这里如果发现之前没有保存过该Binder代理对象,或者弱引用小于0,表示该Binder代理对象已经失效,则会创建一个新的Binder代理对象。
BpBinder类的定义如下:
class BpBinder : public IBinder
{
public:
BpBinder(int32_t handle);
[// BpBinder(int32_t handle)
BpBinder的构造函数如下:
BpBinder::BpBinder(int32_t handle)
: mHandle(handle)
[// mHandle(handle)
这里mHandle就保存了Service组件的句柄值。
]// 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);
}
]// BpBinder(int32_t handle)

inline  int32_t     handle() const { return mHandle; }

virtual const String16&    getInterfaceDescriptor() const;
virtual bool        isBinderAlive() const;
virtual status_t    pingBinder();
virtual status_t    dump(int fd, const Vector<String16>& args);

virtual status_t    transact(   uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);

virtual status_t    linkToDeath(const sp<DeathRecipient>& recipient,
void* cookie = NULL,
uint32_t flags = 0);
virtual status_t    unlinkToDeath(  const wp<DeathRecipient>& recipient,
void* cookie = NULL,
uint32_t flags = 0,
wp<DeathRecipient>* outRecipient = NULL);

virtual void        attachObject(   const void* objectID,
void* object,
void* cleanupCookie,
object_cleanup_func func);
virtual void*       findObject(const void* objectID) const;
virtual void        detachObject(const void* objectID);

virtual BpBinder*   remoteBinder();

status_t    setConstantData(const void* data, size_t size);
void        sendObituary();

class ObjectManager
{
public:
ObjectManager();
~ObjectManager();

void        attach( const void* objectID,
void* object,
void* cleanupCookie,
IBinder::object_cleanup_func func);
void*       find(const void* objectID) const;
void        detach(const void* objectID);

void        kill();

private:
ObjectManager(const ObjectManager&);
ObjectManager& operator=(const ObjectManager&);

struct entry_t
{
void* object;
void* cleanupCookie;
IBinder::object_cleanup_func func;
};

KeyedVector<const void*, entry_t> mObjects;
};

protected:
virtual             ~BpBinder();
virtual void        onFirstRef();
virtual void        onLastStrongRef(const void* id);
virtual bool        onIncStrongAttempted(uint32_t flags, const void* id);

private:
const   int32_t             mHandle;

struct Obituary {
wp<DeathRecipient> recipient;
void* cookie;
uint32_t flags;
};

void                reportOneDeath(const Obituary& obit);
bool                isDescriptorCached() const;

mutable Mutex               mLock;
volatile int32_t    mAlive;
volatile int32_t    mObitsSent;
Vector<Obituary>*   mObituaries;
ObjectManager       mObjects;
Parcel*             mConstantData;
mutable String16            mDescriptorCache;
};
]// 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;
}
]// return getStrongProxyForHandle(0)
}
当调用getContextObject函数得到Binder代理对象之后,就可以调用interface_cast来将它转换成特定的接口
interface_cast是个全局的inline函数,定义在IInterface.h文件中,定义如下:
template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
return INTERFACE::asInterface(obj);
[// return INTERFACE::asInterface(obj);
实际上就是调用asInterface函数,还记得asInterface函数么?asInterface是用IMPLEMENT_META_INTERFACE宏和DECLARE_META_INTERFACE宏实现的。详细信息见上面。
]// return INTERFACE::asInterface(obj);
}
]// gDefaultServiceManager = interface_cast<IServiceManager>(ProcessState::self()->getContextObject(NULL));
}
}

return gDefaultServiceManager;
}

我们下面分析一下Service组件的启动过程。Service进程在启动时,会首先将自己的Service组件注册到Service Manager中,接着就是启动Binder线程池来等待和处理Client进程的通信请求。
当我们得到了ServiceManager的代理对象之后,就会调用addService来注册Service组件。
这实际上是调用BpServiceManager类的成员函数addService来注册Service组件的,BpServiceManager的addService函数的定义如下:
virtual status_t addService(const String16& name, const sp<IBinder>& service, bool allowIsolated)
    {
        Parcel data, reply;
        data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
[// data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor())
首先调用writeInterfaceToken函数写入Service组件的描述。
// Write RPC headers.  (previously just the interface token)
status_t Parcel::writeInterfaceToken(const String16& interface)
{
writeInt32(IPCThreadState::self()->getStrictModePolicy() | STRICT_MODE_PENALTY_GATHER);
[// writeInt32(IPCThreadState::self()->getStrictModePolicy() | STRICT_MODE_PENALTY_GATHER);

]// writeInt32(IPCThreadState::self()->getStrictModePolicy() | STRICT_MODE_PENALTY_GATHER);
// currently the interface identification token is just its name as a string
return writeString16(interface);
[// return writeString16(interface)
接着调用writeString16函数来写入这个Service组件的描述。
status_t Parcel::writeString16(const String16& str)
{
return writeString16(str.string(), str.size());
[// return writeString16(str.string(), str.size())
status_t Parcel::writeString16(const char16_t* str, size_t len)
{
if (str == NULL) return writeInt32(-1);

status_t err = writeInt32(len);
if (err == NO_ERROR) {
len *= sizeof(char16_t);
uint8_t* data = (uint8_t*)writeInplace(len+sizeof(char16_t));
if (data) {
memcpy(data, str, len);
*reinterpret_cast<char16_t*>(data+len) = 0;
return NO_ERROR;
}
err = mError;
}
return err;
}
有writeString16函数可知,writeString16的实现原理就是先写入长度,然后拷贝数据。
]// return writeString16(str.string(), str.size())
}
]// return writeString16(interface)
}
]// data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor())
        data.writeString16(name);
        data.writeStrongBinder(service);
[// data.writeStrongBinder(service)
调用writeStrongBinder来写入一个Service组件。
status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
{
return flatten_binder(ProcessState::self(), val, this);
[// return flatten_binder(ProcessState::self(), val, this)
status_t flatten_binder(const sp<ProcessState>& proc, const sp<IBinder>& binder, Parcel* out)
{
flat_binder_object obj;

obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
if (binder != NULL) {
IBinder *local = binder->localBinder();
[// IBinder *local = binder->localBinder()
localBinder函数其实是来自与BBinder类,BBinder的localBinder函数定义如下:
BBinder* BBinder::localBinder()
{
return this;
}
]// IBinder *local = binder->localBinder()
if (!local) {
BpBinder *proxy = binder->remoteBinder();
if (proxy == NULL) {
ALOGE("null proxy");
}
const int32_t handle = proxy ? proxy->handle() : 0;
obj.type = BINDER_TYPE_HANDLE;
obj.handle = handle;
obj.cookie = NULL;
} else {
obj.type = BINDER_TYPE_BINDER;
obj.binder = local->getWeakRefs();
[// obj.binder = local->getWeakRefs()
这里会调用getWeakRefs来返回一个Service组件的弱引用对象
]// obj.binder = local->getWeakRefs()
obj.cookie = local;
}
} else {
obj.type = BINDER_TYPE_BINDER;
obj.binder = NULL;
obj.cookie = NULL;
}

return finish_flatten_binder(binder, obj, out);
[// return finish_flatten_binder(binder, obj, out)
inline static status_t finish_flatten_binder(const sp<IBinder>& binder, const flat_binder_object& flat, Parcel* out)
{
return out->writeObject(flat, false);
[// return out->writeObject(flat, false)
status_t Parcel::writeObject(const flat_binder_object& val, bool nullMetaData)
{
const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
const bool enoughObjects = mObjectsSize < mObjectsCapacity;
if (enoughData && enoughObjects) {
restart_write:
*reinterpret_cast<flat_binder_object*>(mData+mDataPos) = val;

// Need to write meta-data?
if (nullMetaData || val.binder != NULL) {
mObjects[mObjectsSize] = mDataPos;
acquire_object(ProcessState::self(), val, this);
mObjectsSize++;
}

// remember if it's a file descriptor
if (val.type == BINDER_TYPE_FD) {
if (!mAllowFds) {
return FDS_NOT_ALLOWED;
}
mHasFds = mFdsKnown = true;
}

return finishWrite(sizeof(flat_binder_object));
}

if (!enoughData) {
const status_t err = growData(sizeof(val));
if (err != NO_ERROR) return err;
}
if (!enoughObjects) {
size_t newSize = ((mObjectsSize+2)*3)/2;
size_t* objects = (size_t*)realloc(mObjects, newSize*sizeof(size_t));
if (objects == NULL) return NO_MEMORY;
mObjects = objects;
mObjectsCapacity = newSize;
}

goto restart_write;
}
]// return out->writeObject(flat, false)
}
]// return finish_flatten_binder(binder, obj, out)
}
]// return flatten_binder(ProcessState::self(), val, this)
}
]// data.writeStrongBinder(service)
        data.writeInt32(allowIsolated ? 1 : 0);
        status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);
[// status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply)
这里就开始向Binder驱动程序传递数据了。
首先调用remote()函数,remote函数其实是从BpRefBase中继承来的,定义如下:
inline  IBinder*        remote()                { return mRemote; }
BpRefBase类remote函数只是简单的返回成员变量mRemote,mRemote其实是个BpBinder类型的对象。因此这里调用transact实际调用的是BpBinder类的transact函数。
我们来看一下BpBinder类的transact函数的实现:
status_t BpBinder::transact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
// Once a binder has died, it will never come back to life.
if (mAlive) {
status_t status = IPCThreadState::self()->transact(mHandle, code, data, reply, flags);
[// status_t status = IPCThreadState::self()->transact(mHandle, code, data, reply, flags)
这里参数mHandle其实就是Binder本地对象的句柄值。
这里会调用IPCThreadState的transact函数来和Binder驱动进行数据交互:
status_t IPCThreadState::transact(int32_t handle,
                                  uint32_t code, const Parcel& data,
                                  Parcel* reply, uint32_t flags)
{
status_t err = data.errorCheck();

flags |= TF_ACCEPT_FDS;

IF_LOG_TRANSACTIONS() {
TextOutput::Bundle _b(alog);
alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
<< handle << " / code " << TypeCode(code) << ": "
<< indent << data << dedent << endl;
}

if (err == NO_ERROR) {
LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
(flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);
[// err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL)
这里调用writeTransactionData来写入binder_transaction_data数据
status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags, int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
{
binder_transaction_data tr;

tr.target.handle = handle;
tr.code = code;
tr.flags = binderFlags;
tr.cookie = 0;
tr.sender_pid = 0;
tr.sender_euid = 0;

const status_t err = data.errorCheck();
if (err == NO_ERROR) {
tr.data_size = data.ipcDataSize();
tr.data.ptr.buffer = data.ipcData();
tr.offsets_size = data.ipcObjectsCount()*sizeof(size_t);
tr.data.ptr.offsets = data.ipcObjects();
} else if (statusBuffer) {
tr.flags |= TF_STATUS_CODE;
*statusBuffer = err;
tr.data_size = sizeof(status_t);
tr.data.ptr.buffer = statusBuffer;
tr.offsets_size = 0;
tr.data.ptr.offsets = NULL;
} else {
return (mLastError = err);
}

mOut.writeInt32(cmd);
mOut.write(&tr, sizeof(tr));
[// mOut.write(&tr, sizeof(tr))
写入binder_transaction_data数据
]// mOut.write(&tr, sizeof(tr))
return NO_ERROR;
}
]// err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL)
}

if (err != NO_ERROR) {
if (reply) reply->setError(err);
return (mLastError = err);
}

if ((flags & TF_ONE_WAY) == 0) {
#if 0
if (code == 4) { // relayout
ALOGI(">>>>>> CALLING transaction 4");
} else {
ALOGI(">>>>>> CALLING transaction %d", code);
}
#endif
if (reply) {
err = waitForResponse(reply);
[// err = waitForResponse(reply)
这里调用waitForResponse来发送和得到Binder驱动程序的返回
status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
{
int32_t cmd;
int32_t err;

while (1) {
if ((err=talkWithDriver()) < NO_ERROR) break;
[// if ((err=talkWithDriver()) < NO_ERROR) break
这里就调用talkWithDriver函数来和Binder驱动程序交互数据。
]// if ((err=talkWithDriver()) < NO_ERROR) break
err = mIn.errorCheck();
if (err < NO_ERROR) break;
if (mIn.dataAvail() == 0) continue;

cmd = mIn.readInt32();

IF_LOG_COMMANDS() {
alog << "Processing waitForResponse Command: "
<< getReturnString(cmd) << endl;
}

switch (cmd) {
case BR_TRANSACTION_COMPLETE:
if (!reply && !acquireResult) goto finish;
break;

case BR_DEAD_REPLY:
err = DEAD_OBJECT;
goto finish;

case BR_FAILED_REPLY:
err = FAILED_TRANSACTION;
goto finish;

case BR_ACQUIRE_RESULT:
{
ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
const int32_t result = mIn.readInt32();
if (!acquireResult) continue;
*acquireResult = result ? NO_ERROR : INVALID_OPERATION;
}
goto finish;

case BR_REPLY:
{
binder_transaction_data tr;
err = mIn.read(&tr, sizeof(tr));
ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
if (err != NO_ERROR) goto finish;

if (reply) {
if ((tr.flags & TF_STATUS_CODE) == 0) {
reply->ipcSetDataReference(
reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
tr.data_size,
reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
tr.offsets_size/sizeof(size_t),
freeBuffer, this);
} else {
err = *static_cast<const status_t*>(tr.data.ptr.buffer);
freeBuffer(NULL,
reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
tr.data_size,
reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
tr.offsets_size/sizeof(size_t), this);
}
} else {
freeBuffer(NULL,
reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
tr.data_size,
reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
tr.offsets_size/sizeof(size_t), this);
continue;
}
}
goto finish;

default:
err = executeCommand(cmd);
if (err != NO_ERROR) goto finish;
break;
}
}

finish:
if (err != NO_ERROR) {
if (acquireResult) *acquireResult = err;
if (reply) reply->setError(err);
mLastError = err;
}

return err;
}
]// err = waitForResponse(reply)
} else {
Parcel fakeReply;
err = waitForResponse(&fakeReply);
}
#if 0
if (code == 4) { // relayout
ALOGI("<<<<<< RETURNING transaction 4");
} else {
ALOGI("<<<<<< RETURNING transaction %d", code);
}
#endif

IF_LOG_TRANSACTIONS() {
TextOutput::Bundle _b(alog);
alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
<< handle << ": ";
if (reply) alog << indent << *reply << dedent << endl;
else alog << "(none requested)" << endl;
}
} else {
err = waitForResponse(NULL, NULL);
}

return err;
}
]// status_t status = IPCThreadState::self()->transact(mHandle, code, data, reply, flags)
if (status == DEAD_OBJECT) mAlive = 0;
return status;
}

return DEAD_OBJECT;
}

]// status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply)
        return err == NO_ERROR ? reply.readExceptionCode() : err;
    }

上面我们的分析都是集中在C++层的实现。接下来,我们分析一下Java层的Binder机制的实现:
和c++层一样,在使用系统的Binder机制的时候,首先需要获得ServiceManager的代理对象,这是通过调用Java层的ServiceManager类的getIServiceManager函数实现的:
private static IServiceManager getIServiceManager() {
        if (sServiceManager != null) {
            return sServiceManager;
[// return sServiceManager
sServiceManager是一个静态的IServiceManager对象,定义如下:
private static IServiceManager sServiceManager;
IServiceManager定义在IServiceManager.java文件中,声明如下:
public interface IServiceManager extends IInterface
而IInterface的定义如下:
public interface IInterface
                {
                    /**
                     * Retrieve the Binder object associated with this interface.
                     * You must use this instead of a plain cast, so that proxy objects
                     * can return the correct result.
                     */
                    public IBinder asBinder();
                    [// public IBinder asBinder()
                    IBinder接口定义在IBinder.java文件中:
                    public interface IBinder {
                            /**
                             * The first transaction code available for user commands.
                             */
                            int FIRST_CALL_TRANSACTION  = 0x00000001;
                            /**
                             * The last transaction code available for user commands.
                             */
                            int LAST_CALL_TRANSACTION   = 0x00ffffff;

                            /**
                             * IBinder protocol transaction code: pingBinder().
                             */
                            int PING_TRANSACTION        = ('_'<<24)|('P'<<16)|('N'<<8)|'G';

                            /**
                             * IBinder protocol transaction code: dump internal state.
                             */
                            int DUMP_TRANSACTION        = ('_'<<24)|('D'<<16)|('M'<<8)|'P';

                            /**
                             * IBinder protocol transaction code: interrogate the recipient side
                             * of the transaction for its canonical interface descriptor.
                             */
                            int INTERFACE_TRANSACTION   = ('_'<<24)|('N'<<16)|('T'<<8)|'F';

                            int TWEET_TRANSACTION   = ('_'<<24)|('T'<<16)|('W'<<8)|'T';

                            int LIKE_TRANSACTION   = ('_'<<24)|('L'<<16)|('I'<<8)|'K';

                            /** @hide */
                            int SYSPROPS_TRANSACTION = ('_'<<24)|('S'<<16)|('P'<<8)|'R';

                            int FLAG_ONEWAY             = 0x00000001;

                            /**
                             * Get the canonical name of the interface supported by this binder.
                             */
                            public String getInterfaceDescriptor() throws RemoteException;

                            public boolean pingBinder();

                            public boolean isBinderAlive();

                            public IInterface queryLocalInterface(String descriptor);

                            public void dump(FileDescriptor fd, String[] args) throws RemoteException;

                            public void dumpAsync(FileDescriptor fd, String[] args) throws RemoteException;

                            public boolean transact(int code, Parcel data, Parcel reply, int flags)
                                throws RemoteException;

                            public interface DeathRecipient {
                                public void binderDied();
                            }

                            public void linkToDeath(DeathRecipient recipient, int flags)
                                    throws RemoteException;

                            public boolean unlinkToDeath(DeathRecipient recipient, int flags);
                        }

                    ]// public IBinder asBinder()
                }
这貌似和C++层的设计很像啊!

]// return sServiceManager
        }

        // Find the service manager
        sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());
        [// sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject())
这里会得到ServiceManager的代理对象来初始化sServiceManager.
调用BinderInternal.getContextObject()会得到ServiceManager的Java服务代理对象,接着调用ServiceManagerNative的asInterface将这个Java服务代理对象封装成一个ServiceManagerProxy对象.
我们首先分析BinderInternal.getContextObject()的实现:
public static final native IBinder getContextObject();
getContextObject是个Native函数,实际上会调用android_util_Binder.cpp的android_os_BinderInternal_getContextObject函数,如下所示:
static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
            {
                sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
                [// sp<IBinder> b = ProcessState::self()->getContextObject(NULL)
这里会调用ProcessState对象的成员函数getContextObject来获得一个句柄值等于NULL,即等于0的Binder代理对象,即一个BpBinder对象.
                ]// sp<IBinder> b = ProcessState::self()->getContextObject(NULL)
                return javaObjectForIBinder(env, b);
                [// return javaObjectForIBinder(env, b)
                这里会调用javaObjectForIBinder来将刚刚得到的BpBinder对象封装成一个Java服务代理对象.javaObjectForIBinder的函数实现如下:
                jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
                    {
                        if (val == NULL) return NULL;

                        if (val->checkSubclass(&gBinderOffsets)) {
                        [// if (val->checkSubclass(&gBinderOffsets))
这里gBinderOffsets定义在android_util_Binder.cpp文件中,是一个bindernative_offsets_t结构体对象:
static struct bindernative_offsets_t
                            {
                                // Class state.
                                jclass mClass;
                                [// jclass mClass
                                mClass指向Java层中的Binder类
                                ]// jclass mClass
                                jmethodID mExecTransact;
[// jmethodID mExecTransact
mExecTransact指向mClass所指向Java层中的Binder类的成员函数execTransact
]// jmethodID mExecTransact
                                // Object state.
                                jfieldID mObject;
[// jfieldID mObject
mObject指向mClass指向所Java层中的Binder类的成员变量mObject
]// jfieldID mObject
                            } gBinderOffsets;
                            gBinderOffsets全局变量是在int_register_android_od_Binder中初始化的:
static int int_register_android_os_Binder(JNIEnv* env)
                            {
                                jclass clazz = FindClassOrDie(env, kBinderPathName);
[// jclass clazz = FindClassOrDie(env, kBinderPathName)
const char* const kBinderPathName = "android/os/Binder";
这里clazz指向了Java层的Binder类
]// jclass clazz = FindClassOrDie(env, kBinderPathName)
                                gBinderOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
                                gBinderOffsets.mExecTransact = GetMethodIDOrDie(env, clazz, "execTransact", "(IJJI)Z");
                                gBinderOffsets.mObject = GetFieldIDOrDie(env, clazz, "mObject", "J");

                                return RegisterMethodsOrDie(
                                    env, kBinderPathName,
                                    gBinderMethods, NELEM(gBinderMethods));
                            }
                        ]// if (val->checkSubclass(&gBinderOffsets))

                            // One of our own!
                            jobject object = static_cast<JavaBBinder*>(val.get())->object();
                            LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);
                            return object;
                        }

                        // For the rest of the function we will hold this lock, to serialize
                        // looking/creation of Java proxies for native Binder proxies.
                        AutoMutex _l(mProxyLock);

                        // Someone else's...  do we know about it?
                        jobject object = (jobject)val->findObject(&gBinderProxyOffsets);
                        [// jobject object = (jobject)val->findObject(&gBinderProxyOffsets)
这里gBinderProxyOffsets是定义在android_util_Binder.cpp文件中,是一个binderproxy_offsets_t结构体对象:
static struct binderproxy_offsets_t
                            {
                                // Class state.
                                jclass mClass;
                                [// jclass mClass
                                mClass指向Java层中的BinderProxy类
                                ]// jclass mClass
                                jmethodID mConstructor;
                                [// jmethodID mConstructor
                                mConstructor指向BinderProxy类的构造函数
                                ]// jmethodID mConstructor
                                jmethodID mSendDeathNotice;
[// jmethodID mSendDeathNotice
mSendDeathNotice指向BinderProxy类的静态成员函数sendDeathNotice
]// jmethodID mSendDeathNotice
                                // Object state.
                                jfieldID mObject;
                                [// jfieldID mObject
                                mObject指向BinderProxy的成员变量mObject
                                ]// jfieldID mObject
                                jfieldID mSelf;
                                [// jfieldID mSelf
                                mSelf指向BinderProxy的成员变量mSelf
                                ]// jfieldID mSelf
                                jfieldID mOrgue;

                            } gBinderProxyOffsets;
                            全局变量gBinderProxyOffsets实在函数int_register_android_os_BinderProxy中初始化的:
                            static int int_register_android_os_BinderProxy(JNIEnv* env)
                            {
                                jclass clazz = FindClassOrDie(env, "java/lang/Error");
                                gErrorOffsets.mClass = MakeGlobalRefOrDie(env, clazz);

                                clazz = FindClassOrDie(env, kBinderProxyPathName);
                                [// clazz = FindClassOrDie(env, kBinderProxyPathName)
                                const char* const kBinderProxyPathName = "android/os/BinderProxy";
                                clazz类指向Java层的BinderProxy类.
                                ]// clazz = FindClassOrDie(env, kBinderProxyPathName)
                                gBinderProxyOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
                                gBinderProxyOffsets.mConstructor = GetMethodIDOrDie(env, clazz, "<init>", "()V");
                                gBinderProxyOffsets.mSendDeathNotice = GetStaticMethodIDOrDie(env, clazz, "sendDeathNotice",
                                        "(Landroid/os/IBinder$DeathRecipient;)V");

                                gBinderProxyOffsets.mObject = GetFieldIDOrDie(env, clazz, "mObject", "J");
                                gBinderProxyOffsets.mSelf = GetFieldIDOrDie(env, clazz, "mSelf",
                                                                            "Ljava/lang/ref/WeakReference;");
                                gBinderProxyOffsets.mOrgue = GetFieldIDOrDie(env, clazz, "mOrgue", "J");

                                clazz = FindClassOrDie(env, "java/lang/Class");
                                gClassOffsets.mGetName = GetMethodIDOrDie(env, clazz, "getName", "()Ljava/lang/String;");

                                return RegisterMethodsOrDie(
                                    env, kBinderProxyPathName,
                                    gBinderProxyMethods, NELEM(gBinderProxyMethods));
                            }

这里val是一个BpBinder对象, 这里调用BpBinder的findObject函数定义如下:
void* BpBinder::findObject(const void* objectID) const
                            {
                                AutoMutex _l(mLock);
                                return mObjects.find(objectID);
                                [// return mObjects.find(objectID)
                                BpBinder类的mObjects成员变量是一个ObjectManager类型的对象.
                                ObjectManager       mObjects;
关于ObjectManager的分析可以参考前面的分析.
                                ]// return mObjects.find(objectID)
                            }
                        ]// jobject object = (jobject)val->findObject(&gBinderProxyOffsets)
                        if (object != NULL) {
                            jobject res = jniGetReferent(env, object);
                            if (res != NULL) {
                                ALOGV("objectForBinder %p: found existing %p!\n", val.get(), res);
                                return res;
                            }
                            LOGDEATH("Proxy object %p of IBinder %p no longer in working set!!!", object, val.get());
                            android_atomic_dec(&gNumProxyRefs);
                            val->detachObject(&gBinderProxyOffsets);
                            env->DeleteGlobalRef(object);
                        }

                        object = env->NewObject(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mConstructor);
                        [// object = env->NewObject(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mConstructor)
                        这里构造一个Java层的BinderProxy对象.
                        ]// object = env->NewObject(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mConstructor)
                        if (object != NULL) {
                            LOGDEATH("objectForBinder %p: created new proxy %p !\n", val.get(), object);
                            // The proxy holds a reference to the native object.
                            env->SetLongField(object, gBinderProxyOffsets.mObject, (jlong)val.get());
                            [// env->SetLongField(object, gBinderProxyOffsets.mObject, (jlong)val.get())
                            这里将刚刚创建的Binder代理对象设置到Java层的BinderProxy的mObject成员变量中去.
                            ]// env->SetLongField(object, gBinderProxyOffsets.mObject, (jlong)val.get())
                            val->incStrong((void*)javaObjectForIBinder);

                            // The native object needs to hold a weak reference back to the
                            // proxy, so we can retrieve the same proxy if it is still active.
                            jobject refObject = env->NewGlobalRef(
                                    env->GetObjectField(object, gBinderProxyOffsets.mSelf));
                            val->attachObject(&gBinderProxyOffsets, refObject,
                                    jnienv_to_javavm(env), proxy_cleanup);

                            // Also remember the death recipients registered on this proxy
                            sp<DeathRecipientList> drl = new DeathRecipientList;
                            drl->incStrong((void*)javaObjectForIBinder);
                            env->SetLongField(object, gBinderProxyOffsets.mOrgue, reinterpret_cast<jlong>(drl.get()));

                            // Note that a new object reference has been created.
                            android_atomic_inc(&gNumProxyRefs);
                            incRefsCreated(env);
                        }

                        return object;
                    }
                ]// return javaObjectForIBinder(env, b)
            }
程序执行完BinderInternal.getContextObject()我们就获得了一个句柄值为0的Java服务代理对象,接下来就可以调用ServiceManagerNative类的静态成员函数asInterface将它封装成一个Service Manager的Java代理对象了.
ServiceManagerNative的asInterface函数实现如下:
static public IServiceManager asInterface(IBinder obj)
           {
            if (obj == null) {
                return null;
               }
              IServiceManager in =(IServiceManager)obj.queryLocalInterface(descriptor);
              [// IServiceManager in =(IServiceManager)obj.queryLocalInterface(descriptor)
              这里的obj是个BinderProxy对象, BinderProxy类定义在Binder.java文件中,它的queryLocalInterface函数返回null.
              public IInterface queryLocalInterface(String descriptor) {
                    return null;
                  }

              ]// IServiceManager in =(IServiceManager)obj.queryLocalInterface(descriptor)
                if (in != null) {
                return in;
               }

                return new ServiceManagerProxy(obj);
                [// return new ServiceManagerProxy(obj)
                这里会构造一个ServiceManagerProxy对象,并返回该对象.
public ServiceManagerProxy(IBinder remote) {
                   mRemote = remote;
                   [// mRemote = remote
                   private IBinder mRemote;
                   ]// mRemote = remote
                  }
                ]// return new ServiceManagerProxy(obj)
         }


        ]// sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject())
        return sServiceManager;
    }


aidl文件的Stub类继承了Binder类, 因此, 在创建具体的Java层的Binder本地对象的时候,会调用Binder类的构造函数来执行初始化操作.
Binder类的构造函数定义如下:
public Binder() {
    init();
    [// init()
    Binder的init函数是个native函数:
    private native final void init();
    它的实现定义在android_util_Binder.cpp文件中android_os_Binder_init函数,定义如下:
    static void android_os_Binder_init(JNIEnv* env, jobject obj)
            {
                JavaBBinderHolder* jbh = new JavaBBinderHolder();
                [// JavaBBinderHolder* jbh = new JavaBBinderHolder()
这里创建一个JavaBBinderHolder对象. JavaBBinderHolder的定义如下:
class JavaBBinderHolder : public RefBase
                    {
public:
sp<JavaBBinder> get(JNIEnv* env, jobject obj)
{
AutoMutex _l(mLock);
sp<JavaBBinder> b = mBinder.promote();
if (b == NULL) {
b = new JavaBBinder(env, obj);
[// b = new JavaBBinder(env, obj)
JavaBBinder类同样定义在android_util_Binder.cpp文件中,
class JavaBBinder : public BBinder
JavaBBinder继承了Binder库中的BBinder类, 用来描述一个Binder本地对象.
]// b = new JavaBBinder(env, obj)
mBinder = b;
ALOGV("Creating JavaBinder %p (refs %p) for Object %p, weakCount=%" PRId32 "\n",
b.get(), b->getWeakRefs(), obj, b->getWeakRefs()->getWeakCount());
}

return b;
}

sp<JavaBBinder> getExisting()
{
AutoMutex _l(mLock);
return mBinder.promote();
}

private:
Mutex           mLock;
wp<JavaBBinder> mBinder;
                    };

                ]// JavaBBinderHolder* jbh = new JavaBBinderHolder()
                if (jbh == NULL) {
                    jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
                    return;
                }
                ALOGV("Java Binder %p: acquiring first ref on holder %p", obj, jbh);
                jbh->incStrong((void*)android_os_Binder_init);
                env->SetLongField(obj, gBinderOffsets.mObject, (jlong)jbh);
                [// env->SetLongField(obj, gBinderOffsets.mObject, (jlong)jbh)
这里将刚刚创建的JavaBBinderHolder设置到gBinderOffsets中的mObject成员中, 这样就设置到Java层的Binder类的mObject成员变量中.
这样运行在Java层中的服务就可以通过它的成员变量mObject来访问运行在C++层中的JavaBBinderHolder对象jbh了.
                ]// env->SetLongField(obj, gBinderOffsets.mObject, (jlong)jbh)
            }
    ]// init()
     if (FIND_POTENTIAL_LEAKS) {
        final Class<? extends Binder> klass = getClass();
          if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && (klass.getModifiers() & Modifier.STATIC) == 0) {
           Log.w(TAG, "The following Binder class should be static or leaks might occur: " + klass.getCanonicalName());
          }
      }
   }
分享到:
评论

相关推荐

    Android底层源码分析_Binder

    ### Android底层源码分析_Binder #### 总体概述 Binder是Android系统中实现进程间通信(IPC)的核心机制之一。其设计模式基于客户端-服务器(Client-Server)架构,其中提供服务的一方称为Server进程,请求服务的...

    Android NDK实现Binder服务和客户端

    需要在系统源码下编译,或者提取出对应的头文件亦可。这里需要注意Android4.x以后系统SeLinux如果打开,系统级需要配置对应的sepolicy才能使用。测试阶段推荐直接setenforce 0关闭鉴权即可

    安卓Android源码——Android Launcher 源码修改可编译.zip

    "安卓Android源码——Android Launcher 源码修改可编译.zip" 这个标题表明我们关注的是Android操作系统的源代码,特别是与启动器(Launcher)相关的部分。Launcher是用户与Android系统交互的主要界面,它管理应用...

    Android系统的Binder机制之一——Service_Manager

    ### Android系统的Binder机制之一——Service_Manager #### 一、引言 在深入探讨Android系统中的Binder机制之前,我们首先简要回顾一下Binder机制的基本概念及其重要性。Android系统基于Linux内核,但在进程间通信...

    android native层 binder通信机制演示源码

    本压缩包提供了基于Android的Native层Binder通信的源码示例,主要包含了两个关键部分:BP(Binder Proxy)和BN(Binder Node)。BP通常位于客户端,负责将调用转化为跨进程的消息,而BN则在服务端,处理这些消息并...

    binder用例源码

    本用例源码着重展示了Binder在Native层的应用,适用于Android 2.3版本。 ### 1. Binder基础 Binder在Android中扮演了接口代理的角色,允许不同进程之间的对象调用对方的方法,实现了跨进程的远程方法调用(Remote ...

    android开发揭秘源码

    4. 参考开源项目:许多开源应用和库都基于Android源码进行了扩展,从中可以学习最佳实践。 四、源码学习价值 1. 解决问题:遇到系统级问题时,源码是查找问题根源的直接途径。 2. 性能优化:理解底层运行机制,有助...

    android源码

    Android源码是一个庞大的开源项目,包含了操作系统、中间件层、应用程序框架以及丰富的API库,是开发者深入了解Android系统工作原理和定制化开发的关键。这个名为"android源码.zip"的压缩包很可能包含了完整的...

    安卓系统源码 (android 14 rar)

    《安卓系统源码详解——基于Android 14的探索与学习》 Android系统源码是开发者深入了解操作系统工作原理、定制个性化系统以及优化应用性能的重要工具。Android 14的源码,作为Android发展历程中的一个重要版本,为...

    android源码开发实战3.05.zip

    《Android源码开发实战》是针对Android系统源码分析与应用开发的一本深入实践书籍,主要面向具有Android开发基础的开发者。"3.05"可能是书籍中的一个章节或者更新版本,具体的内容我们无法直接从文件名中获取,但...

    Android应用源码之音乐播放器源码.zip

    本篇文章将详细解析"Android应用源码之音乐播放器源码.zip"中的关键知识点,帮助你理解如何构建一个功能完善的Android音乐播放器。 1. **多媒体框架(MediaPlayer)**: Android提供了`MediaPlayer`类来处理音频和...

    Android的binder机制研究(C++部分)

    在Android源码中,与C/C++相关的Binder机制实现主要集中在以下文件中: - `frameworks\base\include\utils\IInterface.h`: 定义了一个通用接口`IInterface`,所有通过Binder机制暴露的服务都需继承该接口。 - `...

    安卓Android源码——安卓Android电子麦克风.zip

    这个名为“安卓Android源码——安卓Android电子麦克风”的压缩包很可能包含了一份关于Android系统中电子麦克风部分的源代码,这对于开发者来说是一个宝贵的资源。下面我们将深入探讨Android源码以及与电子麦克风相关...

    Android源码分享

    在Android开发领域,深入理解Android源码是提升技术能力的关键步骤。这份名为"Android源码分享"的资源包,显然为开发者提供了一个宝贵的探索平台。它不仅包含了Android系统的源代码,还提供了学习方法和课程体系流程...

    Binder实战大荟萃源码.rar

    总的来说,"Binder实战大荟萃源码"是深入学习Android IPC机制的理想资料,无论你是初学者还是经验丰富的开发者,都能从中受益。通过实际操练和理解源码,你将能够更好地设计和实现高效的Android服务和客户端,提升...

    android 我的笔记 源码

    Android 系统由五大部分组成:Linux 内核、HAL(硬件抽象层)、系统库、应用程序框架和应用程序。其中,Linux 内核提供底层硬件支持,HAL 封装了具体硬件设备的操作,系统库提供了多种服务和功能,应用程序框架为...

    Android深入浅出之Binder机制

    ### Android深入浅出之Binder机制 #### 一、概述 Android系统的Binder机制是实现进程间通信(IPC)的核心技术之一,对于理解Android底层框架和服务之间的交互至关重要。本文将基于邓凡平博客中关于Binder机制的...

    Android源码——快捷查询源码.zip

    本资源"Android源码——快捷查询源码.zip"包含的是一个帮助开发者快速查询Android源码的工具或指南,旨在提高开发效率,深入理解Android系统的运行机制。以下是基于这个主题的详细知识点: 1. **Android源码结构**...

    安卓Android源码——osChina.zip

    《安卓Android源码深度探索——osChina.zip剖析》 Android操作系统是全球最受欢迎的智能手机平台之一,它的开源特性吸引了无数开发者进行深入研究。本篇文章将基于"osChina.zip"这一压缩包,探讨Android的源码,...

Global site tag (gtag.js) - Google Analytics