Android跨進(jìn)程通信IPC之14——Binder之native層C++篇--ServiceManager的獲得

移步系列Android跨進(jìn)程通信IPC系列

1 源碼信息

framework/native/libs/binder/
  - ProcessState.cpp
  - BpBinder.cpp
  - Binder.cpp
  - IServiceManager.cpp
framework/native/include/binder/
  - IServiceManager.h
  - IInterface.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 流程圖

5713484-44dee73939fb85ed.png

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() 主要工作:
  1. 調(diào)用open,打/dev/binder驅(qū)動設(shè)備
  2. 調(diào)用mmap(),創(chuàng)建大小為 1016K的內(nèi)存地址空間
  3. 設(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

參考

Android跨進(jìn)程通信IPC之9——Binder之Framework層C++篇1

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,428評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,024評論 3 413
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,285評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,548評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 71,328評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,878評論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,971評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,098評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,616評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,554評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,725評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,243評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 43,971評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,361評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,613評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,339評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 47,695評論 2 370

推薦閱讀更多精彩內(nèi)容