我们就来看一下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 asInterface( \
const android::sp
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::asInterface( \
const android::sp
{ \
android::sp intr; \
if (obj != NULL) { \
intr = static_cast( \
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
{
return NULL;
}
queryLocalInterface函数默认返回NULL, 而BnInterface重写了queryLocalInterface函数, 定义如下:
template
inline sp
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
/**
* Retrieve an existing service, non-blocking.
*/
virtual sp
/**
* Register a service.
*/
virtual status_t addService( const String16& name,
const sp
bool allowIsolated = false) = 0;
/**
* Return list of all existing services.
*/
virtual Vector
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
{
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
[// gDefaultServiceManager = interface_cast
如果gDefaultServiceManager为null, 则调用ProcessState的getContextObject函数来得到Service Manager代理对象:
getContextObject函数的定义如下:
sp
{
return getStrongProxyForHandle(0);
[// return getStrongProxyForHandle(0)
这里调用getStrongProxyForHandle函数来查找具体的Binder代理对象,只不过传入了一个特殊参数0.
getStrongProxyForHandle函数定义如下:
sp
{
sp
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
]// 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
virtual status_t transact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
virtual status_t linkToDeath(const sp
void* cookie = NULL,
uint32_t flags = 0);
virtual status_t unlinkToDeath( const wp
void* cookie = NULL,
uint32_t flags = 0,
wp
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
};
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
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
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
inline sp
{
return INTERFACE::asInterface(obj);
[// return INTERFACE::asInterface(obj);
实际上就是调用asInterface函数,还记得asInterface函数么?asInterface是用IMPLEMENT_META_INTERFACE宏和DECLARE_META_INTERFACE宏实现的。详细信息见上面。
]// return INTERFACE::asInterface(obj);
}
]// gDefaultServiceManager = interface_cast
}
}
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
{
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
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
{
return flatten_binder(ProcessState::self(), val, this);
[// return flatten_binder(ProcessState::self(), val, this)
status_t flatten_binder(const sp
{
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
{
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
// 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
tr.data_size,
reinterpret_cast
tr.offsets_size/sizeof(size_t),
freeBuffer, this);
} else {
err = *static_cast
freeBuffer(NULL,
reinterpret_cast
tr.data_size,
reinterpret_cast
tr.offsets_size/sizeof(size_t), this);
}
} else {
freeBuffer(NULL,
reinterpret_cast
tr.data_size,
reinterpret_cast
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
[// sp
这里会调用ProcessState对象的成员函数getContextObject来获得一个句柄值等于NULL,即等于0的Binder代理对象,即一个BpBinder对象.
]// sp
return javaObjectForIBinder(env, b);
[// return javaObjectForIBinder(env, b)
这里会调用javaObjectForIBinder来将刚刚得到的BpBinder对象封装成一个Java服务代理对象.javaObjectForIBinder的函数实现如下:
jobject javaObjectForIBinder(JNIEnv* env, const sp
{
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
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, "
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
drl->incStrong((void*)javaObjectForIBinder);
env->SetLongField(object, gBinderProxyOffsets.mOrgue, reinterpret_cast
// 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
{
AutoMutex _l(mLock);
sp
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
{
AutoMutex _l(mLock);
return mBinder.promote();
}
private:
Mutex mLock;
wp
};
]// 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());
}
}
}