Android之binder驱动个人学习小结

Read the fucking Source Code.
这段时间,大概花了两个星期(期间还偷懒了好几天),深入学习了一下Android的Binder驱动。话说上半年在看Mediaplay的源码时,就遇到过很多的IPC,当时也没有深入的去了解这块内容。这次为了对Android有一个系统级别的了解,所以较为深入的学习了一番。主要参考的内容包括:csdn的android 红人老罗,以及手里的一本杨丰盛的Android技术内幕(系统卷),作为主要的学习资料。当然我所小结的内容,也没有他们那么的详细,只是理清了整个思路而已。
注释:
SM:ServiceManager
MS:MediaPlayerService
xxx:指的是某种服务,入HelloService。
一.Binder驱动的整体架构
单从C++层宏观上看来,binder驱动的主要组成部分是:client(客户端),server(服务端),一个Service Manager和binder底层驱动。
整体的框图如下(摘自老罗的图):

其实从图中可以清晰的发现,在Android的应用层中Client和Server所谓的IPC,其实真正的工作均由底层的Binder驱动来完成。也就是说binder驱动可以完成进程间通信,这也是Android特点之一。Service Manager做为一个守护进程,主要来处理客户端的服务请求,管理所有的服务项。
 
二.binder底层驱动核心内容。
说到底,binder底层的驱动架构和通用的linux驱动没有区别,核心的内容包括binder_init,binder_open,binder_mmap,binder_ioctl.
binder驱动在Android系统中以miscdevice完成设备的注册,作为抽象设备,他没有直接操作硬件,只是完成了内存的拷贝处理。如果要深入理解这块机制,请参考老罗的android之旅。在这里对binder_ioctl做一定的分析:
2.1 驱动核心的操作数据结构:
binder_proc和binder_thread:
每open一个binder驱动(系统允许多个进程打开binder驱动),都会有一个专门的binder_proc管理当前进程的信息,包括进程的ID,当前进程由mmap所映射出的buffer信息,以及当前进程所允许的最大线程量。同时这个binder_proc会加入到系统的全局链表binder_procs中去,方便在不同进程之间可以查找信息。
binder_thread:在当前进程下存在多线程,因此binder驱动使用binder_thread来管理对应的线程信息,主要包括线程所属的binder_proc、当前状态looper以及一个transaction_stack(我的理解是负责着实际进程间通信交互的源头和目的地)。
binder_write_read :
[plain]
struct binder_write_read { 
    signed long write_size; /* bytes to write */ 
    signed long write_consumed; /* bytes consumed by driver */ 
    unsigned long   write_buffer; 
    signed long read_size;  /* bytes to read */ 
    signed long read_consumed;  /* bytes consumed by driver */ 
    unsigned long   read_buffer; 
}; 
在binder驱动中,以该结构体作为信息封装的中转(可以理解为内核和用户的连接)。在驱动中为根据write_size和read_size的大小来进行处理(见ioctl的解析部分),在write_buffer和read_buffer都代表着用户空间的buffer地址。在write_buffer中,由一个cmd和binder_transaction_data组成,cmd主要告知驱动当前所要处理的内容。
binder_transaction_data:
[plain]  
struct binder_transaction_data { 
    /* The first two are only used for bcTRANSACTION and brTRANSACTION, 
     * identifying the target and contents of the transaction. 
     */ 
    union { 
        size_t  handle; /* target descriptor of command transaction */ 
        void    *ptr;   /* target descriptor of return transaction */ 
    } target; 
    void        *cookie;    /* target object cookie */ 
    unsigned int    code;       /* transaction command */ 
 
    /* General information about the transaction. */ 
    unsigned int    flags; 
    pid_t       sender_pid; 
    uid_t       sender_euid; 
    size_t      data_size;  /* number of bytes of data */ 
    size_t      offsets_size;   /* number of bytes of offsets */ 
 
    /* If this transaction is inline, the data immediately 
     * follows here; otherwise, it ends with a pointer to 
     * the data buffer. 
     */ 
    union { 
        struct { 
            /* transaction data */ 
            const void  *buffer; 
            /* offsets from buffer to flat_binder_object structs */ 
            const void  *offsets; 
        } ptr; 
        uint8_t buf[8]; 
    } data; 
}; 
在这里,buffer和offsets分别代表传输内容的数据量以及Binder实体的偏移量(会遇到多个Binder实体)。
binder_transaction:该结构体主要C/S即请求进程和服务进程的相关信息,方便进程间通信,以及信息的调用
binder_work:理解为binder驱动中,进程所要处理的工作项。
binder_transactionbinder_transactionbinder_transactionbinder_transaction
2.2 binder驱动之ioctl解析:
和常用的ioctl相类似,在这里我们关注BINDER_WRITE_READ命令项的内容。
binder_thread_write和binder_thread_read会根据用户传入的write_size和read_size的有无来进行处理。在这里以Mediaplayservice和ServiceManager的通信来分析,调用的cmd如下:
MS首先传入cmd=BC_TRANSACTION:
调用binder_transaction:
[plain] 
static void binder_transaction(struct binder_proc *proc, 
                   struct binder_thread *thread, 
                   struct binder_transaction_data *tr, int reply) 

...else {//client请求service 
        if (tr->target.handle) {//SM时为target.handle=0 
            struct binder_ref *ref; 
            ref = binder_get_ref(proc, tr->target.handle); 
            if (ref == NULL) { 
                binder_user_error("binder: %d:%d got " 
                    "transaction to invalid handle\n", 
                    proc->pid, thread->pid); 
                return_error = BR_FAILED_REPLY; 
                goto err_invalid_target_handle; 
            } 
            target_node = ref->node; 
        } else { 
            target_node = binder_context_mgr_node;//调用的是SM守护进程节点 
            if (target_node == NULL) { 
                return_error = BR_DEAD_REPLY; 
                goto err_no_context_mgr_node; 
            } 
        } 
        e->to_node = target_node->debug_id; 
        target_proc = target_node->proc;//SM守护进程的相关信息 
        if (target_proc == NULL) { 
            return_error = BR_DEAD_REPLY; 
            goto err_dead_binder; 
        } 
        if (!(tr->flags & TF_ONE_WAY) && thread->transaction_stack) { 
            struct binder_transaction *tmp; 
            tmp = thread->transaction_stack; 
            if (tmp->to_thread != thread) { 
                binder_user_error("binder: %d:%d got new " 
                    "transaction with bad transaction stack" 
                    ", transaction %d has target %d:%d\n", 
                    proc->pid, thread->pid, tmp->debug_id, 
                    tmp->to_proc ? tmp->to_proc->pid : 0, 
                    tmp->to_thread ? 
                    tmp->to_thread->pid : 0); 
                return_error = BR_FAILED_REPLY; 
                goto err_bad_call_stack; 
            } 
            while (tmp) { 
                if (tmp->from && tmp->from->proc == target_proc) 
                    target_thread = tmp->from; 
                tmp = tmp->from_parent; 
            } 
        } 
    } 
    if (target_thread) { 
        e->to_thread = target_thread->pid; 
        target_list = &target_thread->todo; 
        target_wait = &target_thread->wait; 
    } else { 
        target_list = &target_proc->todo;//SM进程binder_proc的todo 
        target_wait = &target_proc->wait;//等待队列头,对应于SM 
    } 
    ... 
    if (!reply && !(tr->flags & TF_ONE_WAY)) 
        t->from = thread;//事务性记录from binder进程,即记录下请求进程 
    else 
        t->from = NULL; 
    t->sender_euid = proc->tsk->cred->euid; 
    t->to_proc = target_proc; 
    t->to_thread = target_thread;//目的服务进程 
    t->code = tr->code; 
    t->flags = tr->flags; 
    t->priority = task_nice(current); 
    t->buffer = binder_alloc_buf(target_proc, tr->data_size, 
        tr->offsets_size, !reply && (t->flags & TF_ONE_WAY));//在SM上进程上开辟一个binder_buffer 
    if (t->buffer == NULL) { 
        return_error = BR_FAILED_REPLY; 
        goto err_binder_alloc_buf_failed; 
    } 
    t->buffer->allow_user_free = 0; 
    t->buffer->debug_id = t->debug_id; 
    t->buffer->transaction = t; 
    t->buffer->target_node = target_node; 
    if (target_node) 
        binder_inc_node(target_node, 1, 0, NULL);//增加目标节点的引用 
 
    offp = (size_t *)(t->buffer->data + ALIGN(tr->data_size, sizeof(void *)));//内存中的偏移量 
 
    if (copy_from_user(t->buffer->data, tr->data.ptr.buffer, tr->data_size)) { 
        binder_user_error("binder: %d:%d got transaction with invalid " 
            "data ptr\n", proc->pid, thread->pid); 
        return_error = BR_FAILED_REPLY; 
        goto err_copy_data_failed; 
    } 
    if (copy_from_user(offp, tr->data.ptr.offsets, tr->offsets_size)) { 
        binder_user_error("binder: %d:%d got transaction with invalid " 
            "offsets ptr\n", proc->pid, thread->pid); 
        return_error = BR_FAILED_REPLY; 
        goto err_copy_data_failed; 
    } 
    if (!IS_ALIGNED(tr->offsets_size, sizeof(size_t))) { 
        binder_user_error("binder: %d:%d got transaction with " 
            "invalid offsets size, %zd\n", 
            proc->pid, thread->pid, tr->offsets_size); 
        return_error = BR_FAILED_REPLY; 
        goto err_bad_offset; 
    } 
    off_end = (void *)offp + tr->offsets_size; 
    for (; offp < off_end; offp++) { 
        struct flat_binder_object *fp; 
        if (*offp > t->buffer->data_size - sizeof(*fp) || 
            t->buffer->data_size < sizeof(*fp) || 
            !IS_ALIGNED(*offp, sizeof(void *))) {       //对buffer大小做一定的检验 
            binder_user_error("binder: %d:%d got transaction with " 
                "invalid offset, %zd\n", 
                proc->pid, thread->pid, *offp); 
            return_error = BR_FAILED_REPLY; 
            goto err_bad_offset; 
        } 
        fp = (struct flat_binder_object *)(t->buffer->data + *offp);//获取一个binder实体 
        switch (fp->type) { 
        case BINDER_TYPE_BINDER://初次调用 
        case BINDER_TYPE_WEAK_BINDER: { 
            struct binder_ref *ref; 
            struct binder_node *node = binder_get_node(proc, fp->binder); 
            if (node == NULL) { 
                node = binder_new_node(proc, fp->binder, fp->cookie);//创建一个mediaservice节点 
                if (node == NULL) { 
                    return_error = BR_FAILED_REPLY; 
                    goto err_binder_new_node_failed; 
                } 
                node->min_priority = fp->flags & FLAT_BINDER_FLAG_PRIORITY_MASK; 
                node->accept_fds = !!(fp->flags & FLAT_BINDER_FLAG_ACCEPTS_FDS); 
            } 
            if (fp->cookie != node->cookie) { 
                binder_user_error("binder: %d:%d sending u%p " 
                    "node %d, cookie mismatch %p != %p\n", 
                    proc->pid, thread->pid, 
                    fp->binder, node->debug_id, 
                    fp->cookie, node->cookie); 
                goto err_binder_get_ref_for_node_failed; 
            } 
            ref = binder_get_ref_for_node(target_proc, node); 
            if (ref == NULL) { 
                return_error = BR_FAILED_REPLY; 
                goto err_binder_get_ref_for_node_failed; 
            } 
            if (fp->type == BINDER_TYPE_BINDER) 
                fp->type = BINDER_TYPE_HANDLE;//fp->type类型改为了BINDER_TYPE_HANDLE句柄 
            else 
                fp->type = BINDER_TYPE_WEAK_HANDLE; 
            fp->handle = ref->desc;// 
            binder_inc_ref(ref, fp->type == BINDER_TYPE_HANDLE, 
                       &thread->todo);//增加引用次数 
 
            binder_debug(BINDER_DEBUG_TRANSACTION, 
                     "        node %d u%p -> ref %d desc %d\n", 
                     node->debug_id, node->ptr, ref->debug_id, 
                     ref->desc); 
        } break; 
        case BINDER_TYPE_HANDLE: 
        case BINDER_TYPE_WEAK_HANDLE: { 
            struct binder_ref *ref = binder_get_ref(proc, fp->handle); 
            if (ref == NULL) { 
                binder_user_error("binder: %d:%d got " 
                    "transaction with invalid " 
                    "handle, %ld\n", proc->pid, 
                    thread->pid, fp->handle); 
                return_error = BR_FAILED_REPLY; 
                goto err_binder_get_ref_failed; 
            } 
            if (ref->node->proc == target_proc) { 
                if (fp->type == BINDER_TYPE_HANDLE) 
                    fp->type = BINDER_TYPE_BINDER; 
                else 
                    fp->type = BINDER_TYPE_WEAK_BINDER; 
                fp->binder = ref->node->ptr; 
                fp->cookie = ref->node->cookie; 
                binder_inc_node(ref->node, fp->type == BINDER_TYPE_BINDER, 0, NULL); 
                binder_debug(BINDER_DEBUG_TRANSACTION, 
                         "        ref %d desc %d -> node %d u%p\n", 
                         ref->debug_id, ref->desc, ref->node->debug_id, 
                         ref->node->ptr); 
            } else { 
                struct binder_ref *new_ref; 
                new_ref = binder_get_ref_for_node(target_proc, ref->node); 
                if (new_ref == NULL) { 
                    return_error = BR_FAILED_REPLY; 
                    goto err_binder_get_ref_for_node_failed; 
                } 
                fp->handle = new_ref->desc; 
                binder_inc_ref(new_ref, fp->type == BINDER_TYPE_HANDLE, NULL); 
                binder_debug(BINDER_DEBUG_TRANSACTION, 
                         "        ref %d desc %d -> ref %d desc %d (node %d)\n", 
                         ref->debug_id, ref->desc, new_ref->debug_id, 
                         new_ref->desc, ref->node->debug_id); 
            } 
        } break; 
        default: 
            binder_user_error("binder: %d:%d got transactio" 
                "n with invalid object type, %lx\n", 
                proc->pid, thread->pid, fp->type); 
            return_error = BR_FAILED_REPLY; 
            goto err_bad_object_type; 
        } 
    } 
    if (reply) { 
        BUG_ON(t->buffer->async_transaction != 0); 
        binder_pop_transaction(target_thread, in_reply_to); 
    } else if (!(t->flags & TF_ONE_WAY)) { 
        BUG_ON(t->buffer->async_transaction != 0); 
        t->need_reply = 1; 
        t->from_parent = thread->transaction_stack;  
        thread->transaction_stack = t; 
    } else { 
        BUG_ON(target_node == NULL); 
        BUG_ON(t->buffer->async_transaction != 1); 
        if (target_node->has_async_transaction) { 
            target_list = &target_node->async_todo; 
            target_wait = NULL; 
        } else 
            target_node->has_async_transaction = 1; 
    } 
    t->work.type = BINDER_WORK_TRANSACTION; 
    list_add_tail(&t->work.entry, target_list);//binder_work添加到SM进程Proc链表中 
    tcomplete->type = BINDER_WORK_TRANSACTION_COMPLETE;//type设置为BINDER_WORK_TRANSACTION_COMPLETE 
    list_add_tail(&tcomplete->entry, &thread->todo);//待完成的工作加入的本线程的todo链表中 
    if (target_wait) 
        wake_up_interruptible(target_wait);//唤醒Service Manager进程 
    return; 
 
...} 
分析这个函数,可以知道和SM通信时,获取target_proc为SM进程的相关信息。然后是维护当前请求的binder实体,以免被crash。以binder_transaction t为C/S之间做为传递的信息,做初始化记录请求进程和服务进程到t中。最后做如下操作:
 t->work.type = BINDER_WORK_TRANSACTION;
 list_add_tail(&t->work.entry, target_list);//binder_work添加到SM进程Proc链表中
 tcomplete->type = BINDER_WORK_TRANSACTION_COMPLETE;//type设置为BINDER_WORK_TRANSACTION_COMPLETE
 list_add_tail(&tcomplete->entry, &thread->todo);//待完成的工作加入的本线程的todo链表中
 if (target_wait)
  wake_up_interruptible(target_wait);//唤醒Service Manager进程
可以看到,将这个t加入到了服务进程SM的链表中,将待完成的tcomplete加入到当前MS的thread中,最后唤醒SM,做相关的处理。
MS继续执行binder_thread_read如下:
[plain] 
static int binder_thread_read(struct binder_proc *proc, 
                  struct binder_thread *thread, 
                  void  __user *buffer, int size, 
                  signed long *consumed, int non_block) 

    void __user *ptr = buffer + *consumed; 
    void __user *end = buffer + size; 
 
    int ret = 0; 
    int wait_for_proc_work; 
 
    if (*consumed == 0) { 
        if (put_user(BR_NOOP, (uint32_t __user *)ptr))//添加BR_NOOP 
            return -EFAULT; 
        ptr += sizeof(uint32_t); 
    } 
 
retry: 
    wait_for_proc_work = thread->transaction_stack == NULL && 
                list_empty(&thread->todo);// false 
 
    if (thread->return_error != BR_OK && ptr < end) { 
        if (thread->return_error2 != BR_OK) { 
            if (put_user(thread->return_error2, (uint32_t __user *)ptr)) 
                return -EFAULT; 
            ptr += sizeof(uint32_t); 
            if (ptr == end) 
                goto done; 
            thread->return_error2 = BR_OK; 
        } 
        if (put_user(thread->return_error, (uint32_t __user *)ptr)) 
            return -EFAULT; 
        ptr += sizeof(uint32_t); 
        thread->return_error = BR_OK; 
        goto done; 
    } 
 
 
    thread->looper |= BINDER_LOOPER_STATE_WAITING; 
    if (wait_for_proc_work) 
        proc->ready_threads++; 
    mutex_unlock(&binder_lock); 
    if (wait_for_proc_work) { 
        if (!(thread->looper & (BINDER_LOOPER_STATE_REGISTERED | 
                    BINDER_LOOPER_STATE_ENTERED))) { 
            binder_user_error("binder: %d:%d ERROR: Thread waiting " 
                "for process work before calling BC_REGISTER_" 
                "LOOPER or BC_ENTER_LOOPER (state %x)\n", 
                proc->pid, thread->pid, thread->looper); 
            wait_event_interruptible(binder_user_error_wait, 
                         binder_stop_on_user_error < 2); 
        } 
        binder_set_nice(proc->default_priority); 
        if (non_block) { 
            if (!binder_has_proc_work(proc, thread)) 
                ret = -EAGAIN; 
        } else 
            ret = wait_event_interruptible_exclusive(proc->wait, binder_has_proc_work(proc, thread));//binder_has_proc_work为false唤醒 
    } else { 
        if (non_block) { 
            if (!binder_has_thread_work(thread)) 
                ret = -EAGAIN; 
        } else 
            ret = wait_event_interruptible(thread->wait, binder_has_thread_work(thread)); 
    } 
    mutex_lock(&binder_lock); 
    if (wait_for_proc_work) 
        proc->ready_threads--; 
    thread->looper &= ~BINDER_LOOPER_STATE_WAITING; 
 
    if (ret) 
        return ret; 
 
    while (1) { 
        uint32_t cmd; 
        struct binder_transaction_data tr; 
        struct binder_work *w; 
        struct binder_transaction *t = NULL; 
 
        if (!list_empty(&thread->todo)) 
            w = list_first_entry(&thread->todo, struct binder_work, entry); 
        else if (!list_empty(&proc->todo) && wait_for_proc_work)//在SM被唤醒时proc->todo为1且wait_for_proc_work等待进程有事情做 
            w = list_first_entry(&proc->todo, struct binder_work, entry);//获取binder_work 
        else { 
            if (ptr - buffer == 4 && !(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN)) /* no data added */ 
                goto retry; 
            break; 
        } 
 
        if (end - ptr < sizeof(tr) + 4) 
            break; 
 
        switch (w->type) { 
        case BINDER_WORK_TRANSACTION: {//SM唤醒时带调用 
            t = container_of(w, struct binder_transaction, work);//通过binder_transaction的指针变量work为w,获取binder_transaction 
        } break; 
        case BINDER_WORK_TRANSACTION_COMPLETE: {  
            cmd = BR_TRANSACTION_COMPLETE; 
            if (put_user(cmd, (uint32_t __user *)ptr))  //BR_TRANSACTION_COMPLETE命令写回 
                return -EFAULT; 
            ptr += sizeof(uint32_t); 
 
            binder_stat_br(proc, thread, cmd); 
            binder_debug(BINDER_DEBUG_TRANSACTION_COMPLETE, 
                     "binder: %d:%d BR_TRANSACTION_COMPLETE\n", 
                     proc->pid, thread->pid); 
 
            list_del(&w->entry);//从thread->todo删除链表 
            kfree(w); 
            binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE); 
        } break; 
写会BR_NOOP和BR_TRANSACTION_COMPLETE给用户空间,相当于从内核读取了数据,同时也做list_del(&w->entry)的处理。
MS继续与binder交互,进入ret = wait_event_interruptible(thread->wait, binder_has_thread_work(thread));进入睡眠等待SM的唤醒。
 
SM在被MS唤醒后所做的处理如下:
SM同样在binder_thread_read时处于ret = wait_event_interruptible(thread->wait, binder_has_thread_work(thread));的睡眠当中,但是此时proc->todo已经有内容,在前面的MS write的过程进行了(list_add_tail(&t->work.entry, target_list);//binder_work添加到SM进程Proc链表中)操作,所以会执行:
 w = list_first_entry(&proc->todo, struct binder_work, entry);//获取binder_work
 t = container_of(w, struct binder_transaction, work);//通过binder_transaction的指针变量work为w,获取binder_transaction
最后获取binder_transaction t 用于SM和MS用来交互和中转信息。
有了从MS传递过来的t,将t的相关信息读取回SM的用户空间,传递给SM的命令为cmd=BR_TRANSACTION。
MS再次传递cmd=BC_REPLY,再次回到binder_thread_write
[plain]
{  //reply=1,sevice回复给client 
        in_reply_to = thread->transaction_stack;//获取当前事务性即原来MS传递给SM的binder_transaction变量t 
        if (in_reply_to == NULL) { 
            binder_user_error("binder: %d:%d got reply transaction " 
                      "with no transaction stack\n", 
                      proc->pid, thread->pid); 
            return_error = BR_FAILED_REPLY; 
            goto err_empty_call_stack; 
        } 
        binder_set_nice(in_reply_to->saved_priority); 
        if (in_reply_to->to_thread != thread) { 
            binder_user_error("binder: %d:%d got reply transaction " 
                "with bad transaction stack," 
                " transaction %d has target %d:%d\n", 
                proc->pid, thread->pid, in_reply_to->debug_id, 
                in_reply_to->to_proc ? 
                in_reply_to->to_proc->pid : 0, 
                in_reply_to->to_thread ? 
                in_reply_to->to_thread->pid : 0); 
            return_error = BR_FAILED_REPLY; 
            in_reply_to = NULL; 
            goto err_bad_call_stack; 
        } 
        thread->transaction_stack = in_reply_to->to_parent; 
        target_thread = in_reply_to->from;//获取请求的线程 
        if (target_thread == NULL) { 
            return_error = BR_DEAD_REPLY; 
            goto err_dead_binder; 
        } 
        if (target_thread->transaction_stack != in_reply_to) { 
            binder_user_error("binder: %d:%d got reply transaction " 
                "with bad target transaction stack %d, " 
                "expected %d\n", 
                proc->pid, thread->pid, 
                target_thread->transaction_stack ? 
                target_thread->transaction_stack->debug_id : 0, 
                in_reply_to->debug_id); 
            return_error = BR_FAILED_REPLY; 
            in_reply_to = NULL; 
            target_thread = NULL; 
            goto err_dead_binder; 
        } 
        target_proc = target_thread->proc;//请教进程的相关信息 
    } 
前期MS在执行时,将MS自己的thread信息记录在了t当中。
[plain]
if (!reply && !(tr->flags & TF_ONE_WAY)) 
    t->from = thread;//事务性记录from binder进程,即记录下请求进程 
因此SM在执行binder_thread_write时,会获取到请求进程的thread,最终和前面MS唤醒SM一样,唤醒SM,只是现在的目标进程target_proc换成了MS的内容。
最终SM回互用户空间BR_TRANSACTION_COMPLETE,SM随后再次进行LOOP循环,睡眠等待其他请求进程的唤醒。
MS被唤醒后,所做的处理和SM被唤醒时相类似,在这里写会的cmd=BR_REPLY,以此完成了一次SM和MS的IPC.
 
2.3 binder 驱动C++层的机制简单介绍
可以简单的理解Binder IPC 实际就是C/S通过Linux的机制,对各自线程的信息进行维护,使SM和MS的用户空间不断和内核空间以ioctl进行读写的交互。服务端对信息进行解析完成相应的操作。客户度实际只需发送命令即可。作为应用程序的开发,Android很好的为我们做了各种封装,包括C++层次的binder和Java层次的binder驱动。
核心类:BpBinder(远程BinderProxy),BBinder(Native 本地Binder)
基于Binder C++层的机制,以SM和MS为例,在MS如果要和SM通信,就需要获得SM在MS进程中的一个Proxy,这里称之为BpServiceManager,BpServiceManager的操作函数分为addservice和getservice,需要的参量为一个Bpbinder(在这里就是SM远程的binder对象,相当于一个句柄,由于其特殊性,句柄数值为0)。
在2.2中分析的binder底层部分内容,就是基于用户空间的addservice开始的。在这里引用罗老师的UML图,方便自己的理解。
Android之binder驱动个人学习小结_第1张图片

在这里只对BpServiceManager的addservice做解析,该类最终的实现其实还是调用BpBinder的transact来完成,而该函数的实现最终调用的是IPCThreadState的transact,在该transact代码如下:
[plain]
status_t IPCThreadState::transact(int32_t handle, 
                                  uint32_t code, const Parcel& data, 
                                  Parcel* reply, uint32_t flags)  //handle=0,flags=0 

    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);//将要发送的数据整理成一个binder_transaction_data 
    } 
     
    if (err != NO_ERROR) { 
        if (reply) reply->setError(err); 
        return (mLastError = err); 
    } 
     
    if ((flags & TF_ONE_WAY) == 0) { 
        #if 0 
        if (code == 4) { // relayout 
            LOGI(">>>>>> CALLING transaction 4"); 
        } else { 
            LOGI(">>>>>> CALLING transaction %d", code); 
        } 
        #endif 
        if (reply) { 
            err = waitForResponse(reply); 
        } else { 
            Parcel fakeReply; 
            err = waitForResponse(&fakeReply); 
        } 
        #if 0 
        if (code == 4) { // relayout 
            LOGI("<<<<<< RETURNING transaction 4"); 
        } else { 
            LOGI("<<<<<< 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; 

在这里真正实现ioctl的内容在waitForResponse的talkWithDriver中实现。
SM作为Android系统中特殊的一部分,他即可用当做服务端,也管理着系统的所有Service。新的服务需要向他完成注册才可以正常的使用。因此在这里的addservice就是在远程通过Binder驱动和SM交互,完成了MS的注册,注册传入的是一个BBinder的实体BnMediaPlayService,name=MediaPlay。
在C++的binder机制中,Bpxxx对应的Bnxxx(Bpxxx继承自BpBinder,Bnxxx继承自BBinder),简单理解就是Bnxxx在向SM完成注册后,会自动启动一个线程来等待客户端的请求,而在客户端如果要请求服务,需要获取一个Bpxxx远程代理来完成。Bpxxx在getservice时还回xxx服务的binder句柄,存放在Bpxxx对应的BpBinder的mHandle中。在binder驱动的底层会根据这个mHandle,查找到对应的target服务进程,同理根据2.2中MS唤醒SM的过程,进行命令的处理。
因此总结出在客户端需要服务时,首先获得Bpxxx(new BpBinder(mHandle))。然后是最终调用BpBinder的remote()->transact。而在用户端以BBinder->ontransact完成命令的解析。
 
2.4 Binder驱动的Java机制
简单的说一下Java层的binder驱动,其实这部分的难点还是在于Java 中Native函数在JNI的转换,感谢Google的开发人员,实现了Java和C++层的Binder函数的转换。
简单的总结3个小点:
1.Java层拥有一个SM的远程接口SMProxy,句柄为0 的BinderProxy对象,BinderProxy相当于BpBinder,在JNI实现转换。
2,Ixxx接口定义一个stub和proxy,Stub(存根):理解为本地服务。proxy:远程的代理。与C++相对应的前者就是Bnxxx,后者就是Bpxxx。www.2cto.com
3. xxx需要继承了Ixxx的Stub,才可以完成请求的处理。
 
2.5 总结
上面的内容,基本是自己的阅读和学习的感受,Binder驱动的复杂程度是难以想象的,源码量大。写完本文也没有全部读通,但是这也为深入的去了解整个android系统开辟了基础。其中有些内容都是参考罗老师的Android之旅来完成的,在这里表示感谢。在接下去的一端时间将在Android4.0.3 ICS上学习Android系统整个系统过程,主要关心的是3个开机画面,继续给力,最近身体不是很舒服,对着电脑头老是晕,效率下降了很多,但是依旧在继续努力,给自己加油。
 

你可能感兴趣的:(thread,android,struct,user,null,buffer)