Jimmy Chen

A Programmer

(原创)BpBinder、BBinder和IInterface的关系

  本来想一篇文章就把BpBinder、BBinder、IBinder和IInterface的关系弄清楚的,但是感觉脱离Binder实际的使用流程来看这几个类,总觉得抓不到重点,所以感觉也还是和前面的文章一样,只是直接看里面的几个重要的函数调用,先不管实际Binder实际调用流程是怎么样的

IBinder

  BpBinder和BBinder都是Android中与Binder通信相关的代表,他们都是从IBinder中继承而来的。其中BpBinder是客户端用来与Server交互的代理类,BBinder则是和proxy相对的一端,它是proxy交互的目的端。如果说Proxy代表客户端,那么BBinder就代表这服务端。这里BpBinder和BBinder是一一对应的,即某个BpBinder只能和对应的BBinder交互。

IBinder.h

// IBinder从Refbase继承而来,一提供强弱指针计数能力
class IBinder : public virtual RefBase
{
public:
    enum {
        FIRST_CALL_TRANSACTION  = 0x00000001,
        LAST_CALL_TRANSACTION   = 0x00ffffff,

        PING_TRANSACTION        = B_PACK_CHARS('_','P','N','G'),
        DUMP_TRANSACTION        = B_PACK_CHARS('_','D','M','P'),
        INTERFACE_TRANSACTION   = B_PACK_CHARS('_', 'N', 'T', 'F'),
        SYSPROPS_TRANSACTION    = B_PACK_CHARS('_', 'S', 'P', 'R'),

        // Corresponds to TF_ONE_WAY -- an asynchronous call.
        FLAG_ONEWAY             = 0x00000001
    };

                          IBinder();

    // 根据descriptor查询相应的IInterface对象
    virtual sp<IInterface>  queryLocalInterface(const String16& descriptor);

    // 获取descriptor描述符
    virtual const String16& getInterfaceDescriptor() const = 0;

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

    // transact binder通信函数
    virtual status_t        transact(   uint32_t code,
                                        const Parcel& data,
                                        Parcel* reply,
                                        uint32_t flags = 0) = 0;

    // 死亡通知相应类
    class DeathRecipient : public virtual RefBase
    {
    public:
        virtual void binderDied(const wp<IBinder>& who) = 0;
    };

    
    // 如其名,用于注册Binder用的
virtual status_t        linkToDeath(const sp<DeathRecipient>& recipient,
                                        void* cookie = NULL,
                                        uint32_t flags = 0) = 0;

    // 撤销用之前注册的死亡通知函数
virtual status_t        unlinkToDeath(  const wp<DeathRecipient>& recipient,
                                            void* cookie = NULL,
                                            uint32_t flags = 0,
                                            wp<DeathRecipient>* outRecipient = NULL) = 0;

    virtual bool            checkSubclass(const void* subclassID) const;

    typedef void (*object_cleanup_func)(const void* id, void* obj, void* cleanupCookie);

    virtual void            attachObject(   const void* objectID,
                                            void* object,
                                            void* cleanupCookie,
                                            object_cleanup_func func) = 0;
    virtual void*           findObject(const void* objectID) const = 0;
    virtual void            detachObject(const void* objectID) = 0;
 
    // 返回服务端的binder引用
virtual BBinder*        localBinder();
    // 放回客户端的binder引用
virtual BpBinder*       remoteBinder();

protected:
    virtual          ~IBinder();

private:
};

  对于IBinder中的方法,基本都是没有实现的,这些方法的实现都交给继承它的子类来实现,那下面直接看BpBinder的内容。

BpBinder

BpBinder.h

class BpBinder : public IBinder
{
public:
                        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;
            // BpBinder代理端是否还存活
            volatile int32_t    mAlive;
            // 是否已发送过死亡通知
            volatile int32_t    mObitsSent;
            // 用Vector保存死亡通知信息
            Vector<Obituary>*   mObituaries;
            ObjectManager       mObjects;
            Parcel*             mConstantData;
    mutable String16            mDescriptorCache;
};

BpBinder的构造函数

BpBinder::BpBinder(int32_t handle)
    : mHandle(handle)  // 将传入的handle值保存到mHandle成员变量里
    , mAlive(1)        // mAlive设置为1
    , mObitsSent(0)
    , mObituaries(NULL)
{
    ALOGV("Creating BpBinder %p handle %d\n", this, mHandle);

    extendObjectLifetime(OBJECT_LIFETIME_WEAK);
    IPCThreadState::self()->incWeakHandle(handle);
}

  首先调用extendObjectLifetime将对象改为弱引用控制,通过IPCThreadState的incWeakHandle增加Binder Service的如引用计数值。IncWeakHandle如下:

void IPCThreadState::incWeakHandle(int32_t handle)
{
    LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
    mOut.writeInt32(BC_INCREFS);
    mOut.writeInt32(handle);
}

  这一步只是将BC_INCREFS请求写到mOut中,还没有发送出去。

  除了incWeakHandle函数外还有decWeakHandle,incStrongHandle和decStrongHandle与Binder协议中的其他命令对应起来。

getInterfaceDescriptor函数

const String16& BpBinder::getInterfaceDescriptor() const
{
    if (isDescriptorCached() == false) {
        Parcel send, reply;
        // 通过BpBinder的transact函数将INTERFACE_TRANSACTION请求发送出去
        status_t err = const_cast<BpBinder*>(this)->transact(
                INTERFACE_TRANSACTION, send, &reply);
         // 调用没有出错
        if (err == NO_ERROR) {
            // 读取返回值得内容
            String16 res(reply.readString16());
            Mutex::Autolock _l(mLock);
            // mDescriptorCache could have been assigned while the lock was
            // released.
            if (mDescriptorCache.size() == 0)
                mDescriptorCache = res;
        }
    }

    // we're returning a reference to a non-static object here. Usually this
    // is not something smart to do, however, with binder objects it is
    // (usually) safe because they are reference-counted.

    return mDescriptorCache;
}

  这里是通过BpBinder的transact函数将请求发送出去,transact函数相当重要,下面我们就看看这个函数。

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) {
        // 调用IPCThreadState的transact函数
        status_t status = IPCThreadState::self()->transact(
            mHandle, code, data, reply, flags);
        if (status == DEAD_OBJECT) mAlive = 0;
        return status;
    }

    return DEAD_OBJECT;
}

  这么看,BpBinder这个代理端的数据发送其实也不是自己执行数据传输的操作,而是调用IPCThreadState的transact函数进行数据传输。

IPCThreadState::transact函数

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 (err == NO_ERROR) {
        LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
            (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
    // 调用writeTransactionData,将data中的数据打包成binder_transaction_data
    // 结构并写入到mOut中
        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) {
        // 和Binder驱动通信,等待数据回复
            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);
    }
    
#ifdef _MTK_ENG_BUILD_
    if (err != NO_ERROR) {
        ALOGD("transact return err=%d\n", (int32_t)err);
    }
#endif
    return err;
}

  IPCThreadState的transact函数主要的步骤是两个,首先调用writeTransactionData,在这个函数里面主要工作是将Parcel类变量data打包成一个binder_transaction_data,然后将其写到mOut中,方法比较简单,代码就不贴出来了。然后调用waitForResponse,等待binder驱动处理数据。

waitForResponse函数

status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
{
    uint32_t cmd;
    int32_t err;

    while (1) {
        if ((err=talkWithDriver()) < NO_ERROR) break;
        err = mIn.errorCheck();
        if (err < NO_ERROR) break;
        if (mIn.dataAvail() == 0) continue;
        
        cmd = (uint32_t)mIn.readInt32();
    
        ……………..

        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 binder_size_t*>(tr.data.ptr.offsets),
                            tr.offsets_size/sizeof(binder_size_t),
                            freeBuffer, this);
                    } else {
                        err = *reinterpret_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 binder_size_t*>(tr.data.ptr.offsets),
                            tr.offsets_size/sizeof(binder_size_t), this);
                    }
                } else {
                    freeBuffer(NULL,
                        reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
                        tr.data_size,
                        reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
                        tr.offsets_size/sizeof(binder_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;
}

  waitForResponse函数里面,首先调用talkWithDriver和Binder驱动进行交互,talkWithDrive里面通过ioctl系统调用,调用到binder驱动的binder_ioctl,然后根据binder驱动处理后的结果switch操作。除去一些BR_返回操作特殊处理外,default状态是调用executeCommand对返回值进行处理的。getInterfaceDescriptor和transact的内容就看到这里。

linkToDeath函数

status_t BpBinder::linkToDeath(
    const sp& recipient, void* cookie, uint32_t flags)
{
    Obituary ob;
    ob.recipient = recipient;
    ob.cookie = cookie;
    ob.flags = flags;

    ……………

    {
        AutoMutex _l(mLock);

        // 还没有发送过死亡通知
        if (!mObitsSent) {
        // 第一次调用的话,mObituaries还没有分配内存
            if (!mObituaries) {
                mObituaries = new Vector<Obituary>;
                if (!mObituaries) {
                    return NO_MEMORY;
                }
                ALOGV("Requesting death notification: %p handle %d\n", this, mHandle);
                getWeakRefs()->incWeak(this);
                IPCThreadState* self = IPCThreadState::self();
                self->requestDeathNotification(mHandle, this);
                self->flushCommands();
            }
            ssize_t res = mObituaries->add(ob);
            return res >= (ssize_t)NO_ERROR ? (status_t)NO_ERROR : res;
        }
    }

    return DEAD_OBJECT;
}

  首先判断是否已经发送过死亡通知,如果没有发送过那么就分配内存,然后调用IPCThreadState的requestDeathNotification,将自己注册到binder驱动里面去,然后将Obituary添加到vector里。

requestDeathNotification && flushCommands

status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
{
    mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
    mOut.writeInt32((int32_t)handle);
    mOut.writePointer((uintptr_t)proxy);
    return NO_ERROR;
}

void IPCThreadState::flushCommands()
{
    if (mProcess->mDriverFD <= 0)
        return;
    talkWithDriver(false);
}

  所以也是将数据写到mOut中,然后调用IPCThreadState的flushCommands,然后再主动调用talkWithDriver和binder驱动进行交互。前面讲到talkWithDriver就是通过ioctl系统调用,进入到binder驱动,这里最后会调用到binder驱动中的binder_thread_write函数。

binder_thread_write的BC_REQUEST_DEATH_NOTIFICATION部分

// 这里注册和清除死亡通知走的是同一个分支
case BC_REQUEST_DEATH_NOTIFICATION:
case BC_CLEAR_DEATH_NOTIFICATION:{
    uint32_t target;
    binder_uintptr_t cookie;
    struct binder_ref *ref;
    struct binder_ref_death *death;

    // 取得requestDeathNotification中写入的handle值
    if (get_user(target, (uint32_t __user *) ptr))
        return -EFAULT;
    ptr += sizeof(uint32_t);
    // 获取BpBinder的指针
    if (get_user(cookie, (binder_uintptr_t __user *) ptr))
        return -EFAULT;
    ptr += sizeof(binder_uintptr_t);
    ref = binder_get_ref(proc, target, false);
    if (ref == NULL) {
        binder_user_error("%d:%d %s invalid ref %d\n",
            proc->pid, thread->pid,
            cmd == BC_REQUEST_DEATH_NOTIFICATION ?
            "BC_REQUEST_DEATH_NOTIFICATION" :
            "BC_CLEAR_DEATH_NOTIFICATION", target);
        break;
    }

    ……………………..

    if (cmd == BC_REQUEST_DEATH_NOTIFICATION) {
    // 判断之前是否已经注册过死亡通知了
        if (ref->death) {
            binder_user_error("%d:%d BC_REQUEST_DEATH_NOTIFICATION death notification already set\n",
                proc->pid, thread->pid);
            break;
        }
        death = kzalloc(sizeof(*death), GFP_KERNEL);
        if (death == NULL) {
            thread->return_error = BR_ERROR;
            binder_debug(BINDER_DEBUG_FAILED_TRANSACTION,
                     "%d:%d BC_REQUEST_DEATH_NOTIFICATION failed\n",
                     proc->pid, thread->pid);
            break;
        }
        binder_stats_created(BINDER_STAT_DEATH);
        // 初始化工作队列
        INIT_LIST_HEAD(&death->work.entry);
        // 将传入的指针保存到binder_ref_death中
        death->cookie = cookie;
        ref->death = death;
        if (ref->node->proc == NULL) {
            ref->death->work.type = BINDER_WORK_DEAD_BINDER;
            if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) {
                list_add_tail(&ref->death->work.entry, &thread->todo);
            } else {
                list_add_tail(&ref->death->work.entry, &proc->todo);
                wake_up_interruptible(&proc->wait);
            }
        }
    } else {
       // else部分先不看
    }
}

  到这里死亡通知的注册工作就做完了,其实看这部分的时候一直有个疑问,就是在linkToDeath中用的是Vector类,表明可以有多个Obituary,但是在binder驱动里面有if (ref->death)判断之前是否已经注册过死亡通知了,那么不就代表只能注册一个死亡通知吗,哪位什么还要用Vector来保存,这里实在想不明白。

unlinkToDeath函数

status_t BpBinder::unlinkToDeath(
    const wp<DeathRecipient>& recipient, void* cookie, uint32_t flags,
    wp<DeathRecipient>* outRecipient)
{
    AutoMutex _l(mLock);

    // 已经发送过死亡通知了
    if (mObitsSent) {
        return DEAD_OBJECT;
    }

    const size_t N = mObituaries ? mObituaries->size() : 0;
    for (size_t i=0; iitemAt(i);
        // 找到对应的死亡通知对象
        if ((obit.recipient == recipient
                    || (recipient == NULL && obit.cookie == cookie))
                && obit.flags == flags) {
            if (outRecipient != NULL) {
                *outRecipient = mObituaries->itemAt(i).recipient;
            }
            mObituaries->removeAt(i);
            if (mObituaries->size() == 0) {
                ALOGV("Clearing death notification: %p handle %d\n", this, mHandle);
                IPCThreadState* self = IPCThreadState::self();
                // 调用IPCThreadState的clearDeathNotification
                self->clearDeathNotification(mHandle, this);
                // flushCommands与binder交互
                self->flushCommands();
                delete mObituaries;
                mObituaries = NULL;
            }
            return NO_ERROR;
        }
    }

    return NAME_NOT_FOUND;
}

  clearDeathNotification函数的内容和requestDeathNotification函数的内容基本类似,只是填充的command改成BC_CLEAR_DEATH_NOTIFICATION了而已,然后flushCommands前面已经看多,接下来看看binder驱动如何处理BC_CLEAR_DEATH_NOTIFICATION的。

BC_CLEAR_DEATH_NOTIFICATION的处理

case BC_REQUEST_DEATH_NOTIFICATION:
case BC_CLEAR_DEATH_NOTIFICATION:{
    uint32_t target;
    binder_uintptr_t cookie;
    struct binder_ref *ref;
    struct binder_ref_death *death;

    if (get_user(target, (uint32_t __user *) ptr))
        return -EFAULT;
    ptr += sizeof(uint32_t);
    if (get_user(cookie, (binder_uintptr_t __user *) ptr))
        return -EFAULT;
    ptr += sizeof(binder_uintptr_t);
    ref = binder_get_ref(proc, target, false);
    if (ref == NULL) {
        binder_user_error("%d:%d %s invalid ref %d\n",
            proc->pid, thread->pid,
            cmd == BC_REQUEST_DEATH_NOTIFICATION ?
            "BC_REQUEST_DEATH_NOTIFICATION" :
            "BC_CLEAR_DEATH_NOTIFICATION", target);
        break;
    }

    ……………………

    if (cmd == BC_REQUEST_DEATH_NOTIFICATION) {
    // 这部分上面已经看过了
         }
    } else {
    // 死亡通知已经处理过了
        if (ref->death == NULL) {
            binder_user_error("%d:%d BC_CLEAR_DEATH_NOTIFICATION death notification not active\n",
                proc->pid, thread->pid);
            break;
        }
        death = ref->death;
        if (death->cookie != cookie) {
            binder_user_error("%d:%d BC_CLEAR_DEATH_NOTIFICATION death notification cookie mismatch %016llx != %016llx\n",
                proc->pid, thread->pid,
                (u64) death->cookie, (u64) cookie);
            break;
        }
        ref->death = NULL;
        if (list_empty(&death->work.entry)) {
        // 改变work type
            death->work.type = BINDER_WORK_CLEAR_DEATH_NOTIFICATION;
            // 然后根据work的状态加到对应的todo队列中
            if (thread->looper & (BINDER_LOOPER_STATE_REGISTERED | BINDER_LOOPER_STATE_ENTERED)) {
                list_add_tail(&death->work.entry, &thread->todo);
            } else {
                list_add_tail(&death->work.entry, &proc->todo);
                wake_up_interruptible(&proc->wait);
            }
        } else {
            BUG_ON(death->work.type != BINDER_WORK_DEAD_BINDER);
            death->work.type = BINDER_WORK_DEAD_BINDER_AND_CLEAR;
        }
    }

  这里改变command为BINDER_WORK_CLEAR_DEATH_NOTIFICATION了,要等到下一个binder_thread_read就会处理这个command

BINDER_WORK_CLEAR_DEATH_NOTIFICATION

case BINDER_WORK_DEAD_BINDER:
case BINDER_WORK_DEAD_BINDER_AND_CLEAR:
case BINDER_WORK_CLEAR_DEATH_NOTIFICATION:{
        struct binder_ref_death *death;
        uint32_t cmd;

        death = container_of(w, struct binder_ref_death, work);

        // 走这里
        if (w->type == BINDER_WORK_CLEAR_DEATH_NOTIFICATION)
            // 返回给用户空间的BR_ command
            cmd = BR_CLEAR_DEATH_NOTIFICATION_DONE;
        else
            cmd = BR_DEAD_BINDER;
        // 获取的内容直接返回给用户空间
        if (put_user(cmd, (uint32_t __user *) ptr))
            return -EFAULT;
        ptr += sizeof(uint32_t);
        if (put_user(death->cookie, (binder_uintptr_t __user *) ptr))
            return -EFAULT;
        ptr += sizeof(binder_uintptr_t);
        binder_stat_br(proc, thread, cmd);
        binder_debug(BINDER_DEBUG_DEATH_NOTIFICATION,
                 "%d:%d %s %016llx\n",
                 proc->pid, thread->pid,
                 cmd == BR_DEAD_BINDER ?
                 "BR_DEAD_BINDER" :
                 "BR_CLEAR_DEATH_NOTIFICATION_DONE",
                 (u64) death->cookie);
        // 做清理工作
        if (w->type == BINDER_WORK_CLEAR_DEATH_NOTIFICATION) {
             // 删除死亡通知的work队列
            list_del(&w->entry);
            // 释放binder_death占用的内容空间
            kfree(death);
            // 删除注册时加进去的BINDER_STATE_DEATH
            binder_stats_deleted(BINDER_STAT_DEATH);
        } else
            list_move(&w->entry, &proc->delivered_death);
        if (cmd == BR_DEAD_BINDER)
            goto done; /* DEAD_BINDER notifications can cause transactions */
    }
    break;

  上面直接将注册时传给binder驱动的BpBinder给传回给用户空间,其command为BR_CLEAR_DEATH_NOTIFICATION_DONE。

BR_CLEAR_DEATH_NOTIFICATION_DONE

case BR_CLEAR_DEATH_NOTIFICATION_DONE:
    {
        BpBinder *proxy = (BpBinder*)mIn.readPointer();
        proxy->getWeakRefs()->decWeak(proxy);
    } break;

这里只是做最后的清理工作。OK,unlinkToDeath就完成所有工作了。

attachObject、findObject、detachObject

attachObject

void BpBinder::attachObject(
    const void* objectID, void* object, void* cleanupCookie,
    object_cleanup_func func)
{
    AutoMutex _l(mLock);
    ALOGV("Attaching object %p to binder %p (manager=%p)", object, this, &mObjects);
    mObjects.attach(objectID, object, cleanupCookie, func);
}

  从代码中可以知道,attachObject的工作是通过mObjects的attach来完成的,查看BpBinder.h的代码可以知道mObject的类型是ObjectManager,所以BpBinder的attachObjec的工作是交个BpBinder的内部类ObjectManager的attach来完成的。

void BpBinder::ObjectManager::attach(
    const void* objectID, void* object, void* cleanupCookie,
    IBinder::object_cleanup_func func)
{
    entry_t e;
    e.object = object;
    e.cleanupCookie = cleanupCookie;
    e.func = func;

    if (mObjects.indexOfKey(objectID) >= 0) {
        ALOGE("Trying to attach object ID %p to binder ObjectManager %p with object %p, but object ID already in use",
                objectID, this,  object);
        return;
    }

    mObjects.add(objectID, e);
}

findObject && detachObject && kill

  findObject、detachObject和函数的内容和attachObject基本一样,所以这里只贴出代码好了,分析相对简单,请大家自行查看。

void* BpBinder::ObjectManager::find(const void* objectID) const
{
    const ssize_t i = mObjects.indexOfKey(objectID);
    if (i < 0) return NULL;
    return mObjects.valueAt(i).object;
}

void BpBinder::ObjectManager::detach(const void* objectID)
{
    mObjects.removeItem(objectID);
}


void* BpBinder::findObject(const void* objectID) const
{
    AutoMutex _l(mLock);
    return mObjects.find(objectID);
}

void BpBinder::detachObject(const void* objectID)
{
    AutoMutex _l(mLock);
    mObjects.detach(objectID);
}

sendObituary函数

void BpBinder::sendObituary()
{
    ALOGV("Sending obituary for proxy %p handle %d, mObitsSent=%s\n",
        this, mHandle, mObitsSent ? "true" : "false");

    mAlive = 0;
    // 如果已经发送过死亡通知了就直接返回
    if (mObitsSent) return;

    mLock.lock();
    Vector<Obituary>* obits = mObituaries;
    if(obits != NULL) {
        ALOGV("Clearing sent death notification: %p handle %d\n", this, mHandle);
        // 清除注册在binder驱动中的死亡通知
        IPCThreadState* self = IPCThreadState::self();
        self->clearDeathNotification(mHandle, this);
        self->flushCommands();
        mObituaries = NULL;
    }
    mObitsSent = 1;
    mLock.unlock();

    ALOGV("Reporting death of proxy %p for %zu recipients\n",
        this, obits ? obits->size() : 0U);

    if (obits != NULL) {
        const size_t N = obits->size();
        for (size_t i=0; iitemAt(i));
        }

        delete obits;
    }
}

void BpBinder::reportOneDeath(const Obituary& obit)
{
    sp<DeathRecipient> recipient = obit.recipient.promote();
    ALOGV("Reporting death to recipient: %p\n", recipient.get());
    if (recipient == NULL) return;

    recipient->binderDied(this);
}

  这里首先要判断之前是否已经发送过死亡通知,如果已经发送过了,那当然就不用再次发送了。如果没有发送过死亡通知的话,那么首先需要调用IPCThreadState的clearDeathNotification,来清除注册到binder驱动中的死亡通知,这两个函数在unlinkToDeath中已经有介绍了,这里就略过。最后会调用保存到mObituaries这个vector里面的死亡通知函数来通知相应的BpBinder实例。

BBinder

BBinder类

class BBinder : public IBinder
{
public:
                        BBinder();

    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 BBinder*    localBinder();

protected:
    virtual             ~BBinder();

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

private:
                        BBinder(const BBinder& o);
            BBinder&    operator=(const BBinder& o);

    class Extras;

    atomic_uintptr_t    mExtras;  // should be atomic<Extras *>
            void*       mReserved0;
};

  其中,isBinderAlive函数只是返回true,这很好理解,因为BBinder代表的是Binder通信中的服务端,服务端是否存活,服务端自己当然是知道的。同时linkToDeath和unlinkToDeath这两个函数都只是返回INVALID_OPERATION,表明这两个函数在服务端是不需要做什么的,毕竟这两个函数是用来注册死亡通知用的。

transact函数

status_t BBinder::transact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
    data.setDataPosition(0);

    status_t err = NO_ERROR;
    switch (code) {
        // 如果是ping command,走这个分支
        case PING_TRANSACTION:
            reply->writeInt32(pingBinder());
            break;

        // 否则默认调用onTransact函数
        default:
            err = onTransact(code, data, reply, flags);
            break;
    }

    if (reply != NULL) {
        reply->setDataPosition(0);
    }

    return err;
}

  那么接下来直接看onTransact函数好了。

status_t BBinder::onTransact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t /*flags*/)
{
    switch (code) {
        case INTERFACE_TRANSACTION:
            reply->writeString16(getInterfaceDescriptor());
            return NO_ERROR;

        case DUMP_TRANSACTION: {
            int fd = data.readFileDescriptor();
            int argc = data.readInt32();
            Vector<String16> args;
            for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
               args.add(data.readString16());
            }
            return dump(fd, args);
        }

        case SYSPROPS_TRANSACTION: {
            report_sysprop_change();
            return NO_ERROR;
        }

        default:
            return UNKNOWN_TRANSACTION;
    }
}

  没有什么实际的内容,看样子,在编写实际的Binder服务端程序的时候应该是会重载这个函数,以提供实际的功能。

attachObject、detachObject、findObject

class BBinder::Extras
{
public:
    Mutex mLock;
    BpBinder::ObjectManager mObjects;
};

void BBinder::attachObject(
    const void* objectID, void* object, void* cleanupCookie,
    object_cleanup_func func)
{
    Extras* e = reinterpret_cast<Extras*>(
                    atomic_load_explicit(&mExtras, memory_order_acquire));

    if (!e) {
        e = new Extras;
        uintptr_t expected = 0;
        if (!atomic_compare_exchange_strong_explicit(
                                        &mExtras, &expected,
                                        reinterpret_cast<uintptr_t>(e),
                                        memory_order_release,
                                        memory_order_acquire)) {
            delete e;
            e = reinterpret_cast<Extras*>(expected);  // Filled in by CAS
        }
        if (e == 0) return; // out of memory
    }

    AutoMutex _l(e->mLock);
    e->mObjects.attach(objectID, object, cleanupCookie, func);
}

// The C11 standard doesn't allow atomic loads from const fields,
// though C++11 does.  Fudge it until standards get straightened out.
static inline uintptr_t load_const_atomic(const atomic_uintptr_t* p,
                                          memory_order mo) {
    atomic_uintptr_t* non_const_p = const_cast<atomic_uintptr_t*>(p);
    return atomic_load_explicit(non_const_p, mo);
}

void* BBinder::findObject(const void* objectID) const
{
    Extras* e = reinterpret_cast<Extras*>(
                    load_const_atomic(&mExtras, memory_order_acquire));
    if (!e) return NULL;

    AutoMutex _l(e->mLock);
    return e->mObjects.find(objectID);
}

void BBinder::detachObject(const void* objectID)
{
    Extras* e = reinterpret_cast<Extras*>(
                    atomic_load_explicit(&mExtras, memory_order_acquire));
    if (!e) return;

    AutoMutex _l(e->mLock);
    e->mObjects.detach(objectID);
}

这三个函数的功能也是通过BpBinder中的ObjectManager来实现的。

  BBinder的代码不多s,看样子主要还是依靠具体服务端的特性来添加相应的功能的。

IInterface

IInterface.h

// IInterface类定义处
class IInterface : public virtual RefBase
{
public:
            IInterface();
            static sp<IBinder>  asBinder(const IInterface*);
            static sp<IBinder>  asBinder(const sp<IInterface>&);

protected:
    virtual                     ~IInterface();
    virtual IBinder*            onAsBinder() = 0;
};

// ----------------------------------------------------------------------

template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
    return INTERFACE::asInterface(obj);
}

// ----------------------------------------------------------------------

// BnInterface类模板定义
template<typename INTERFACE>
class BnInterface : public INTERFACE, public BBinder
{
public:
    virtual sp<IInterface>      queryLocalInterface(const String16& _descriptor);
    virtual const String16&     getInterfaceDescriptor() const;

protected:
    virtual IBinder*            onAsBinder();
};

// ----------------------------------------------------------------------
// BpInterface类模板定义,继承了INTERFACE(模板类)和BpRefBase类
template<typename INTERFACE>
class BpInterface : public INTERFACE, public BpRefBase
{
public:
                                BpInterface(const sp<IBinder>& remote);

protected:
    virtual IBinder*            onAsBinder();
};

// ----------------------------------------------------------------------

// DECLARE_META_INTERFACE宏定义
#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();                                            \

// 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() { }                                   \


#define CHECK_INTERFACE(interface, data, reply)                         \
    if (!data.checkInterface(this)) { return PERMISSION_DENIED; }       \


// ----------------------------------------------------------------------
// No user-serviceable parts after this...
// BnInterface:: queryLocalInterface方法实现
template<typename INTERFACE>
inline sp<IInterface> BnInterface<INTERFACE>::queryLocalInterface(
        const String16& _descriptor)
{
    if (_descriptor == INTERFACE::descriptor) return this;
    return NULL;
}

// BnInterface:: getInterfaceDescriptor方法实现
template<typename INTERFACE>
inline const String16& BnInterface<INTERFACE>::getInterfaceDescriptor() const
{
    return INTERFACE::getInterfaceDescriptor();
}

template<typename INTERFACE>
IBinder* BnInterface<INTERFACE>::onAsBinder()
{
    return this;
}

template<typename INTERFACE>
inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)
    : BpRefBase(remote)
{
}

template<typename INTERFACE>
inline IBinder* BpInterface<INTERFACE>::onAsBinder()
{
    return remote();
}

  除了构造函数和析构函数外,IInterface类里面只带有一个实现了的类方法,两个不同的重载,就是将IInterface参数转换成IBinder对象,然后返回给调用者,这样子调用者就可以使用IBinder提供的transact、onTransact等函数进行Binder数据传输了。

DECLARE_META_INTERFACE

  首先看看DECLARE_META_INTERFACE宏,我们直接将一个具体参数代替INTERFACE好了,这里假定适应CameraService来代替INTERFACE,得到如下的内容

static const android::String16 descriptor;                          
static android::sp<ICameraService> asInterface(                       
const android::sp<android::IBinder>& obj);                  
virtual const android::String16& getInterfaceDescriptor() const;    
ICameraService ();                                                   
virtual ~ ICameraService ();

  替换之后的内容就很容易理解了,无非就是定义了一些方法,那么IMPLEMENT_META_INTERFACE应该就是实现这些方法的宏了,下面看看替换后的IMPLEMENT_META_INTERFACE的内容是什么。

IMPLEMENT_META_INTERFACE

  其中依旧用CameraService来代替INTERFACE,然后用android.os.ICameraService来代替NAME,所以得到的代码如下:

const android::String16 ICameraService::descriptor(android.os.ICameraService);             
const android::String16&                                            
        ICameraService::getInterfaceDescriptor() const {              
    return ICameraService::descriptor;                                
}                                                                   
android::sp<ICameraService> ICameraService::asInterface(                
        const android::sp<android::IBinder>& obj)                   
{                                                                   
    android::sp<ICameraService> intr;                                 
    if (obj != NULL) {                                              
        intr = static_cast<ICameraService*>(                          
            obj->queryLocalInterface(                              
                    ICameraService::descriptor).get());               
        if (intr == NULL) {                                         
            intr = new BpCameraService(obj);                          
        }                                                           
    }                                                               
    return intr;                                                    
}                                                                   
ICameraService::ICameraService() { }                                    
ICameraService::~ICameraService() { }                                   

  其实将descriptor定义为android.os.ICameraService,然后getInterfaceDescriptor函数可以获取到这个descriptor。然后在asInterface函数中,将一个IBinder对象转换为一个BpInterface类对象。

  这篇大概就看到这里好了,IInterface里面还有一些其他的函数,暂时也没办法彻底说清楚他们的作用,所以就先留着吧,到后面有机会看到再说好了。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d 博主赞过: