1 源碼信息
framework/native/libs/binder/
- ProcessState.cpp
- BpBinder.cpp
- Binder.cpp
- IServiceManager.cpp
framework/native/include/binder/
- IServiceManager.h
- IInterface.h
- ProcessState.cpp
- BpBinder.cpp
- Binder.cpp
- IServiceManager.cpp
- IServiceManager.h
-
IInterface.h
這里重點提醒下framework/native/libs/binder/IServiceManager.cpp和 framework/native/include/binder/IServiceManager.h大家千萬不要弄混了。
2 獲取Service Manager簡述
- 獲取Service Manager是通過defaultServiceManager()方法來完成的。當(dāng)進(jìn)程 注冊服務(wù) 與 獲取服務(wù)之前,都需要調(diào)用defaultServiceManager()方法來獲取gDefaultServiceManager對象。
- 對于gDefaultServiceManager對象,如果存在直接返回。如果不存在直接創(chuàng)建該對象,創(chuàng)建過程包括調(diào)用open()打開binder驅(qū)動設(shè)備,利用mmap()映射內(nèi)核的地址空間。
3 流程圖
4 獲取defaultServiceManager
//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>(
//這里才是關(guān)鍵和重點
ProcessState::self()->getContextObject(NULL));
if (gDefaultServiceManager == NULL)
sleep(1);
}
}
return gDefaultServiceManager;
}
- 獲取ServiceManager 對象采用單例模式,當(dāng)gDefaultServiceManager存在,則直接返回,否則創(chuàng)建一個新對象。
- 這里的創(chuàng)建單利模式和咱們之前的java里面的單例不一樣。它里面多了一層while循環(huán),這是谷歌在2013年1月Todd Poynor提交的修改。因為當(dāng)?shù)谝淮螄L試創(chuàng)建獲取ServiceManager時,ServiceManager可能還未準(zhǔn)備就緒,所以通過sleep1秒,實現(xiàn)延遲1秒,然后嘗試去獲取直到成功。
gDefualtServiceManager的創(chuàng)建過程又可以分解為3個步驟
- ProcessState::self() :用于獲取ProcessState對象(也是單例模式),每個進(jìn)程有且只有一個ProcessState對象,存在則直接返回,不存在則創(chuàng)建。
- getContextObject(): 用于獲取BpBinder對象,對于hanle=0的BpBinder對象,存在則直接返回,不存在則創(chuàng)建。
- interface_cast<IServiceManager>():用于獲取BpServiceManager對象。
5 獲取ProcessState對象
5.1 ProcessState::self
//frameworks/native/libs/binder/ProcessState.cpp 70行
// 這又是一個進(jìn)程單體
sp<ProcessState> ProcessState::self()
{
Mutex::Autolock _l(gProcessMutex);
if (gProcess != NULL) {
return gProcess;
}
//實例化 ProcessState,首次創(chuàng)建
gProcess = new ProcessState;
return gProcess;
}
獲取ProcessState對象:這也是一個單利模式,從而保證每一個進(jìn)程只有一個ProcessState對象,其中g(shù)Proccess和gProccessMutex是保持在Static.cpp的類全局變量。
5.2 ProccessState的構(gòu)造函數(shù)
//frameworks/native/libs/binder/ProcessState.cpp 339行
ProcessState::ProcessState()
//這里打開了打開了Binder驅(qū)動,也就是/dev/binder文件,返回文件描述符
: mDriverFD(open_driver())
, 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) {
//采用內(nèi)存映射函數(shù)mmap,給binder分配一塊虛擬地址空間,涌來了接收事物
mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
if (mVMStart == MAP_FAILED) {
//沒有足夠空間分配給/dev/binder,則關(guān)閉驅(qū)動。
close(mDriverFD);
mDriverFD = -1;
}
}
}
通過上面的構(gòu)造函數(shù)我們知道
- ProcessState的單利模式的唯一性,因此一個進(jìn)程只打開binder設(shè)備一次,其中ProcessState的成員變量mDriverFD記錄binder驅(qū)動的fd,用于訪問binder設(shè)備。
- BINDER_VM_SIZE=(110241024- (40962)),所以binder分配的默認(rèn)內(nèi)存大小是10241016也就是1M-8K(1M減去8k)
- DEFAULT_MAX_BINDER_THREAD=15,binder默認(rèn)的最大可并發(fā)的線程數(shù)為16。
5.3 open_driver()方法
//frameworks/native/libs/binder/ProcessState.cpp 311行
static int open_driver()
{
// 打開/dev/binder設(shè)備,建立與內(nèi)核的Binder驅(qū)動的交互通道
int fd = open("/dev/binder", O_RDWR);
if (fd >= 0) {
fcntl(fd, F_SETFD, FD_CLOEXEC);
int vers = 0;
status_t result = ioctl(fd, BINDER_VERSION, &vers);
if (result == -1) {
close(fd);
fd = -1;
}
if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
close(fd);
fd = -1;
}
size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
// 通過ioctl設(shè)置binder驅(qū)動,能支持的最大線程數(shù)
result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
if (result == -1) {
ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
}
} else {
ALOGW("Opening '/dev/binder' failed: %s\n", strerror(errno));
}
return fd;
}
open_driver的作用就是打開/dev/binder設(shè)備,設(shè)定binder支持的最大線程數(shù)。
6 獲取BpBiner對象
6.1 getContextObject()方法
//frameworks/native/libs/binder/ProcessState.cpp 85行
sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
{
return getStrongProxyForHandle(0);
}
我們發(fā)現(xiàn)這里面什么都沒做,就是調(diào)用getStrongProxyForHandle()方法,大家注意它的入?yún)懰罏?,然后我們繼續(xù)深入
6.2 getStrongProxyForHandle()方法
//frameworks/native/libs/binder/ProcessState.cpp 179行
sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
{
sp<IBinder> result;
AutoMutex _l(mLock);
//查找handle對應(yīng)的資源項
handle_entry* e = lookupHandleLocked(handle);
if (e != NULL) {
IBinder* b = e->binder;
if (b == NULL || !e->refs->attemptIncWeak(this)) {
if (handle == 0) {
Parcel data;
//通過ping操作測試binder是否已經(jīng)準(zhǔn)備就緒
status_t status = IPCThreadState::self()->transact(
0, IBinder::PING_TRANSACTION, data, NULL, 0);
if (status == DEAD_OBJECT)
return NULL;
}
//當(dāng)handle值所對應(yīng)的IBinder不存在或弱引用無效時,則創(chuàng)建BpBinder對象
b = new BpBinder(handle);
e->binder = b;
if (b) e->refs = b->getWeakRefs();
result = b;
} else {
result.force_set(b);
e->refs->decWeak(this);
}
}
return result;
}
當(dāng)handle值所對應(yīng)的IBinder不存在或弱引用無效時會創(chuàng)建BpBinder,否則直接獲取。針對hande==0的特殊情況,通過PING_TRANSACTION來判斷是否準(zhǔn)備就緒。如果在context manager還未生效前,一個BpBinder的本地引用就已經(jīng)被創(chuàng)建,那么驅(qū)動將無法提供context manager的引用。
在getStrongProxyForHandle()方法里面先后調(diào)用了lookupHandleLocked()方法和創(chuàng)建BpBinder對象
6.3 lookupHandleLocked()方法
//frameworks/native/libs/binder/ProcessState.cpp 166行
ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
{
const size_t N=mHandleToObject.size();
//當(dāng)handle大于mHandleToObject的長度時,進(jìn)入該分支
if (N <= (size_t)handle) {
handle_entry e;
e.binder = NULL;
e.refs = NULL;
//從mHandleToObject的第N個位置開始,插入(handle+1-N)個e到隊列中
status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
if (err < NO_ERROR) return NULL;
}
return &mHandleToObject.editItemAt(handle);
}
- 根據(jù)handle值來查找對應(yīng)的handle_entry,handle_entry是一個結(jié)構(gòu)體,里面記錄了IBinder和weakref_type兩個指針。
- 當(dāng)handle大于mHandleToObject的Vector長度時,則向Vector中添加(handle+1-N)個handle_entry結(jié)構(gòu)體,然后再返回handle向?qū)?yīng)位置的handle_entry結(jié)構(gòu)體指針。
6.4 創(chuàng)建BpBinder
//frameworks/native/libs/binder/BpBinder.cpp 89行
BpBinder::BpBinder(int32_t handle)
: mHandle(handle)
, mAlive(1)
, mObitsSent(0)
, mObituaries(NULL)
{
//延長對象的生命時間
extendObjectLifetime(OBJECT_LIFETIME_WEAK);
// handle所對應(yīng)的bindle弱引用+1
IPCThreadState::self()->incWeakHandle(handle);
}
創(chuàng)建BpBinder對象中將handle相對應(yīng)的弱引用+1
7 獲取BpServiceManager對象
7.1 interface_cast()函數(shù)
//frameworks/native/include/binder/IInterface.h 42行
template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
return INTERFACE::asInterface(obj);
}
這是一個模板函數(shù),可得出,interface_cast<IServiceManager>()等價于IServiceManager::asInterface()。接下來,再說說asInterface()函數(shù)的具體功能。
7.2 IServiceManager::asInterface()函數(shù)
對于asInterface()函數(shù),通過搜索代碼,你會發(fā)現(xiàn)根本找不到這個方法是在哪里定義這個函數(shù)的,其實是通過模板函數(shù)來定義的,通過下面兩個代碼完成的
// 位于IServiceManager.h 33行
DECLARE_META_INTERFACE(ServiceManager)
//位于IServiceManager.cpp 108行
IMPLEMENT_META_INTERFACE(ServiceManager,"android.os.IServiceManager")
那我們就來重點說下這兩塊代碼的功能
7.3 DECLARE_META_INTERFACE
//framework/native/include/binder/IInterface.h 74行
#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();
位于IServiceManager.h文件中,INTERFACE=ServiceManager展開即可得:
static const android::String16 descriptor;
static android::sp< IServiceManager > asInterface(const android::sp<android::IBinder>& obj)
virtual const android::String16& getInterfaceDescriptor() const;
IServiceManager ();
virtual ~IServiceManager();
該過程主要是聲明asInterface()、getInterfaceDescriptor()方法。
7.4 IMPLEMENT_META_INTERFACE
//framework/native/include/binder/IInterface.h 83行
#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() { }
位于IServiceManager.cpp文件中,INTERFACE=ServiceManager,NAME="android.os.IServiceManager" 開展即可得:
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>& obj)
{
android::sp<IServiceManager> intr;
if(obj != NULL) {
intr = static_cast<IServiceManager *>(
obj->queryLocalInterface(IServiceManager::descriptor).get());
if (intr == NULL) {
intr = new BpServiceManager(obj); //【見小節(jié)4.5】
}
}
return intr;
}
IServiceManager::IServiceManager () { }
IServiceManager::~ IServiceManager() { }
不難發(fā)現(xiàn),上面說的IServiceManager::asInterface() 等價于new BpServiceManager()。在這里,更確切地說應(yīng)該是new BpServiceManager(BpBinder)。
7.4.1 BpServiceManager實例化
//frameworks/native/libs/binder/IServiceManager.cpp 126行
class BpServiceManager : public BpInterface<IServiceManager>
{
public:
BpServiceManager(const sp<IBinder>& impl)
: BpInterface<IServiceManager>(impl)
{
}
virtual sp<IBinder> getService(const String16& name) const
{
unsigned n;
for (n = 0; n < 5; n++){
sp<IBinder> svc = checkService(name);
if (svc != NULL) return svc;
ALOGI("Waiting for service %s...\n", String8(name).string());
sleep(1);
}
return NULL;
}
virtual sp<IBinder> checkService( const String16& name) const
{
Parcel data, reply;
data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
data.writeString16(name);
remote()->transact(CHECK_SERVICE_TRANSACTION, data, &reply);
return reply.readStrongBinder();
}
virtual status_t addService(const String16& name, const sp<IBinder>& service,
bool allowIsolated)
{
Parcel data, reply;
data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
data.writeString16(name);
data.writeStrongBinder(service);
data.writeInt32(allowIsolated ? 1 : 0);
status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);
return err == NO_ERROR ? reply.readExceptionCode() : err;
}
virtual Vector<String16> listServices()
{
Vector<String16> res;
int n = 0;
for (;;) {
Parcel data, reply;
data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
data.writeInt32(n++);
status_t err = remote()->transact(LIST_SERVICES_TRANSACTION, data, &reply);
if (err != NO_ERROR)
break;
res.add(reply.readString16());
}
return res;
}
};
創(chuàng)建BpServiceManager對象的過程,會先初始化父類對象:
7.4.2 BpServiceManager實例化
//frameworks/native/include/binder/IInterface.h 135行
template<typename INTERFACE>
class BpInterface : public INTERFACE, public BpRefBase
{
public: BpInterface(const sp<IBinder>& remote);
protected: virtual IBinder* onAsBinder();
};
7.4.3 BpRefBase初始化
BpRefBase::BpRefBase(const sp<IBinder>& o)
: mRemote(o.get()), mRefs(NULL), mState(0)
{
extendObjectLifetime(OBJECT_LIFETIME_WEAK);
if (mRemote) {
mRemote->incStrong(this);
mRefs = mRemote->createWeak(this);
}
}
new BpServiceManager(),在初始化過程中,比較重要的類BpRefBase的mRemote指向new BpBinder(0),從而BpServiceManager能夠利用Binder進(jìn)行通信。
8 模板函數(shù)
C層的Binder架構(gòu),通過下面的兩個宏,非常方便地創(chuàng)建了new Bp##INTERFACE(obj)
代碼如下:
// 用于申明asInterface(),getInterfaceDescriptor()
#define DECLARE_META_INTERFACE(INTERFACE)
// 用于實現(xiàn)上述兩個方法
#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)
例如:
// 實現(xiàn)BpServiceManager對象
IMPLEMENT_META_INTERFACE(ServiceManager,"android.os.IServiceManager")
等價于:
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>& 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;
}
IServiceManager::IServiceManager () { }
IServiceManager::~ IServiceManager() { }
9 總結(jié)
- defaultServiceManager 等價于new BpServiceManager(new BpBinder(0));
- ProcessState:: self() 主要工作:
- 調(diào)用open,打/dev/binder驅(qū)動設(shè)備
- 調(diào)用mmap(),創(chuàng)建大小為 1016K的內(nèi)存地址空間
- 設(shè)定當(dāng)前進(jìn)程最大的并發(fā)Binder線程個數(shù)為16
- BpServiceManager巧妙將通信層與業(yè)務(wù)層邏輯合為一體,通過繼承接口IServiceManager實現(xiàn)接口中的業(yè)務(wù)邏輯函數(shù);通過成員變量mRemote=new BpBinder(0) 進(jìn)行Binder通信工作。BpBinder通過handle來指向所對應(yīng)的BBinder,在整個Binder系統(tǒng)總handle=0代表ServiceManager所對應(yīng)的BBinder。