Android Framework:Binder(4)-Native Service的註冊
1、Native Service註冊的概述
Android中不少Service是Native Service,本篇咱們挑選Native service中的cameraserver的啓動註冊來學習Native Service註冊涉及的Binder機制。android
Native Service在啓動後須要經過Binder驅動向ServiceManager進行註冊,註冊過程便是一次跨進程的操做,Native Service是Client端,ServiceManager是Server端。cookie
1. Native Service註冊至ServiceManager示意圖:數據結構
1.Service啓動的時候會去獲取ServiceManager的代理實例,即BpServiceManager(BpBinder(0)),經過ServiceManager的代理實例向ServiceManager中註冊Service的name和Service實例:經過ioctl()將註冊信息寫入至binder驅動,由binder驅動通知ServiceManager進程;
2.另外一端ServiceManager在系統啓動開始初始化時主線程及進入死循環binder_loop,不斷的讀取binder驅動,查詢是否有Client端的請求消息。架構
2.Binder架構中的重要類
2.1. ServiceManager模塊中的Binder類框架:
Binder Native層涉及到的類比較多,關係也很複雜,關於ServiceManager模塊的類的結構基本以下:app
其中藍色的框的地方在Android N上的代碼中並未實現,Android M及以前的code上仍是能夠看到部分相關code,可是隻是定義未使用。
通常的Native Service端會繼承實現了經過BnInterface模板類構造出的IXXXService接口的BnXXXService,經過調用構造出的BBinder的transact方法來實現調用Service端的onTransact()方法來進行Service端的操做。
而ServiceManager進程能夠直接與Binder驅動通訊,不須要依賴這一套繼承體系。 這裏將ServiceManger當作一個普通的Server端,以便說明Android中通常狀況下的Binder通訊架構。
簡單說明下:
1.BpInterface和BnInterface其實就是爲了鏈接業務類和Binder類。不一樣的是BpInterface經過繼承BpRefBase來持有一個BpBinder對象,而BnInterface是經過繼承的方式來成爲一個BBinder對象。BpXXXService和BnXXXService繼承 ‘經過BpInterface和BnInterface模板類構造出的IXXXService接口,實現XXXService的業務函數。
2.BpServiceManager,在Client端獲取service或者Service在註冊時,須要經過ServiceManager的對象去查詢,獲取或添加service,而Client端獲取到的不是ServiceManager的對象而是ServiceManager的對象的代理對象,及BpServiceManager(BpBinder(0))。
3.BpBinder和BBinder繼承自IBinder接口,實現與Binder驅動交互的接口。框架
2.2. Binder通訊類ProcessState,IPCThreadState
同一個進程裏只有一個ProcessState,ProcessState負責打開Binder驅動,創建IPC線程池,設置進程基本信息。
IPCthreadState負責着Binder的讀取,寫入和請求處理框架。異步
2、CameraService的啓動初始化
android系統在啓動時會去解析各類rc文件,而後作各類操做,好比啓動主要的service,咱們要分析的cameraserver的rc文件以下:函數
frameworks\av\camera\cameraserver\cameraserver.rc
service cameraserver /system/bin/cameraserver
class main
user cameraserver
group audio camera input drmrpc
ioprio rt 4
writepid /dev/cpuset/camera-daemon/tasks /dev/stune/top-app/tasksoop
咱們知道啓動cameraserver時會走入口函數main:學習
frameworks\av\camera\cameraserver\main_cameraserver.cpp
int main(int argc __unused, char** argv __unused)
{
sp<ProcessState> proc(ProcessState::self());//得到一個ProcessState實例
sp<IServiceManager> sm = defaultServiceManager();//須要獲得ServiceManager實例以註冊該服務
CameraService::instantiate();//Cameraserver實例化
//線程池管理
ProcessState::self()->startThreadPool();
IPCThreadState::self()->joinThreadPool();
}
cameraserver的main函數中主要的初始化流程以下圖:
下面咱們來詳細的看下cameraserver啓動時走的流程。
1. 打開Binder驅動中映射一塊內存保存進程基本信息
每一個進程只有一個ProcessState,以下是ProcessState的單例獲取方式:
/frameworks/native/libs/binder/ProcessState.cpp
sp<ProcessState> ProcessState::self()
{
Mutex::Autolock _l(gProcessMutex);
if (gProcess != NULL) {
return gProcess;
}
gProcess = new ProcessState;
return gProcess;
}
若是沒有gProcess實例則在ProcessState的構造函數中進行構造:
ProcessState::ProcessState()
: mDriverFD(open_driver()) //注意在新建ProcessState時打開了Binder驅動
, mVMStart(MAP_FAILED)//映射內存的起始地址
, mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
, mThreadCountDecrement(PTHREAD_COND_INITIALIZER)
, mExecutingThreadsCount(0)
//通常進程的最大binder線程數是15,system_server的最大binder線程數是32
, 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.
//在binder驅動中進行內存映射,
mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
...
}
}
這個構造函數裏面調用open_driver()打開了/dev/binder設備驅動文件,返回文件描述符。這樣咱們就能經過這個mDriverFd來和binder驅動交互了。
open_driver(),獲取文件描述符並設置最大binder線程數量:
/frameworks/native/libs/binder/ProcessState.cpp
static int open_driver()
{ //打開binder驅動得到文件描述符,這裏及調到上篇文章中說的binder_open的驅動函數了
int fd = open("/dev/binder", O_RDWR | O_CLOEXEC);
if (fd >= 0) {
size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
...
}
...
return fd;
}
小結:
這一步主要就是打開Binder驅動,爲該Service的進程在binder驅動中映射一段內存,設置了基本的進程信息;
2. defaultServiceManager獲取serviceManager的代理對象
cameraserver初始化須要將本身加到serviceManager的管理list中,所以須要先獲取到serviceManager的實例:
sp<IServiceManager> sm = defaultServiceManager();
1
defaultServiceManager的實現:
frameworks/native/libs/binder/IServiceManager.cpp
sp<IServiceManager> defaultServiceManager()
{
if (gDefaultServiceManager != NULL) return gDefaultServiceManager;
{
AutoMutex _l(gDefaultServiceManagerLock);
while (gDefaultServiceManager == NULL) {
//獲取ServiceManager的代理對象
gDefaultServiceManager = interface_cast<IServiceManager>(
ProcessState::self()->getContextObject(NULL));
}
}
return gDefaultServiceManager;
}
可看到獲取servicemanager實例也是經過單例方式得到,第一次獲取時是經過下面的方法:
gDefaultServiceManager = interface_cast<IServiceManager>(
ProcessState::self()->getContextObject(NULL));
這裏能夠看到是兩部分,
2.1.咱們先看ProcessState::self()->getContextObject(NULL)作了什麼獲得什麼:
/frameworks/native/libs/binder/ProcessState.cpp
sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
{
return getStrongProxyForHandle(0);
}
傳下去的參數handle是0,最終返回了一個BpBinder(0)的對象:
sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
{
sp<IBinder> result;
AutoMutex _l(mLock);
//根據hanle值查找對應的handle實體,若未發現對應實體則會建立一個新的項返回
handle_entry* e = lookupHandleLocked(handle);
if (e != NULL) {
IBinder* b = e->binder;
if (b == NULL || !e->refs->attemptIncWeak(this)) {
...
b = new BpBinder(handle);//這裏返回handle爲0的BpBinder對象
e->binder = b;
if (b) e->refs = b->getWeakRefs();
result = b;
}
}
return result;
}
=================
BpBinder和BBinder的關係:(摘自《深刻理解Android卷1-鄧凡平》)
BpBinder和BBinder都是從IBinder類中派生而來,如圖:
BpBinder是客戶端用來與Server交互的代理類,p指proxy的意思;
BBinder則是與proxy相對的一端,是proxy交互的目的端,及表明服務端。這裏的BpBinder和BBinder經過handle值是一一對應的.
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);
}
================
2.2 模板類的替換
接着看獲取ServiceManager實例方法,即這裏能夠這麼替換:
gDefaultServiceManager = interface_cast<IServiceManager>(
new BpBinder(0));
這裏interface_cast是一個模板函數,定義以下:
/frameworks/native/include/binder/IInterface.h
template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
return INTERFACE::asInterface(obj);
}
所以這裏至關於
inline sp<IServiceManager> interface_cast(const sp<IBinder>& obj)
{
return IServiceManager::asInterface(obj);
}
因此咱們接着看IServiceManager接口類:
frameworks/native/include/binder/IServiceManager.h
class IServiceManager : public IInterface
{
public:
DECLARE_META_INTERFACE(ServiceManager);//關鍵的宏
//下面是ServiceManager所提供的業務函數。
//getService是阻塞的,若是不存在的話會阻塞幾秒
virtual sp<IBinder> getService( const String16& name) const = 0;
virtual sp<IBinder> checkService( const String16& name) const = 0;//非阻塞的
virtual status_t addService( const String16& name,const sp<IBinder>& service,bool allowIsolated = false) = 0;
virtual Vector<String16> listServices() = 0;
enum {
GET_SERVICE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
CHECK_SERVICE_TRANSACTION,
ADD_SERVICE_TRANSACTION,
LIST_SERVICES_TRANSACTION,
};
};
sp<IServiceManager> defaultServiceManager();
template<typename INTERFACE>
status_t getService(const String16& name, sp<INTERFACE>* outService)
{
const sp<IServiceManager> sm = defaultServiceManager();
if (sm != NULL) {
*outService = interface_cast<INTERFACE>(sm->getService(name));
if ((*outService) != NULL) return NO_ERROR;
}
return NAME_NOT_FOUND;
}
bool checkCallingPermission(const String16& permission);
bool checkCallingPermission(const String16& permission,
int32_t* outPid, int32_t* outUid);
bool checkPermission(const String16& permission, pid_t pid, uid_t uid);
}; // namespace android
#endif // ANDROID_ISERVICE_MANAGER_H
上面關鍵的宏的定義和實現:
frameworks/native/include/binder/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();
//宏實現
#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() { } \
所以:
gDefaultServiceManager = interface_cast<IServiceManager>(new BpBinder(0));
及能夠等價爲:
gDefaultServiceManager = IServiceManager::asInterface(BpBinder(0))
咱們重點看IServiceManager::asInterface(obj);的實現方法,對應函數模板能夠同效展開爲:
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);//obj及以前建立的BpBinder(0)
}
}
return intr;
}
到這裏咱們能夠看出gDefaultServiceManager被賦值的是一個BpServiceMananger對象,即defaultServiceManager()獲得一個BpServiceManager(BpBinder(0))的對象;
BpServiceManager分析:
咱們看到BpServiceManager繼承自BpInterface的類模,由下面分析BpServiceManager是繼承了IServiceManager和BpRefBase接口的,所以BpServiceManager中實現了IServiceManager中的接口函數:
/frameworks/native/libs/binder/IServiceManager.cpp::class BpServiceManager
class BpServiceManager : public BpInterface<IServiceManager>
{
BpServiceManager(const sp<IBinder>& impl):BpInterface<IServiceManager>(impl){}//調用父類的構造函數,傳入impl即BpBinder(0)
virtual sp<IBinder> BpServiceManager(const String16& name) {sp<IBinder> svc = checkService(name);return svc;}
virtual sp<IBinder> checkService( const String16& name) {remote()->transact(CHECK_SERVICE_TRANSACTION, data, &reply)}
virtual status_t addService(const String16& name,,){remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);}
virtual Vector<String16> listServices() {remote()->transact(LIST_SERVICES_TRANSACTION, data, &reply);}
}
父類BpInterface中能夠看到BpInterface繼承類public INTERFACE, public BpRefBase,替換掉INTERFACE即BpServiceManager繼承了兩個父類:IServiceManager和BpRefBase:
/frameworks/native/include/binder/IInterface.h :: BpInterface
class BpInterface : public INTERFACE, public BpRefBase
{
public:BpInterface(const sp<IBinder>& remote);
protected:virtual IBinder* onAsBinder();
};
inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)
: BpRefBase(remote) //基類的構造函數
{
}
BpInterface的實現代碼以下:
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.
}
}
在這裏看到BpBinder(0)傳遞給了BpServiceManager的祖先類對象BpRefBase對象的mRemote變量中。
BpBinderServiceManager小結:
咱們經過defaultServiceManager()方法獲得獲得了BpServiceManager(BpBinder(0))對象,BpServiceManager對象實現了IServiceManager的業務函數,是ServiceManager的代理,經過這個對象咱們就能夠調用ServiceManager所暴露出來的各個方法,經過BpServiceManager這個代理來轉達給ServiceManager。
首先,咱們經過ProcessState::self()->getContextObject(NULL)獲得了BpBinder(0)對象。
而後,咱們用interface_cast(BpBinder(0))這個模版,將BpBinder(0)轉換爲IServiceManager類型的BpServiceManager對象。
至此,咱們獲得了ServiceManager的代理對象。
3.Cameraserver註冊至ServiceManager:
CameraService未實現父類BinderService的方法instantiate();因此會調用父類的方法:
/frameworks/native/include/binder/BinderService.h
static void instantiate() { publish(); }
public:
static status_t publish(bool allowIsolated = false) {
sp<IServiceManager> sm(defaultServiceManager());
return sm->addService(
String16(SERVICE::getServiceName()),//將service的名字傳給SM
new SERVICE(), allowIsolated);//將service的實例傳給SM
}
//getServiceName()在子類中實現,返回"media.camera"
/frameworks/av/services/camera/libcameraservice/CameraService.h
static char const* getServiceName() { return "media.camera"; }
咱們看到,NativeService在初始化的過程就是把本身註冊爲獨立Service name的Service的過程,同時把Service對象傳遞給ServiceManager。
在publish中咱們又看到defaultServiceManager()獲取到sm,由上面小節的分析咱們知道sm是ServiceManager的代理對象,事實上是一個BpServiceManager(BpBinder(0)),執行sm->addService()會調到BpServiceManager類中的addService方法。
frameworks/native/libs/binder/IServiceManager.cpp::BpServiceManager
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);
//transact函數在IPCThreadState.h中默認值是0表明oneway,異步無需等待結果繼續執行
status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);//操做指令是add service,service名字在data裏
return err == NO_ERROR ? reply.readExceptionCode() : err;
}
這裏的remote()返回的是mRemote,是BpBinder對象;由上面BpServiceManager的介紹中知道BpServiceManager的構造函數中BpBinder(0)這個對象最終是賦給了BpServiceManager的父類BpRefBase的mRemote成員變量,而此時咱們經過remote()函數獲得的對象應該就是BpBinder(0)這個對象。所以,remote()->transact()便是BpBinder(0)->transact()。
下面看BpBinder的transact方法,發現transact方法的具體實現是在IPCThreadState中:
/frameworks/native/libs/binder/BpBinder.cpp
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);//這裏的handle是0,code是ADD_SERVICE_TRANSACTION,data中是service名字等信息
if (status == DEAD_OBJECT) mAlive = 0;
return status;
}
return DEAD_OBJECT;
}
咱們看到BpBinder裏調用了IPCThreadState的transact方法:
/frameworks/native/libs/binder/IPCThreadState.cpp
status_t IPCThreadState::transact(int32_t handle,uint32_t code, const Parcel& data,Parcel* reply, uint32_t flags)
{
if (err == NO_ERROR) {
err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);
}
if ((flags & TF_ONE_WAY) == 0) {
if (reply) {
err = waitForResponse(reply);
} else {
Parcel fakeReply;
err = waitForResponse(&fakeReply);
}
...
} else {
err = waitForResponse(NULL, NULL);
}
return err;
}
首先數據封裝,writeTransactionData()將數據封裝至mOut中,每一個線程都有一個IPCThreadState.cpp,每一個IPCThreadState中有一個mIn,一個mOut,其中mIn是用來接收來自Binder設備的數據,mOut則是用來存儲發往Binder設備的數據
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;//向binder驅動中傳輸數據的數據結構
tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
tr.target.handle = handle;
tr.code = code;
tr.flags = binderFlags;
...
mOut.writeInt32(cmd);
mOut.write(&tr, sizeof(tr));//將tr中保存的數據寫到mOut中
return NO_ERROR;
}
經過waitForResponse()傳輸數據:
status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
{
uint32_t cmd;
int32_t err;
while (1) {
if ((err=talkWithDriver()) < NO_ERROR) break;//向binder驅動交換數據操做
cmd = (uint32_t)mIn.readInt32();//從mIn中獲取binder驅動傳過來的命令
switch (cmd) {
case BR_TRANSACTION_COMPLETE: break;//binder驅動返回對端transact成功
case BR_DEAD_REPLY:err = DEAD_OBJECT;goto finish;//
case BR_FAILED_REPLY: err = FAILED_TRANSACTION;goto finish;
case BR_ACQUIRE_RESULT://暫時未實現
//binder驅動給Client進程傳遞Server進程的回覆
case BR_REPLY:{...}goto finish;
default:
err = executeCommand(cmd);
if (err != NO_ERROR) goto finish;
break;
}
}
finish:
...
return err;
}
在talkWithDriver()函數中經過ioctl方式來和binder驅動進行數據交換操做:把mOut中的內容發送給binder驅動,同時從mIn讀取binder驅動傳來的數據
status_t IPCThreadState::talkWithDriver(bool doReceive)
{
binder_write_read bwr;//用來與binder設備交換數據的結構
...
bwr.write_buffer = (uintptr_t)mOut.data();//mOut中的數據放置bwr的write_buffer中
if (doReceive && needRead) {//從mIn中讀取binder驅動傳來的數據
bwr.read_size = mIn.dataCapacity();
bwr.read_buffer = (uintptr_t)mIn.data();
} else {
bwr.read_size = 0;
bwr.read_buffer = 0;
}
...
status_t err;
#if defined(__ANDROID__)
//經過ioctrl向binder驅動中mProcess->mDriverFD幾點進行BINDER_WRITE_READ操做,數據在&bwr中
if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0) err = NO_ERROR;
...
} while (err == -EINTR);
...
return err;
}
在service_manager進程中,service_manager正在不斷的向binder驅動中查詢是否有向本身發的請求,通過上一步的ioctl()後,service_manager進程會不斷循環檢測是否有請求需執行,隨後執行service_manager的do_add_service方法將該camaraservice信息加到service_manager的service管理鏈表中。
這樣就完成了service向ServiceManager的註冊過程,具體能夠看上篇文章有關ServiceManager的流程-Android Framework:Binder(2)-Service Manager
至此完成addService的操做。
小結:
經過上面的過程即經過ServiceManager的代理BpServiceManager(BpBinder(0))將CameraService的servicename和實例註冊到了ServiceManager中了;
4.Service線程池管理,處理請求
做爲一個Service,向ServiceManager註冊完本身以後,Service就須要有檢測本身被調用的機制了,這裏的檢測機制就是CameraService搭建的線程池檢測機制:
ProcessState::self()->startThreadPool();//新啓動一個線程來和Binder驅動進行交互
IPCThreadState::self()->joinThreadPool();//主線程也與Binder設備進行交互
startThreadPool()中新啓動一個線程:
frameworks\native\libs\binder\ProcessState.cpp
void ProcessState::startThreadPool()
{
AutoMutex _l(mLock);
if (!mThreadPoolStarted) {
mThreadPoolStarted = true;
spawnPooledThread(true);
}
}
這裏的isMain是true:
void ProcessState::spawnPooledThread(bool isMain)
{
if (mThreadPoolStarted) {
String8 name = makeBinderThreadName();
sp<Thread> t = new PoolThread(isMain);
t->run(name.string());
}
}
跑起來一個PoolThread類型的線程:
frameworks\native\libs\binder\ProcessState.cpp
class PoolThread : public Thread
{
public:
PoolThread(bool isMain)
: mIsMain(isMain)
{
}
protected:
virtual bool threadLoop()
{
IPCThreadState::self()->joinThreadPool(mIsMain)//這裏
return false;
}
const bool mIsMain;
}
...
}
startThreadPool()中spawnPooledThread()出的新線程一樣執行了joinThreadPool()函數,區別是子線程中參數是true,而主線程中設置的參數爲默認參數false :
void IPCThreadState::joinThreadPool(bool isMain)
{
//若是isMain是true則進入循環,不然註冊準備進入循環
mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
set_sched_policy(mMyThreadId, SP_FOREGROUND);
status_t result;
do {
processPendingDerefs();
result = getAndExecuteCommand();//在循環中獲取是否有須要執行的指令
...
} while (result != -ECONNREFUSED && result != -EBADF);
mOut.writeInt32(BC_EXIT_LOOPER); //向mOut中寫上退出循環標誌,BC_XXX是進程發送給binder驅動的命令
talkWithDriver(false);//
}
在IPCThreadState的joinThreadPool函數中的do-while死循環中先talkwithdriver()從binder驅動中讀取Client端請求的數據:
status_t IPCThreadState::getAndExecuteCommand()
{
status_t result;
int32_t cmd;
result = talkWithDriver();
if (result >= NO_ERROR) {
...
cmd = mIn.readInt32();
//處理收到的消息
result = executeCommand(cmd);
...
}
return result;
}
循環中獲得請求後,mIn中有binder驅動有回覆的Client端的請求數據,則執行executeCommand()函數,將Client端請求從新打包成Parcel數據發送給Service的BBinder對象即Service端代理去執行相應的請求:
status_t IPCThreadState::executeCommand(int32_t cmd)
{
BBinder* obj;
RefBase::weakref_type* refs;
status_t result = NO_ERROR;
switch ((uint32_t)cmd) {
case BR_ERROR:result = mIn.readInt32();break;
case BR_OK: break;
case BR_ACQUIRE:mOut.writeInt32(BC_ACQUIRE_DONE); break;
case BR_RELEASE:break;
case BR_INCREFS: break;
case BR_DECREFS: break;
case BR_ATTEMPT_ACQUIRE:break;
case BR_TRANSACTION:
{
binder_transaction_data tr;
result = mIn.read(&tr, sizeof(tr));//從mIn中讀取數據放至tr中
...
Parcel reply;
status_t error;
if (tr.target.ptr) {
//獲取目標對象的強引用
if (reinterpret_cast<RefBase::weakref_type*>( tr.target.ptr)->attemptIncStrong(this)) {
//BBinder的transact()函數,即執行Server端的transact函數
error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,&reply, tr.flags);
reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);
}
}
...
}
break;
case BR_DEAD_BINDER:break;
case BR_CLEAR_DEATH_NOTIFICATION_DONE: break;
case BR_FINISHED:result = TIMED_OUT;break;
case BR_NOOP: break;
//binder驅動回覆的消息用來建立一個新線程用來和Binder通訊
case BR_SPAWN_LOOPER:mProcess->spawnPooledThread(false); break;
...
}
}
對於CameraService將會調用Service的BBinder中onTransact()接口的實現函數:
frameworks\av\services\camera\libcameraservice\CameraService.cpp::onTransact
status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
uint32_t flags) {
const int pid = getCallingPid();
const int selfPid = getpid();
// Permission checks
switch (code) {
case BnCameraService::NOTIFYSYSTEMEVENT: {
if (pid != selfPid) {
// Ensure we're being called by system_server, or similar process with
// permissions to notify the camera service about system events
if (!checkCallingPermission(
String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
const int uid = getCallingUid();
ALOGE("Permission Denial: cannot send updates to camera service about system"
" events from pid=%d, uid=%d", pid, uid);
return PERMISSION_DENIED;
}
}
break;
}
}
return BnCameraService::onTransact(code, data, reply, flags);
}
至此調用到Service端的實現請求的地方,。
總結一下:
3、Native Service註冊總結: Service在啓動時須要向ServiceManager註冊本身的信息,從而可以使client端經過ServiceManager查詢和獲取該service的實例和調用方法。 Native Service中camera server初始化時主要通過如下幾個步驟: 1. 獲取本進程的ProcessState實例,並確保ProcessState的初始化中打開binder驅動一次,將進程的基本信息寫入至Binder驅動中。 2. 獲取ServiceManager的代理對象:BpServiceManager(BpBinder(0)),經過該代理對象調用ServiceManager的addService方法將Service的name及實例經過ioctl()方法傳至Binder驅動。 3. ServiceManager端在開機啓動後便一直在讀取Binder驅動中是否有本身的Client端的請求,此時有addService的請求,所以ServiceManager會將Binder驅動中的Service請求數據從新解析而後註冊至自身的svclist的鏈表中; 4. CameraServer註冊完以後會搭建自身的監聽請求的機制:會起個IPC的線程池,不斷的talkWithDriver向binder驅動中查詢是否有Client端的請求,若是有打包請求數據,執行IPC線程中的executeCommand()的函數獲取Server端的BBinder對象執行transact函數,從而執行Service的方法。