深入内核讲明白Android Binder【三】

Android binder的kernel实现 至少在五六年前就听说过binder机制,但从未想去深入了解。这次忘了是怎么和同事聊起这个东西的不过作为一个码农我想如果连google OS最为精髓的IPC都不知道,真不好以后出去跟人打招呼,于是乎决心了解下,一开始网上搜了些资料,感觉基本上都没讲出些啥东西,没办法只好 read the fucking code, 上周一直忙着签证的事情,没怎么定下心看因而节假日放出大招。 保留一贯的风格不喜欢整篇 阅读详情

深入内核讲明白Android Binder【三】

前言

深入内核讲明白Android Binder【一】实现了Binder跨进程通信的客户端和服务端的C语言Demo,并对服务端向service_manager注册服务,客户端向service_manager获取服务的源码进行了详细分析,但分析仅止步于用户态,深入内核讲明白Android Binder【二】,详细分析了服务注册过程Binder驱动内核源码,本篇文章继续分析服务获取过程及使用过程的Binder驱动内核源码。相信有了对上一篇文章的基础,这篇文章读起来应该轻松很多,那么我们就开始吧~

一、服务的获取过程内核源码解析

1. 客户端获取服务的用户态源码回顾

深入内核讲明白Android Binder【一】详细分析了客户端获取服务的用户态源码,这里简单回顾一下客户端通过svcmgr_lookup函数获取服务的用户态源码。

int main(int argc, char **argv)
{
    int fd;
    struct binder_state *bs;
    uint32_t svcmgr = BINDER_SERVICE_MANAGER;
    uint32_t handle;
	int ret;

	if (argc < 2){
        fprintf(stderr, "Usage:\n");
        fprintf(stderr, "%s <hello|goodbye>\n", argv[0]);
        fprintf(stderr, "%s <hello|goodbye> <name>\n", argv[0]);
        return -1;
	}
    
    //打开驱动
    bs = binder_open(128*1024);
    if (!bs) {
        fprintf(stderr, "failed to open binder driver\n");
        return -1;
    }
	g_bs = bs;
    
    //向service_manager发送数据,获得hello服务句柄
	handle = svcmgr_lookup(bs, svcmgr, "hello");
	if (!handle) {
        fprintf(stderr, "failed to get hello service\n");
        return -1;
	}
	g_hello_handle = handle;
	fprintf(stderr, "Handle for hello service = %d\n", g_hello_handle);

	/* 向服务端发送数据 */
	if (!strcmp(argv[1], "hello"))
	{
		if (argc == 2) {
			sayhello();
		} else if (argc == 3) {
			ret = sayhello_to(argv[2]);
	        fprintf(stderr, "get ret of sayhello_to = %d\n", ret);		
		}
	}

	binder_release(bs, handle);

    return 0;
}


uint32_t svcmgr_lookup(struct binder_state *bs, uint32_t target, const char *name)
{
    uint32_t handle;
    unsigned iodata[512/4];
    struct binder_io msg, reply;

    bio_init(&msg, iodata, sizeof(iodata), 4); // 为msg划分iodata的空间
    bio_put_uint32(&msg, 0);  // strict mode header
    bio_put_string16_x(&msg, SVC_MGR_NAME); // 写入android.os.IServiceManager
    bio_put_string16_x(&msg, name); // 写入服务名 hello

    // target = 0,代表service_manager,SVC_MGR_CHECK_SERVICE代表需要调用service_manager的查找服务的函数
    if (binder_call(bs, &msg, &reply, target, SVC_MGR_CHECK_SERVICE))
        return 0;

    // 获取hello服务的句柄
    handle = bio_get_ref(&reply);

    if (handle)
        binder_acquire(bs, handle);

    binder_done(bs, &msg, &reply);

    return handle;
}

int binder_call(struct binder_state *bs,
                struct binder_io *msg, struct binder_io *reply,
                uint32_t target, uint32_t code)
{
    int res;
    struct binder_write_read bwr;
    struct {
        uint32_t cmd;
        struct binder_transaction_data txn;
    } __attribute__((packed)) writebuf;
    unsigned readbuf[32];

    if (msg->flags & BIO_F_OVERFLOW) {
        fprintf(stderr,"binder: txn buffer overflow\n");
        goto fail;
    }
    // 构造binder_transaction_data
    writebuf.cmd = BC_TRANSACTION;//ioclt类型
    writebuf.txn.target.handle = target;//数据发送给哪个进程
    writebuf.txn.code = code;//调用进程的哪个函数
    writebuf.txn.flags = 0;
    writebuf.txn.data_size = msg->data - msg->data0;//数据本身大小
    writebuf.txn.offsets_size = ((char*) msg->offs) - ((char*) msg->offs0);//数据头大小,指向binder_node实体(发送端提供服务函数的地址),bio_put_obj(&msg, ptr);
    writebuf.txn.data.ptr.buffer = (uintptr_t)msg->data0;//指向数据本身内存起点
    writebuf.txn.data.ptr.offsets = (uintptr_t)msg->offs0;//指向数据头内存起点
   
    // 构造binder_write_read
    bwr.write_size = sizeof(writebuf);
    bwr.write_consumed = 0;
    bwr.write_buffer = (uintptr_t) &writebuf;

    hexdump(msg->data0, msg->data - msg->data0);
    for (;;) {
        bwr.read_size = sizeof(readbuf);
        bwr.read_consumed = 0;
        bwr.read_buffer = (uintptr_t) readbuf;

        res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);//调用ioctl发送数据给驱动程序

        if (res < 0) {
            fprintf(stderr,"binder: ioctl failed (%s)\n", strerror(errno));
            goto fail;
        }
        // 解析数据,将readbuf中的数据解析给reply
        res = binder_parse(bs, reply, (uintptr_t) readbuf, bwr.read_consumed, 0);
        if (res == 0) return 0;
        if (res < 0) goto fail;
    }

fail:
    memset(reply, 0, sizeof(*reply));
    reply->flags |= BIO_F_IOERROR;
    return -1;
}

可以看到svcmgr_lookup函数也是组织好binder_io数据,然后调用binder_call函数,把binder_io数据封装为binder_write_read数据,最后通过ioctl发送给service_manager。

这个过程和深入内核讲明白Android Binder【二】中分析的服务端向service_manager注册服务的过程类似,都是组织数据,然后通过ioctl把数据发给service_manager。

那么下面我们就进入linux内核源码,分析数据发给service_manager后,到底干了什么。

2. 客户端获取服务的内核源码分析

服务端调用ioctl,对应会调用到内核Binder驱动程序中的binder_ioctl函数,点击查看源码

2.1 客户端向service_manager发送数据

1. binder_ioctl
// 客户端调用ioctl发送数据给驱动程序
res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);

// 对应Binder内核驱动程序调用binder_ioctl函数处理数据
static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
	int ret;
	// 获取服务的binder_proc,它是在服务打开binder驱动的时候创建的,后面我们会分析
	struct binder_proc *proc = filp->private_data;
	struct binder_thread *thread;
	void __user *ubuf = (void __user *)arg;

	/*pr_info("binder_ioctl: %d:%d %x %lx\n",
			proc->pid, current->pid, cmd, arg);*/

	binder_selftest_alloc(&proc->alloc);

	trace_binder_ioctl(cmd, arg);

	ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);
	if (ret)
		goto err_unlocked;

	//为服务进程proc创建binder_thread
	thread = binder_get_thread(proc);
	if (thread == NULL) {
		ret = -ENOMEM;
		goto err;
	}
    
    // 从上面的分析可知此时cmd=BINDER_WRITE_READ
	switch (cmd) {
	case BINDER_WRITE_READ:
	    // 处理服客户端数据
		ret = binder_ioctl_write_read(filp, arg, thread);
		if (ret)
			goto err;
		break;
		
	......
}
2. binder_ioctl_write_read
static int binder_ioctl_write_read(struct file *filp, unsigned long arg,
                                struct binder_thread *thread)
{
        int ret = 0;
        struct binder_proc *proc = filp->private_data;
        void __user *ubuf = (void __user *)arg; // 用户空间的数据
        // 从用户空间获取客户端发送的数据binder_write_read
        struct binder_write_read bwr;

        //从用户空间发送的数据头拷贝到内核空间(这部分内核空间被mmap映射到了目标进程)
        if (copy_from_user(&bwr, ubuf, sizeof(bwr))) {
                ret = -EFAULT;
                goto out;
        }
        binder_debug(BINDER_DEBUG_READ_WRITE,
                     "%d:%d write %lld at %016llx, read %lld at %016llx\n",
                     proc->pid, thread->pid,
                     (u64)bwr.write_size, (u64)bwr.write_buffer,
                     (u64)bwr.read_size, (u64)bwr.read_buffer);
        
        // 上面已经分析过客户端发送的数据保存在binder_write_read,此时它的write_size是大于0的
        if (bwr.write_size > 0) { // 向驱动程序写数据
                ret = binder_thread_write(proc, thread,
                                          bwr.write_buffer,
                                          bwr.write_size,
                                          &bwr.write_consumed);
                trace_binder_write_done(ret);
                if (ret < 0) {
                        bwr.read_consumed = 0;
                        if (copy_to_user(ubuf, &bwr, sizeof(bwr)))
                                ret = -EFAULT;
                        goto out;
                }
        }
        if (bwr.read_size > 0) { // 从驱动程序读数据
                ret = binder_thread_read(proc, thread, bwr.read_buffer,
                                         bwr.read_size,
                                         &bwr.read_consumed,
                                         filp->f_flags & O_NONBLOCK);
                trace_binder_read_done(ret);
                binder_inner_proc_lock(proc);
                if (!binder_worklist_empty_ilocked(&proc->todo))
                        binder_wakeup_proc_ilocked(proc);
                binder_inner_proc_unlock(proc);
                if (ret < 0) {
                        if (copy_to_user(ubuf, &bwr, sizeof(bwr)))
                                ret = -EFAULT;
                        goto out;
                }
        }
        binder_debug(BINDER_DEBUG_READ_WRITE,
                     "%d:%d wrote %lld of %lld, read return %lld of %lld\n",
                     proc->pid, thread->pid,
                     (u64)bwr.write_consumed, (u64)bwr.write_size,
                     (u64)bwr.read_consumed, (u64)bwr.read_size);
        // 复制数据给到用户空间
        if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {
                ret = -EFAULT;
                goto out;
        }
out:
        return ret;
}

static inline int copy_from_user(void *to, const void __user volatile *from,
				 unsigned long n)
{
	volatile_memcpy(to, from, n);
	return 0;
}

static inline int copy_to_user(void __user volatile *to, const void *from,
			       unsigned long n)
{
	volatile_memcpy(to, from, n);
	return 0;
}

3. binder_thread_write

此时cmd是BC_TRANSACTION

static int binder_thread_write(struct binder_proc *proc,
                        struct binder_thread *thread,
                        binder_uintptr_t binder_buffer, size_t size,
                        binder_size_t *consumed)
{
        uint32_t cmd;
        struct binder_context *context = proc->context;
        // 获取数据buffer,根据上面总结的发送数据可知,这个buffer由cmd和binder_transcation_data两部分数据组成
        void __user *buffer = (void __user *)(uintptr_t)binder_buffer;
        // 发送来的数据consumed=0,因此ptr指向用户空间数据buffer的起点
        void __user *ptr = buffer + *consumed;
        // 指向数据buffer的末尾
        void __user *end = buffer + size;
        // 逐个读取客户端发送来的数据(cmd+binder_transcation_data)
        while (ptr < end && thread->return_error.cmd == BR_OK) {
                int ret;
                
                // 获取用户空间中buffer的cmd值
                if (get_user(cmd, (uint32_t __user *)ptr))
                        return -EFAULT;
                // 移动指针到cmd的位置之后,指向binder_transcation_data数据的内存起点
                ptr += sizeof(uint32_t);
                trace_binder_command(cmd);
                if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.bc)) {
                        atomic_inc(&binder_stats.bc[_IOC_NR(cmd)]);
                        atomic_inc(&proc->stats.bc[_IOC_NR(cmd)]);
                        atomic_inc(&thread->stats.bc[_IOC_NR(cmd)]);
                }
                // 根据上面总结的发送数据可知,cmd是BC_TRANSACTION
                switch (cmd) {
                   ......
                   /*
                BC_TRANSACTION:进程发送信息的cmd
                BR_TRANSACTION:进程接收BC_TRANSACTION发送信息的cmd
                
                BC_REPLY:进程回复信息的cmd
                BR_REPLY:进程接收BC_REPLY回复信息的cmd
                */
                    case BC_TRANSACTION:
                    case BC_REPLY: {
                            struct binder_transaction_data tr;
                            
                            // 从用户空间拷贝binder_transaction_data到内核空间
                            if (copy_from_user(&tr, ptr, sizeof(tr)))
                                    return -EFAULT;
                            // 移动指针到binder_transaction_data的位置之后,指向下一个cmd数据的内存起点
                            ptr += sizeof(tr);
                            // 处理binder_transaction_data数据
                            binder_transaction(proc, thread, &tr,
                                               cmd == BC_REPLY, 0);
                            break;
                    }
                }
        }
        ......
}

int get_user(int *val, const int __user *ptr) {
    if (copy_from_user(val, ptr, sizeof(int))) {
        return -EFAULT; // 返回错误码
    }
    return 0; // 成功
}

4. binder_transaction
4.1 找到目的进程service_manager
static void binder_transaction(struct binder_proc *proc,
                               struct binder_thread *thread,
                               struct binder_transaction_data *tr, int reply,
                               binder_size_t extra_buffers_size)
{
        ......
        // 此时是客户端向内核发送数据,reply为false
        if (reply) { // Binder内核驱动程序向用户空间回复数据的处理逻辑
                ......
        } else { // 用户空间数据发送给内核空间的处理逻辑
                //1. 找到目的进程,本次分析的是向service_manager获取服务,因此目的进程就是tr->target.handle=0的service_manager
                if (tr->target.handle) { // tr->target.handle == 0 代表是service_manager进程,否则是其它进程
                        .......
                } else { //处理service_manager进程
                        mutex_lock(&context->context_mgr_node_lock);
                        //这个node是在创建service_manager时通过BINDER_SET_CONTEXT_MGR的cmd创建的
                        target_node = context->binder_context_mgr_node; 
                        if (target_node)
                                target_node = binder_get_node_refs_for_txn(
                                                target_node, &target_proc,
                                                &return_error);
                        else
                                return_error = BR_DEAD_REPLY;
                        mutex_unlock(&context->context_mgr_node_lock);
                        if (target_node && target_proc->pid == proc->pid) {
                                binder_user_error("%d:%d got transaction to context manager from process owning it\n",
                                                  proc->pid, thread->pid);
                                return_error = BR_FAILED_REPLY;
                                return_error_param = -EINVAL;
                                return_error_line = __LINE__;
                                goto err_invalid_target_handle;
                        }
                }
                ......
        }
 }
4.2 拷贝客户端binder_transaction_data数据中的data.ptr.offsets到service_manager的mmap内核空间
static void binder_transaction(struct binder_proc *proc,
                               struct binder_thread *thread,
                               struct binder_transaction_data *tr, int reply,
                               binder_size_t extra_buffers_size)
{
        int ret;
        struct binder_transaction *t;
        struct binder_work *w;
        struct binder_work *tcomplete;
        binder_size_t buffer_offset = 0;
        binder_size_t off_start_offset, off_end_offset;
        binder_size_t off_min;
        binder_size_t sg_buf_offset, sg_buf_end_offset;
        binder_size_t user_offset = 0;
        struct binder_proc *target_proc = NULL;
        struct binder_thread *target_thread = NULL;
        struct binder_node *target_node = NULL;
        struct binder_transaction *in_reply_to = NULL;
        struct binder_transaction_log_entry *e;
        uint32_t return_error = 0;
        uint32_t return_error_param = 0;
        uint32_t return_error_line = 0;
        binder_size_t last_fixup_obj_off = 0;
        binder_size_t last_fixup_min_off = 0;
        struct binder_context *context = proc->context;
        int t_debug_id = atomic_inc_return(&binder_last_id);
        ktime_t t_start_time = ktime_get();
        char *secctx = NULL;
        u32 secctx_sz = 0;
        struct list_head sgc_head;
        struct list_head pf_head;
        const void __user *user_buffer = (const void __user *)
                                (uintptr_t)tr->data.ptr.buffer;
        INIT_LIST_HEAD(&sgc_head);
        INIT_LIST_HEAD(&pf_head);

        e = binder_transaction_log_add(&binder_transaction_log);
        e->debug_id = t_debug_id;
        e->call_type = reply ? 2 : !!(tr->flags & TF_ONE_WAY);
        e->from_proc = proc->pid;
        e->from_thread = thread->pid;
        e->target_handle = tr->target.handle;
        e->data_size = tr->data_size;
        e->offsets_size = tr->offsets_size;
        strscpy(e->context_name, proc->context->name, BINDERFS_MAX_NAME);

        binder_inner_proc_lock(proc);
        binder_set_extended_error(&thread->ee, t_debug_id, BR_OK, 0);
        binder_inner_proc_unlock(proc);

        if (reply) {// 找到要回复的进程
                ......
        } else {// 1. 找到要发送的目的进程
                if (tr->target.handle) { // 目的进程非service_manager进程
                       .....
                } else { //目的进程是service_manager进程
                        // 找到service_manager的binder_node节点
                        .....
                }
                ......
        }
        if (target_thread)
                e->to_thread = target_thread->pid;
        e->to_proc = target_proc->pid;

        /* TODO: reuse incoming transaction for reply */
        // 为binder_transcation分配内存
        t = kzalloc(sizeof(*t), GFP_KERNEL);
        
        .....

        if (!reply && !(tr->flags & TF_ONE_WAY))
                t->from = thread;
        else
                t->from = NULL;
        // 存储发送双方的基本信息
        t->from_pid = proc->pid;
        t->from_tid = thread->pid;
        t->sender_euid = task_euid(proc->tsk);
        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_new_buf(&target_proc->alloc, tr->data_size,
                tr->offsets_size, extra_buffers_size,
                !reply && (t->flags & TF_ONE_WAY));
        ......
        
        t->buffer->debug_id = t->debug_id;
        t->buffer->transaction = t;
        t->buffer->target_node = target_node;
        t->buffer->clear_on_free = !!(t->flags & TF_CLEAR_BUF);
        trace_binder_transaction_alloc_buf(t->buffer);
        
        // 把客户端的数据拷贝到目的进程service_manager mmap的内存空间,即t->buffer指向的内存空间
        if (binder_alloc_copy_user_to_buffer(
                                &target_proc->alloc,
                                t->buffer,
                                ALIGN(tr->data_size, sizeof(void *)),
                                (const void __user *)
                                        (uintptr_t)tr->data.ptr.offsets,
                                tr->offsets_size)) {
                binder_user_error("%d:%d got transaction with invalid offsets ptr\n",
                                proc->pid, thread->pid);
                return_error = BR_FAILED_REPLY;
                return_error_param = -EFAULT;
                return_error_line = __LINE__;
                goto err_copy_data_failed;
        }
        ......
}

/**
 * binder_alloc_copy_user_to_buffer() - copy src user to tgt user
 * @alloc: binder_alloc for this proc
 * @buffer: binder buffer to be accessed
 * @buffer_offset: offset into @buffer data
 * @from: userspace pointer to source buffer
 * @bytes: bytes to copy
 *
 * Copy bytes from source userspace to target buffer.
 *
 * Return: bytes remaining to be copied
 */
unsigned long
binder_alloc_copy_user_to_buffer(struct binder_alloc *alloc,
				 struct binder_buffer *buffer,
				 binder_size_t buffer_offset,
				 const void __user *from,
				 size_t bytes)
{
	if (!check_buffer(alloc, buffer, buffer_offset, bytes))
		return bytes;

	while (bytes) {
		unsigned long size;
		unsigned long ret;
		struct page *page;
		pgoff_t pgoff;
		void *kptr;

		page = binder_alloc_get_page(alloc, buffer,
					     buffer_offset, &pgoff);
		size = min_t(size_t, bytes, PAGE_SIZE - pgoff);
		kptr = kmap_local_page(page) + pgoff;
		// 拷贝服务端数据到service_manager mmap的内核内存空间
		ret = copy_from_user(kptr, from, size);
		kunmap_local(kptr);
		if (ret)
			return bytes - size + ret;
		bytes -= size;
		from += size;
		buffer_offset += size;
	}
	return 0;
}
4.3 拷贝客户端binder_transaction_data数据中的data.ptr.buffer到service_manager的mmap内核空间
static void binder_transaction(struct binder_proc *proc,
                               struct binder_thread *thread,
                               struct binder_transaction_data *tr, int reply,
                               binder_size_t extra_buffers_size)
{
        int ret;
        struct binder_transaction *t;
        struct binder_work *w;
        struct binder_work *tcomplete;
        binder_size_t buffer_offset = 0;
        binder_size_t off_start_offset, off_end_offset;
        binder_size_t off_min;
        binder_size_t sg_buf_offset, sg_buf_end_offset;
        binder_size_t user_offset = 0;
        struct binder_proc *target_proc = NULL;
        struct binder_thread *target_thread = NULL;
        struct binder_node *target_node = NULL;
        struct binder_transaction *in_reply_to = NULL;
        struct binder_transaction_log_entry *e;
        uint32_t return_error = 0;
        uint32_t return_error_param = 0;
        uint32_t return_error_line = 0;
        binder_size_t last_fixup_obj_off = 0;
        binder_size_t last_fixup_min_off = 0;
        struct binder_context *context = proc->context;
        int t_debug_id = atomic_inc_return(&binder_last_id);
        ktime_t t_start_time = ktime_get();
        char *secctx = NULL;
        u32 secctx_sz = 0;
        struct list_head sgc_head;
        struct list_head pf_head;
        const void __user *user_buffer = (const void __user *)
                                (uintptr_t)tr->data.ptr.buffer;
        INIT_LIST_HEAD(&sgc_head);
        INIT_LIST_HEAD(&pf_head);

        e = binder_transaction_log_add(&binder_transaction_log);
        e->debug_id = t_debug_id;
        e->call_type = reply ? 2 : !!(tr->flags & TF_ONE_WAY);
        e->from_proc = proc->pid;
        e->from_thread = thread->pid;
        e->target_handle = tr->target.handle;
        e->data_size = tr->data_size;
        e->offsets_size = tr->offsets_size;
        strscpy(e->context_name, proc->context->name, BINDERFS_MAX_NAME);

        binder_inner_proc_lock(proc);
        binder_set_extended_error(&thread->ee, t_debug_id, BR_OK, 0);
        binder_inner_proc_unlock(proc);

        if (reply) {// 找到要回复的进程
                ......
        } else {// 1. 找到要发送的目的进程
                if (tr->target.handle) { // 目的进程非service_manager进程
                       .....
                } else { //目的进程是service_manager进程
                        // 找到service_manager的binder_node节点
                        .....
                }
                ......
        }
        if (target_thread)
                e->to_thread = target_thread->pid;
        e->to_proc = target_proc->pid;

        /* TODO: reuse incoming transaction for reply */
        // 为binder_transcation分配内存
        t = kzalloc(sizeof(*t), GFP_KERNEL);
        
        .....

        if (!reply && !(tr->flags & TF_ONE_WAY))
                t->from = thread;
        else
                t->from = NULL;
        // 存储发送双方的基本信息
        t->from_pid = proc->pid;
        t->from_tid = thread->pid;
        t->sender_euid = task_euid(proc->tsk);
        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_new_buf(&target_proc->alloc, tr->data_size,
                tr->offsets_size, extra_buffers_size,
                !reply && (t->flags & TF_ONE_WAY));
        ......
        
        t->buffer->debug_id = t->debug_id;
        t->buffer->transaction = t;
        t->buffer->target_node = target_node;
        t->buffer->clear_on_free = !!(t->flags & TF_CLEAR_BUF);
        trace_binder_transaction_alloc_buf(t->buffer);
        
        // 把客户端的数据拷贝到目的进程service_manager mmap的内存空间,即t->buffer指向的内存空间
        if (binder_alloc_copy_user_to_buffer(
                                &target_proc->alloc,
                                t->buffer,
                                ALIGN(tr->data_size, sizeof(void *)),
                                (const void __user *)
                                        (uintptr_t)tr->data.ptr.offsets,
                                tr->offsets_size)) {
                binder_user_error("%d:%d got transaction with invalid offsets ptr\n",
                                proc->pid, thread->pid);
                return_error = BR_FAILED_REPLY;
                return_error_param = -EFAULT;
                return_error_line = __LINE__;
                goto err_copy_data_failed;
        }
        
        ......

		/* Done processing objects, copy the rest of the buffer */
		if (binder_alloc_copy_user_to_buffer(
					&target_proc->alloc,
					t->buffer, user_offset,
					user_buffer + user_offset,
					tr->data_size - user_offset)) {
			binder_user_error("%d:%d got transaction with invalid data ptr\n",
					proc->pid, thread->pid);
			return_error = BR_FAILED_REPLY;
			return_error_param = -EFAULT;
			return_error_line = __LINE__;
			goto err_copy_data_failed;
		}
		
		......
}
4.4 把待处理的数据放到目的进程service_manager的binder_proc或binder_thread的todo链表
static void binder_transaction(struct binder_proc *proc,
                               struct binder_thread *thread,
                               struct binder_transaction_data *tr, int reply,
                               binder_size_t extra_buffers_size)
{
        int ret;
        struct binder_transaction *t;
        struct binder_work *w;
        struct binder_work *tcomplete;
        binder_size_t buffer_offset = 0;
        binder_size_t off_start_offset, off_end_offset;
        binder_size_t off_min;
        binder_size_t sg_buf_offset, sg_buf_end_offset;
        binder_size_t user_offset = 0;
        struct binder_proc *target_proc = NULL;
        struct binder_thread *target_thread = NULL;
        struct binder_node *target_node = NULL;
        struct binder_transaction *in_reply_to = NULL;
        struct binder_transaction_log_entry *e;
        uint32_t return_error = 0;
        uint32_t return_error_param = 0;
        uint32_t return_error_line = 0;
        binder_size_t last_fixup_obj_off = 0;
        binder_size_t last_fixup_min_off = 0;
        struct binder_context *context = proc->context;
        int t_debug_id = atomic_inc_return(&binder_last_id);
        ktime_t t_start_time = ktime_get();
        char *secctx = NULL;
        u32 secctx_sz = 0;
        struct list_head sgc_head;
        struct list_head pf_head;
        const void __user *user_buffer = (const void __user *)
                                (uintptr_t)tr->data.ptr.buffer;
        INIT_LIST_HEAD(&sgc_head);
        INIT_LIST_HEAD(&pf_head);

        e = binder_transaction_log_add(&binder_transaction_log);
        e->debug_id = t_debug_id;
        e->call_type = reply ? 2 : !!(tr->flags & TF_ONE_WAY);
        e->from_proc = proc->pid;
        e->from_thread = thread->pid;
        e->target_handle = tr->target.handle;
        e->data_size = tr->data_size;
        e->offsets_size = tr->offsets_size;
        strscpy(e->context_name, proc->context->name, BINDERFS_MAX_NAME);

        binder_inner_proc_lock(proc);
        binder_set_extended_error(&thread->ee, t_debug_id, BR_OK, 0);
        binder_inner_proc_unlock(proc);

        if (reply) {// 找到要回复的进程
                ......
        } else {// 1. 找到要发送的目的进程
                if (tr->target.handle) { // 目的进程非service_manager进程
                       .....
                } else { //目的进程是service_manager进程
                        // 找到service_manager的binder_node节点
                        .....
                }
                ......
        }
        if (target_thread)
                e->to_thread = target_thread->pid;
        e->to_proc = target_proc->pid;

        /* TODO: reuse incoming transaction for reply */
        // 为binder_transcation分配内存
        t = kzalloc(sizeof(*t), GFP_KERNEL);
        
        .....

        if (!reply && !(tr->flags & TF_ONE_WAY))
                t->from = thread;
        else
                t->from = NULL;
        // 存储发送双方的基本信息
        t->from_pid = proc->pid;
        t->from_tid = thread->pid;
        t->sender_euid = task_euid(proc->tsk);
        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_new_buf(&target_proc->alloc, tr->data_size,
                tr->offsets_size, extra_buffers_size,
                !reply && (t->flags & TF_ONE_WAY));
        ......
        
        t->buffer->debug_id = t->debug_id;
        t->buffer->transaction = t;
        t->buffer->target_node = target_node;
        t->buffer->clear_on_free = !!(t->flags & TF_CLEAR_BUF);
        trace_binder_transaction_alloc_buf(t->buffer);
        
        // 把客户端的数据拷贝到目的进程service_manager mmap的内存空间,即t->buffer指向的内存空间
        if (binder_alloc_copy_user_to_buffer(
                                &target_proc->alloc,
                                t->buffer,
                                ALIGN(tr->data_size, sizeof(void *)),
                                (const void __user *)
                                        (uintptr_t)tr->data.ptr.offsets,
                                tr->offsets_size)) {
                binder_user_error("%d:%d got transaction with invalid offsets ptr\n",
                                proc->pid, thread->pid);
                return_error = BR_FAILED_REPLY;
                return_error_param = -EFAULT;
                return_error_line = __LINE__;
                goto err_copy_data_failed;
        }
        
        ......

		/* Done processing objects, copy the rest of the buffer */
		if (binder_alloc_copy_user_to_buffer(
					&target_proc->alloc,
					t->buffer, user_offset,
					user_buffer + user_offset,
					tr->data_size - user_offset)) {
			binder_user_error("%d:%d got transaction with invalid data ptr\n",
					proc->pid, thread->pid);
			return_error = BR_FAILED_REPLY;
			return_error_param = -EFAULT;
			return_error_line = __LINE__;
			goto err_copy_data_failed;
		}
		
		......
		
		t->work.type = BINDER_WORK_TRANSACTION;

		if (reply) {
			......
		} else if (!(t->flags & TF_ONE_WAY)) {
			BUG_ON(t->buffer->async_transaction != 0);
			binder_inner_proc_lock(proc);
			/*
			 * Defer the TRANSACTION_COMPLETE, so we don't return to
			 * userspace immediately; this allows the target process to
			 * immediately start processing this transaction, reducing
			 * latency. We will then return the TRANSACTION_COMPLETE when
			 * the target replies (or there is an error).
			 */
			binder_enqueue_deferred_thread_work_ilocked(thread, tcomplete);
			t->need_reply = 1;
			t->from_parent = thread->transaction_stack;
			//入栈
			thread->transaction_stack = t;
			binder_inner_proc_unlock(proc);
			//将数据放入目的进程的binder_proc或binder_thread的todo链表
			return_error = binder_proc_transaction(t,
					target_proc, target_thread);
			if (return_error) {
				binder_inner_proc_lock(proc);
				binder_pop_transaction_ilocked(thread, t);
				binder_inner_proc_unlock(proc);
				goto err_dead_proc_or_thread;
			}
		} else {
			......
		}
}
4.5 binder_proc_transaction将待处理的数据放到service_manager的todo链表,并唤醒service_manager
static int binder_proc_transaction(struct binder_transaction *t,
				    struct binder_proc *proc,
				    struct binder_thread *thread)
{
	struct binder_node *node = t->buffer->target_node;
	bool oneway = !!(t->flags & TF_ONE_WAY);
	bool pending_async = false;
	struct binder_transaction *t_outdated = NULL;
	bool frozen = false;

	BUG_ON(!node);
	binder_node_lock(node);
	if (oneway) {
		BUG_ON(thread);
		if (node->has_async_transaction)
			pending_async = true;
		else
			node->has_async_transaction = true;
	}

	binder_inner_proc_lock(proc);
	if (proc->is_frozen) {
		frozen = true;
		proc->sync_recv |= !oneway;
		proc->async_recv |= oneway;
	}

	if ((frozen && !oneway) || proc->is_dead ||
			(thread && thread->is_dead)) {
		binder_inner_proc_unlock(proc);
		binder_node_unlock(node);
		return frozen ? BR_FROZEN_REPLY : BR_DEAD_REPLY;
	}

	if (!thread && !pending_async)
		thread = binder_select_thread_ilocked(proc);

	if (thread) {
		binder_enqueue_thread_work_ilocked(thread, &t->work);//将数据放入目的进程的binder_thread
	} else if (!pending_async) {
		binder_enqueue_work_ilocked(&t->work, &proc->todo);//将数据放入目的进程的binder_proc
	} else {
		if ((t->flags & TF_UPDATE_TXN) && frozen) {
			t_outdated = binder_find_outdated_transaction_ilocked(t,
									      &node->async_todo);
			if (t_outdated) {
				binder_debug(BINDER_DEBUG_TRANSACTION,
					     "txn %d supersedes %d\n",
					     t->debug_id, t_outdated->debug_id);
				list_del_init(&t_outdated->work.entry);
				proc->outstanding_txns--;
			}
		}
		binder_enqueue_work_ilocked(&t->work, &node->async_todo);
	}

	if (!pending_async)
		binder_wakeup_thread_ilocked(proc, thread, !oneway /* sync */);

	proc->outstanding_txns++;
	binder_inner_proc_unlock(proc);
	binder_node_unlock(node);

	/*
	 * To reduce potential contention, free the outdated transaction and
	 * buffer after releasing the locks.
	 */
	if (t_outdated) {
		struct binder_buffer *buffer = t_outdated->buffer;

		t_outdated->buffer = NULL;
		buffer->transaction = NULL;
		trace_binder_transaction_update_buffer_release(buffer);
		binder_release_entire_buffer(proc, NULL, buffer, false);
		binder_alloc_free_buf(&proc->alloc, buffer);
		kfree(t_outdated);
		binder_stats_deleted(BINDER_STAT_TRANSACTION);
	}

	if (oneway && frozen)
		return BR_TRANSACTION_PENDING_FROZEN;

	return 0;
}

static void
binder_enqueue_thread_work_ilocked(struct binder_thread *thread,
				   struct binder_work *work)
{
	WARN_ON(!list_empty(&thread->waiting_thread_node));
	binder_enqueue_work_ilocked(work, &thread->todo); // 将待处理的数据放到thread的todo链表

	/* (e)poll-based threads require an explicit wakeup signal when
	 * queuing their own work; they rely on these events to consume
	 * messages without I/O block. Without it, threads risk waiting
	 * indefinitely without handling the work.
	 */
	if (thread->looper & BINDER_LOOPER_STATE_POLL &&
	    thread->pid == current->pid && !thread->process_todo)
	    // 唤醒service_manager
		wake_up_interruptible_sync(&thread->wait);

	thread->process_todo = true;
}

static void
binder_enqueue_work_ilocked(struct binder_work *work,
			   struct list_head *target_list)
{
	BUG_ON(target_list == NULL);
	BUG_ON(work->entry.next && !list_empty(&work->entry));
	list_add_tail(&work->entry, target_list);
}

2.2. service_manager被唤醒

1. service_manager发送ioctl读取内核中的数据
int main(int argc, char **argv)
{
    struct binder_state *bs;

    bs = binder_open(128*1024);
    if (!bs) {
        ALOGE("failed to open binder driver\n");
        return -1;
    }

    if (binder_become_context_manager(bs)) {
        ALOGE("cannot become context manager (%s)\n", strerror(errno));
        return -1;
    }


    svcmgr_handle = BINDER_SERVICE_MANAGER;
    binder_loop(bs, svcmgr_handler);

    return 0;
}

void binder_loop(struct binder_state *bs, binder_handler func)
{
    int res;
    struct binder_write_read bwr;
    uint32_t readbuf[32];

    bwr.write_size = 0;
    bwr.write_consumed = 0;
    bwr.write_buffer = 0;

    readbuf[0] = BC_ENTER_LOOPER;
    binder_write(bs, readbuf, sizeof(uint32_t));

    for (;;) {
        bwr.read_size = sizeof(readbuf);
        bwr.read_consumed = 0;
        bwr.read_buffer = (uintptr_t) readbuf;
        
        // 发起读操作
        res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);

        if (res < 0) {
            ALOGE("binder_loop: ioctl failed (%s)\n", strerror(errno));
            break;
        }

        res = binder_parse(bs, 0, (uintptr_t) readbuf, bwr.read_consumed, func);
        if (res == 0) {
            ALOGE("binder_loop: unexpected reply?!\n");
            break;
        }
        if (res < 0) {
            ALOGE("binder_loop: io error %d %s\n", res, strerror(errno));
            break;
        }
    }
}
2. binder_ioctl
// res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);进入binder驱动程序
static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
	int ret;
	struct binder_proc *proc = filp->private_data;
	struct binder_thread *thread;
	void __user *ubuf = (void __user *)arg;

	/*pr_info("binder_ioctl: %d:%d %x %lx\n",
			proc->pid, current->pid, cmd, arg);*/

	binder_selftest_alloc(&proc->alloc);

	trace_binder_ioctl(cmd, arg);

	ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);
	if (ret)
		goto err_unlocked;

	//为进程proc创建binder_thread
	thread = binder_get_thread(proc);
	if (thread == NULL) {
		ret = -ENOMEM;
		goto err;
	}

	switch (cmd) {
	case BINDER_WRITE_READ:
		ret = binder_ioctl_write_read(filp, arg, thread);
		if (ret)
			goto err;
		break;
		......
	}
	......
}
3. binder_ioctl_write_read
static int binder_ioctl_write_read(struct file *filp, unsigned long arg,
				struct binder_thread *thread)
{
	int ret = 0;
	struct binder_proc *proc = filp->private_data;
	void __user *ubuf = (void __user *)arg;
	struct binder_write_read bwr;

    //从用户空间拷贝数据到内核空间(这部分内核空间被mmap映射到了目标进程)
	if (copy_from_user(&bwr, ubuf, sizeof(bwr))) {
		ret = -EFAULT;
		goto out;
	}
	binder_debug(BINDER_DEBUG_READ_WRITE,
		     "%d:%d write %lld at %016llx, read %lld at %016llx\n",
		     proc->pid, thread->pid,
		     (u64)bwr.write_size, (u64)bwr.write_buffer,
		     (u64)bwr.read_size, (u64)bwr.read_buffer);

	if (bwr.write_size > 0) {
		......
	}
	if (bwr.read_size > 0) {
		ret = binder_thread_read(proc, thread, bwr.read_buffer,
					 bwr.read_size,
					 &bwr.read_consumed,
					 filp->f_flags & O_NONBLOCK);
		trace_binder_read_done(ret);
		binder_inner_proc_lock(proc);
		if (!binder_worklist_empty_ilocked(&proc->todo))
			binder_wakeup_proc_ilocked(proc);
		binder_inner_proc_unlock(proc);
		if (ret < 0) {
			if (copy_to_user(ubuf, &bwr, sizeof(bwr)))
				ret = -EFAULT;
			goto out;
		}
	}
	binder_debug(BINDER_DEBUG_READ_WRITE,
		     "%d:%d wrote %lld of %lld, read return %lld of %lld\n",
		     proc->pid, thread->pid,
		     (u64)bwr.write_consumed, (u64)bwr.write_size,
		     (u64)bwr.read_consumed, (u64)bwr.read_size);
	if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {
		ret = -EFAULT;
		goto out;
	}
out:
	return ret;
}
4. binder_thread_read

读取service_manager内核空间的数据,写入service_manager用户空间

static int binder_thread_read(struct binder_proc *proc,
			      struct binder_thread *thread,
			      binder_uintptr_t binder_buffer, size_t size,
			      binder_size_t *consumed, int non_block)
{
	void __user *buffer = (void __user *)(uintptr_t)binder_buffer;
	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:
	binder_inner_proc_lock(proc);
	wait_for_proc_work = binder_available_for_proc_work_ilocked(thread);
	binder_inner_proc_unlock(proc);

	thread->looper |= BINDER_LOOPER_STATE_WAITING;

	trace_binder_wait_for_work(wait_for_proc_work,
				   !!thread->transaction_stack,
				   !binder_worklist_empty(proc, &thread->todo));
	if (wait_for_proc_work) {
		if (!(thread->looper & (BINDER_LOOPER_STATE_REGISTERED |
					BINDER_LOOPER_STATE_ENTERED))) {
			binder_user_error("%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_work(thread, wait_for_proc_work))
			ret = -EAGAIN;
	} else {
		ret = binder_wait_for_work(thread, wait_for_proc_work);
	}

	thread->looper &= ~BINDER_LOOPER_STATE_WAITING;
	
	if (ret)
		return ret;

	while (1) {
		uint32_t cmd;
		struct binder_transaction_data_secctx tr;
		struct binder_transaction_data *trd = &tr.transaction_data;
		struct binder_work *w = NULL;
		struct list_head *list = NULL;
		struct binder_transaction *t = NULL;
		struct binder_thread *t_from;
		size_t trsize = sizeof(*trd);

		binder_inner_proc_lock(proc);
		//如果proc的thread->todo链表有数据,拿到链表数据
		if (!binder_worklist_empty_ilocked(&thread->todo))
			list = &thread->todo;
		//如果proc->todo链表有数据,拿到链表数据
		else if (!binder_worklist_empty_ilocked(&proc->todo) &&
			   wait_for_proc_work)
			list = &proc->todo;
		else {
			binder_inner_proc_unlock(proc);

			/* no data added */
			if (ptr - buffer == 4 && !thread->looper_need_return)
				goto retry;
			break;
		}

		if (end - ptr < sizeof(tr) + 4) {
			binder_inner_proc_unlock(proc);
			break;
		}
		w = binder_dequeue_work_head_ilocked(list);
		if (binder_worklist_empty_ilocked(&thread->todo))
			thread->process_todo = false;

		//逐个处理相关类型的数据,server唤醒service_manager,将数据添加到链表时,binder_work.type是BINDER_WORK_TRANSACTION
		switch (w->type) {
		case BINDER_WORK_TRANSACTION: {
			binder_inner_proc_unlock(proc);
			 t= container_of(w, struct binder_transaction, work);//构造出发送方发来的binder_transaction
		} break;
		
		......
		
		}

		if (!t)
			continue;

		BUG_ON(t->buffer == NULL);
		if (t->buffer->target_node) {
			struct binder_node *target_node = t->buffer->target_node;

			trd->target.ptr = target_node->ptr;
			trd->cookie =  target_node->cookie;
			t->saved_priority = task_nice(current);
			if (t->priority < target_node->min_priority &&
			    !(t->flags & TF_ONE_WAY))
				binder_set_nice(t->priority);
			else if (!(t->flags & TF_ONE_WAY) ||
				 t->saved_priority > target_node->min_priority)
				binder_set_nice(target_node->min_priority);
            //从server发送数据给service_manager,cmd是BC_TRANSACTION
            //从service_manager返回数据给server,将cmd设为BR_TRANSACTION,
			cmd = BR_TRANSACTION;
		} else {
			trd->target.ptr = 0;
			trd->cookie = 0;
			cmd = BR_REPLY;
		}
		trd->code = t->code;
		trd->flags = t->flags;
		trd->sender_euid = from_kuid(current_user_ns(), t->sender_euid);

		......
		
		trd->data_size = t->buffer->data_size;
		trd->offsets_size = t->buffer->offsets_size;
		trd->data.ptr.buffer = t->buffer->user_data;
		trd->data.ptr.offsets = trd->data.ptr.buffer +
					ALIGN(t->buffer->data_size,
					    sizeof(void *));

		tr.secctx = t->security_ctx;
		if (t->security_ctx) {
			cmd = BR_TRANSACTION_SEC_CTX;
			trsize = sizeof(tr);
		}
		// 把cmd写入service_manager的用户空间
		if (put_user(cmd, (uint32_t __user *)ptr)) {
			if (t_from)
				binder_thread_dec_tmpref(t_from);

			binder_cleanup_transaction(t, "put_user failed",
						   BR_FAILED_REPLY);

			return -EFAULT;
		}
		ptr += sizeof(uint32_t);
		// 把tr写入service_manager的用户空间,tr.transaction_data中包括了客户端发送来的数据
		if (copy_to_user(ptr, &tr, trsize)) {
			if (t_from)
				binder_thread_dec_tmpref(t_from);

			binder_cleanup_transaction(t, "copy_to_user failed",
						   BR_FAILED_REPLY);

			return -EFAULT;
		}
		ptr += trsize;

		......

done:

	......
	
	return 0;
}
5. 从service_manager内核空间读取到的数据组织形式

在这里插入图片描述

6. binder_parse解析客户端发送给service_manager的数据

此时cmd是BR_TRANSACTION

void binder_loop(struct binder_state *bs, binder_handler func)
{
    int res;
    struct binder_write_read bwr;
    uint32_t readbuf[32];

    bwr.write_size = 0;
    bwr.write_consumed = 0;
    bwr.write_buffer = 0;

    readbuf[0] = BC_ENTER_LOOPER;
    binder_write(bs, readbuf, sizeof(uint32_t));

    for (;;) {
        bwr.read_size = sizeof(readbuf);
        bwr.read_consumed = 0;
        bwr.read_buffer = (uintptr_t) readbuf;

        res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);//读到数据

        if (res < 0) {
            ALOGE("binder_loop: ioctl failed (%s)\n", strerror(errno));
            break;
        }
        
        //解析读到的数据
        res = binder_parse(bs, 0, (uintptr_t) readbuf, bwr.read_consumed, func);
        if (res == 0) {
            ALOGE("binder_loop: unexpected reply?!\n");
            break;
        }
        if (res < 0) {
            ALOGE("binder_loop: io error %d %s\n", res, strerror(errno));
            break;
        }
    }
}

int binder_parse(struct binder_state *bs, struct binder_io *bio,
                 uintptr_t ptr, size_t size, binder_handler func)
{
    int r = 1;
    uintptr_t end = ptr + (uintptr_t) size;

    while (ptr < end) {
        uint32_t cmd = *(uint32_t *) ptr;
        ptr += sizeof(uint32_t);
#if TRACE
        fprintf(stderr,"%s:\n", cmd_name(cmd));
#endif
        switch(cmd) {
        case BR_NOOP:
            break;
        ......
        //收到数据的处理情况,(收到的数据中有服务名称,服务的handle)
        case BR_TRANSACTION: {
            struct binder_transaction_data *txn = (struct binder_transaction_data *) ptr;
            if ((end - ptr) < sizeof(*txn)) {
                ALOGE("parse: txn too small!\n");
                return -1;
            }
            binder_dump_txn(txn);
            if (func) {
                unsigned rdata[256/4];
                struct binder_io msg;
                struct binder_io reply;
                int res;
                //构造binder_io
                bio_init(&reply, rdata, sizeof(rdata), 4);
                bio_init_from_txn(&msg, txn);
                //处理binde_io
                res = func(bs, txn, &msg, &reply); // func = svcmgr_handler,用于添加/获取服务
                //将处理完的数据,发送给server
                binder_send_reply(bs, &reply, txn->data.ptr.buffer, res);
            }
            ptr += sizeof(*txn);
            break;
        }
        ......
        default:
            ALOGE("parse: OOPS %d\n", cmd);
            return -1;
        }
    }

    return r;
}

7. svcmgr_handler处理客户端发送给service_manager的数据,获取客户端请求的服务handle
int svcmgr_handler(struct binder_state *bs,
                   struct binder_transaction_data *txn,
                   struct binder_io *msg,
                   struct binder_io *reply)
{
    struct svcinfo *si;
    uint16_t *s;
    size_t len;
    uint32_t handle;
    uint32_t strict_policy;
    int allow_isolated;

    //ALOGI("target=%x code=%d pid=%d uid=%d\n",
    //  txn->target.handle, txn->code, txn->sender_pid, txn->sender_euid);

    if (txn->target.handle != svcmgr_handle)
        return -1;

    if (txn->code == PING_TRANSACTION)
        return 0;

    // Equivalent to Parcel::enforceInterface(), reading the RPC
    // header with the strict mode policy mask and the interface name.
    // Note that we ignore the strict_policy and don't propagate it
    // further (since we do no outbound RPCs anyway).
    strict_policy = bio_get_uint32(msg);
    s = bio_get_string16(msg, &len); //传入的是android.os.IServiceManager
    if (s == NULL) {
        return -1;
    }

    if ((len != (sizeof(svcmgr_id) / 2)) ||
        memcmp(svcmgr_id, s, sizeof(svcmgr_id))) {//传入的必须是android.os.IServiceManager
        fprintf(stderr,"invalid id %s\n", str8(s, len));
        return -1;
    }


    switch(txn->code) {
    case SVC_MGR_GET_SERVICE:
    case SVC_MGR_CHECK_SERVICE:
        s = bio_get_string16(msg, &len); // 获取客户端要获取的服务的名字"hello"
        if (s == NULL) {
            return -1;
        }
        // 在service_manager的服务列表中寻找服务名为hello的服务的handle
        handle = do_find_service(bs, s, len, txn->sender_euid, txn->sender_pid);
        if (!handle)
            break;
            
        // 将服务handle写入reply
        bio_put_ref(reply, handle);
        return 0;

    ......

    bio_put_uint32(reply, 0);//处理完后,最后要构造一个reply,并放入0
    return 0;
}

uint32_t do_find_service(struct binder_state *bs, const uint16_t *s, size_t len, uid_t uid, pid_t spid)
{
    struct svcinfo *si;

    if (!svc_can_find(s, len, spid)) {
        ALOGE("find_service('%s') uid=%d - PERMISSION DENIED\n",
             str8(s, len), uid);
        return 0;
    }
    si = find_svc(s, len);
    //ALOGI("check_service('%s') handle = %x\n", str8(s, len), si ? si->handle : 0);
    if (si && si->handle) {
        if (!si->allow_isolated) {
            // If this service doesn't allow access from isolated processes,
            // then check the uid to see if it is isolated.
            uid_t appid = uid % AID_USER;
            if (appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END) {
                return 0;
            }
        }
        return si->handle;
    } else {
        return 0;
    }
}

struct svcinfo *find_svc(const uint16_t *s16, size_t len)
{
    struct svcinfo *si;

    for (si = svclist; si; si = si->next) {
        if ((len == si->len) &&
            !memcmp(s16, si->name, len * sizeof(uint16_t))) {
            return si;
        }
    }
    return NULL;
}

void bio_put_ref(struct binder_io *bio, uint32_t handle)
{
    struct flat_binder_object *obj;

    if (handle)
        obj = bio_alloc_obj(bio);
    else
        obj = bio_alloc(bio, sizeof(*obj));

    if (!obj)
        return;

    obj->flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
    obj->type = BINDER_TYPE_HANDLE;
    obj->handle = handle;
    obj->cookie = 0;
}
8. binder_send_reply将获取到的服务handle数据回复给驱动程序
int binder_parse(struct binder_state *bs, struct binder_io *bio,
                 uintptr_t ptr, size_t size, binder_handler func)
{
    int r = 1;
    uintptr_t end = ptr + (uintptr_t) size;

    while (ptr < end) {
        uint32_t cmd = *(uint32_t *) ptr;
        ptr += sizeof(uint32_t);
#if TRACE
        fprintf(stderr,"%s:\n", cmd_name(cmd));
#endif
        switch(cmd) {
        case BR_NOOP:
            break;
        ......
        //收到数据的处理情况,(收到的数据中有服务名称,服务的handle)
        case BR_TRANSACTION: {
            struct binder_transaction_data *txn = (struct binder_transaction_data *) ptr;
            if ((end - ptr) < sizeof(*txn)) {
                ALOGE("parse: txn too small!\n");
                return -1;
            }
            binder_dump_txn(txn);
            if (func) {
                unsigned rdata[256/4];
                struct binder_io msg;
                struct binder_io reply;
                int res;
                //构造binder_io
                bio_init(&reply, rdata, sizeof(rdata), 4);
                bio_init_from_txn(&msg, txn);
                //处理binde_io
                res = func(bs, txn, &msg, &reply); // func = svcmgr_handler,用于添加/获取服务
                //将处理完的数据,发送给server
                binder_send_reply(bs, &reply, txn->data.ptr.buffer, res);
            }
            ptr += sizeof(*txn);
            break;
        }
        ......
        default:
            ALOGE("parse: OOPS %d\n", cmd);
            return -1;
        }
    }

    return r;
}

void binder_send_reply(struct binder_state *bs,
                       struct binder_io *reply,
                       binder_uintptr_t buffer_to_free,
                       int status)
{
    struct {
        uint32_t cmd_free;
        binder_uintptr_t buffer;
        uint32_t cmd_reply;
        struct binder_transaction_data txn;
    } __attribute__((packed)) data;

    data.cmd_free = BC_FREE_BUFFER;//server拷贝到service_manager映射的内核态缓冲区的数据,用完后,就可以释放了
    data.buffer = buffer_to_free;
    data.cmd_reply = BC_REPLY; // service_manager处理完数据后,将结果回复回去,cmd = BC_REPLY
    data.txn.target.ptr = 0;
    data.txn.cookie = 0;
    data.txn.code = 0;
    if (status) {
        data.txn.flags = TF_STATUS_CODE;
        data.txn.data_size = sizeof(int);
        data.txn.offsets_size = 0;
        data.txn.data.ptr.buffer = (uintptr_t)&status;
        data.txn.data.ptr.offsets = 0;
    } else {
        data.txn.flags = 0;
        data.txn.data_size = reply->data - reply->data0;
        data.txn.offsets_size = ((char*) reply->offs) - ((char*) reply->offs0);
        data.txn.data.ptr.buffer = (uintptr_t)reply->data0;
        data.txn.data.ptr.offsets = (uintptr_t)reply->offs0;
    }
    binder_write(bs, &data, sizeof(data));
}

int binder_write(struct binder_state *bs, void *data, size_t len)
{
    struct binder_write_read bwr;
    int res;

    bwr.write_size = len;
    bwr.write_consumed = 0;
    bwr.write_buffer = (uintptr_t) data;
    bwr.read_size = 0;
    bwr.read_consumed = 0;
    bwr.read_buffer = 0;
    res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);
    if (res < 0) {
        fprintf(stderr,"binder_write: ioctl failed (%s)\n",
                strerror(errno));
    }
    return res;
}

2.3 binder驱动接收到service_manager解析完客户端发送的数据的数据

1. binder_ioctl
static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
	int ret;
	struct binder_proc *proc = filp->private_data;
	struct binder_thread *thread;
	void __user *ubuf = (void __user *)arg;

	/*pr_info("binder_ioctl: %d:%d %x %lx\n",
			proc->pid, current->pid, cmd, arg);*/

	binder_selftest_alloc(&proc->alloc);

	trace_binder_ioctl(cmd, arg);

	ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);
	if (ret)
		goto err_unlocked;

	//为进程proc创建binder_thread
	thread = binder_get_thread(proc);
	if (thread == NULL) {
		ret = -ENOMEM;
		goto err;
	}

	switch (cmd) {
	case BINDER_WRITE_READ:
		ret = binder_ioctl_write_read(filp, arg, thread);
		if (ret)
			goto err;
		break;
		......
	}
	......
}
2. binder_ioctl_write_read
static int binder_ioctl_write_read(struct file *filp, unsigned long arg,
				struct binder_thread *thread)
{
	int ret = 0;
	struct binder_proc *proc = filp->private_data;
	void __user *ubuf = (void __user *)arg;
	struct binder_write_read bwr;

    //从用户空间拷贝数据到内核空间(这部分内核空间被mmap映射到了目标进程)
	if (copy_from_user(&bwr, ubuf, sizeof(bwr))) {
		ret = -EFAULT;
		goto out;
	}
	binder_debug(BINDER_DEBUG_READ_WRITE,
		     "%d:%d write %lld at %016llx, read %lld at %016llx\n",
		     proc->pid, thread->pid,
		     (u64)bwr.write_size, (u64)bwr.write_buffer,
		     (u64)bwr.read_size, (u64)bwr.read_buffer);

	if (bwr.write_size > 0) {
		ret = binder_thread_write(proc, thread,
					  bwr.write_buffer,
					  bwr.write_size,
					  &bwr.write_consumed);
		trace_binder_write_done(ret);
		if (ret < 0) {
			bwr.read_consumed = 0;
			if (copy_to_user(ubuf, &bwr, sizeof(bwr)))
				ret = -EFAULT;
			goto out;
		}
	}
	if (bwr.read_size > 0) {
		......
	}
	......
out:
	return ret;
}
3. binder_thread_write

此时cmd是BC_REPLY

static int binder_thread_write(struct binder_proc *proc,
                        struct binder_thread *thread,
                        binder_uintptr_t binder_buffer, size_t size,
                        binder_size_t *consumed)
{
        uint32_t cmd;
        struct binder_context *context = proc->context;
        // 获取数据buffer,根据上面总结的发送数据可知,这个buffer由cmd和binder_transcation_data两部分数据组成
        void __user *buffer = (void __user *)(uintptr_t)binder_buffer;
        // 发送来的数据consumed=0,因此ptr指向用户空间数据buffer的起点
        void __user *ptr = buffer + *consumed;
        // 指向数据buffer的末尾
        void __user *end = buffer + size;
        // 逐个读取客户端发送来的数据(cmd+binder_transcation_data)
        while (ptr < end && thread->return_error.cmd == BR_OK) {
                int ret;
                
                // 获取用户空间中buffer的cmd值
                if (get_user(cmd, (uint32_t __user *)ptr))
                        return -EFAULT;
                // 移动指针到cmd的位置之后,指向binder_transcation_data数据的内存起点
                ptr += sizeof(uint32_t);
                trace_binder_command(cmd);
                if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.bc)) {
                        atomic_inc(&binder_stats.bc[_IOC_NR(cmd)]);
                        atomic_inc(&proc->stats.bc[_IOC_NR(cmd)]);
                        atomic_inc(&thread->stats.bc[_IOC_NR(cmd)]);
                }
                // 根据上面总结的发送数据可知,cmd是BC_TRANSACTION
                switch (cmd) {
                   ......
                   /*
                BC_TRANSACTION:进程发送信息的cmd
                BR_TRANSACTION:进程接收BC_TRANSACTION发送信息的cmd
                
                BC_REPLY:进程回复信息的cmd
                BR_REPLY:进程接收BC_REPLY回复信息的cmd
                */
                    case BC_TRANSACTION:
                    case BC_REPLY: {
                            struct binder_transaction_data tr;
                            
                            // 从用户空间拷贝binder_transaction_data到内核空间
                            if (copy_from_user(&tr, ptr, sizeof(tr)))
                                    return -EFAULT;
                            // 移动指针到binder_transaction_data的位置之后,指向下一个cmd数据的内存起点
                            ptr += sizeof(tr);
                            // 处理binder_transaction_data数据
                            binder_transaction(proc, thread, &tr,
                                               cmd == BC_REPLY, 0);
                            break;
                    }
                }
        }
        ......
}

int get_user(int *val, const int __user *ptr) {
    if (copy_from_user(val, ptr, sizeof(int))) {
        return -EFAULT; // 返回错误码
    }
    return 0; // 成功
}
4. binder_transaction
4.1. 找到要回复的进程
static void binder_transaction(struct binder_proc *proc,
                               struct binder_thread *thread,
                               struct binder_transaction_data *tr, int reply,
                               binder_size_t extra_buffers_size)
{
        ......

        if (reply) {// 找到要回复的进程
                binder_inner_proc_lock(proc);
				in_reply_to = thread->transaction_stack;//从栈中取出binder_transaction,获得要回复给谁
				if (in_reply_to == NULL) {
					binder_inner_proc_unlock(proc);
					binder_user_error("%d:%d got reply transaction with no transaction stack\n",
							  proc->pid, thread->pid);
					return_error = BR_FAILED_REPLY;
					return_error_param = -EPROTO;
					return_error_line = __LINE__;
					goto err_empty_call_stack;
				}
				if (in_reply_to->to_thread != thread) {
					spin_lock(&in_reply_to->lock);
					binder_user_error("%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);
					spin_unlock(&in_reply_to->lock);
					binder_inner_proc_unlock(proc);
					return_error = BR_FAILED_REPLY;
					return_error_param = -EPROTO;
					return_error_line = __LINE__;
					in_reply_to = NULL;
					goto err_bad_call_stack;
				}
				thread->transaction_stack = in_reply_to->to_parent;//出栈
				binder_inner_proc_unlock(proc);
				binder_set_nice(in_reply_to->saved_priority);
				target_thread = binder_get_txn_from_and_acq_inner(in_reply_to);
				if (target_thread == NULL) {
					/* annotation for sparse */
					__release(&target_thread->proc->inner_lock);
					binder_txn_error("%d:%d reply target not found\n",
						thread->pid, proc->pid);
					return_error = BR_DEAD_REPLY;
					return_error_line = __LINE__;
					goto err_dead_binder;
				}
				if (target_thread->transaction_stack != in_reply_to) {
					binder_user_error("%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);
					binder_inner_proc_unlock(target_thread->proc);
					return_error = BR_FAILED_REPLY;
					return_error_param = -EPROTO;
					return_error_line = __LINE__;
					in_reply_to = NULL;
					target_thread = NULL;
					goto err_dead_binder;
				}
				// 找到要回复的进程
				target_proc = target_thread->proc;
				target_proc->tmp_ref++;
				binder_inner_proc_unlock(target_thread->proc);
        } else {// 1. 找到要发送的目的进程
                ......
        }
......
}
4.2 处理flat_binder_object
static void binder_transaction(struct binder_proc *proc,
                               struct binder_thread *thread,
                               struct binder_transaction_data *tr, int reply,
                               binder_size_t extra_buffers_size)
{
        ......

        if (reply) {// 找到要回复的进程
                binder_inner_proc_lock(proc);
				in_reply_to = thread->transaction_stack;//从栈中取出binder_transaction,获得要回复给谁
				if (in_reply_to == NULL) {
					binder_inner_proc_unlock(proc);
					binder_user_error("%d:%d got reply transaction with no transaction stack\n",
							  proc->pid, thread->pid);
					return_error = BR_FAILED_REPLY;
					return_error_param = -EPROTO;
					return_error_line = __LINE__;
					goto err_empty_call_stack;
				}
				if (in_reply_to->to_thread != thread) {
					spin_lock(&in_reply_to->lock);
					binder_user_error("%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);
					spin_unlock(&in_reply_to->lock);
					binder_inner_proc_unlock(proc);
					return_error = BR_FAILED_REPLY;
					return_error_param = -EPROTO;
					return_error_line = __LINE__;
					in_reply_to = NULL;
					goto err_bad_call_stack;
				}
				thread->transaction_stack = in_reply_to->to_parent;//出栈
				binder_inner_proc_unlock(proc);
				binder_set_nice(in_reply_to->saved_priority);
				target_thread = binder_get_txn_from_and_acq_inner(in_reply_to);
				if (target_thread == NULL) {
					/* annotation for sparse */
					__release(&target_thread->proc->inner_lock);
					binder_txn_error("%d:%d reply target not found\n",
						thread->pid, proc->pid);
					return_error = BR_DEAD_REPLY;
					return_error_line = __LINE__;
					goto err_dead_binder;
				}
				if (target_thread->transaction_stack != in_reply_to) {
					binder_user_error("%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);
					binder_inner_proc_unlock(target_thread->proc);
					return_error = BR_FAILED_REPLY;
					return_error_param = -EPROTO;
					return_error_line = __LINE__;
					in_reply_to = NULL;
					target_thread = NULL;
					goto err_dead_binder;
				}
				// 找到要回复的进程
				target_proc = target_thread->proc;
				target_proc->tmp_ref++;
				binder_inner_proc_unlock(target_thread->proc);
        } else {// 1. 找到要发送的目的进程
                ......
        }
        if (target_thread)
                e->to_thread = target_thread->pid;
        e->to_proc = target_proc->pid;

        /* TODO: reuse incoming transaction for reply */
        // 为binder_transcation分配内存
        t = kzalloc(sizeof(*t), GFP_KERNEL);
        
        .....

        if (!reply && !(tr->flags & TF_ONE_WAY))
                t->from = thread;
        else
                t->from = NULL;
        // 存储发送双方的基本信息
        t->from_pid = proc->pid;
        t->from_tid = thread->pid;
        t->sender_euid = task_euid(proc->tsk);
        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_new_buf(&target_proc->alloc, tr->data_size,
                tr->offsets_size, extra_buffers_size,
                !reply && (t->flags & TF_ONE_WAY));
        ......
        
        t->buffer->debug_id = t->debug_id;
        t->buffer->transaction = t;
        t->buffer->target_node = target_node;
        t->buffer->clear_on_free = !!(t->flags & TF_CLEAR_BUF);
        trace_binder_transaction_alloc_buf(t->buffer);
        
        // 把客户端的数据拷贝到目的进程test_client mmap的内存空间
        if (binder_alloc_copy_user_to_buffer(
                                &target_proc->alloc,
                                t->buffer,
                                ALIGN(tr->data_size, sizeof(void *)),
                                (const void __user *)
                                        (uintptr_t)tr->data.ptr.offsets,
                                tr->offsets_size)) {
                binder_user_error("%d:%d got transaction with invalid offsets ptr\n",
                                proc->pid, thread->pid);
                return_error = BR_FAILED_REPLY;
                return_error_param = -EFAULT;
                return_error_line = __LINE__;
                goto err_copy_data_failed;
        }
        ......
		
		//处理server传入的binder_io.offs数据,这个数据指向用于构建binder_node实体的		flat_binder_object
		for (buffer_offset = off_start_offset; buffer_offset < off_end_offset;
		     buffer_offset += sizeof(binder_size_t)) {
			struct binder_object_header *hdr;
			size_t object_size;
			struct binder_object object;
			binder_size_t object_offset;
			binder_size_t copy_size;
	
			if (binder_alloc_copy_from_buffer(&target_proc->alloc,
							  &object_offset,
							  t->buffer,
							  buffer_offset,
							  sizeof(object_offset))) {
				binder_txn_error("%d:%d copy offset from buffer failed\n",
					thread->pid, proc->pid);
				return_error = BR_FAILED_REPLY;
				return_error_param = -EINVAL;
				return_error_line = __LINE__;
				goto err_bad_offset;
			}
	
			/*
			 * Copy the source user buffer up to the next object
			 * that will be processed.
			 */
			copy_size = object_offset - user_offset;
			if (copy_size && (user_offset > object_offset ||
					binder_alloc_copy_user_to_buffer(
						&target_proc->alloc,
						t->buffer, user_offset,
						user_buffer + user_offset,
						copy_size))) {
				binder_user_error("%d:%d got transaction with invalid data ptr\n",
						proc->pid, thread->pid);
				return_error = BR_FAILED_REPLY;
				return_error_param = -EFAULT;
				return_error_line = __LINE__;
				goto err_copy_data_failed;
			}
			// 将指向flat_binder_object的指针拷贝给object
			object_size = binder_get_object(target_proc, user_buffer,
					t->buffer, object_offset, &object);
			if (object_size == 0 || object_offset < off_min) {
				binder_user_error("%d:%d got transaction with invalid offset (%lld, min %lld max %lld) or object.\n",
						  proc->pid, thread->pid,
						  (u64)object_offset,
						  (u64)off_min,
						  (u64)t->buffer->data_size);
				return_error = BR_FAILED_REPLY;
				return_error_param = -EINVAL;
				return_error_line = __LINE__;
				goto err_bad_offset;
			}
			/*
			 * Set offset to the next buffer fragment to be
			 * copied
			 */
			user_offset = object_offset + object_size;
	
			hdr = &object.hdr;
			off_min = object_offset + object_size;
			// 此处 binder类型的是BINDER_TYPE_HANDLE,通过handle在service_manager的binder-ref中找到hello服务的binder_node
			switch (hdr->type) {
			//处理binder实体
			case BINDER_TYPE_BINDER:
			case BINDER_TYPE_WEAK_BINDER: {
				......
				
			} break;
			//处理binder引用
			case BINDER_TYPE_HANDLE:
			case BINDER_TYPE_WEAK_HANDLE: {
				struct flat_binder_object *fp;
	
				fp = to_flat_binder_object(hdr);
				ret = binder_translate_handle(fp, t, thread);
				if (ret < 0 ||
				    binder_alloc_copy_to_buffer(&target_proc->alloc,
								t->buffer,
								object_offset,
								fp, sizeof(*fp))) {
					binder_txn_error("%d:%d translate handle failed\n",
						thread->pid, proc->pid);
					return_error = BR_FAILED_REPLY;
					return_error_param = ret;
					return_error_line = __LINE__;
					goto err_translate_failed;
				}
			} break;
			......
	 }
......
}
4.3 根据handle找到服务的binder_node,
static int binder_translate_handle(struct flat_binder_object *fp,
				   struct binder_transaction *t,
				   struct binder_thread *thread)
{
	struct binder_proc *proc = thread->proc;
	struct binder_proc *target_proc = t->to_proc;
	struct binder_node *node;
	struct binder_ref_data src_rdata;
	int ret = 0;
    
    // 根据handle从service_manager中找到服务的binder_node
	node = binder_get_node_from_ref(proc, fp->handle,
			fp->hdr.type == BINDER_TYPE_HANDLE, &src_rdata);
	if (!node) {
		binder_user_error("%d:%d got transaction with invalid handle, %d\n",
				  proc->pid, thread->pid, fp->handle);
		return -EINVAL;
	}
	if (security_binder_transfer_binder(proc->cred, target_proc->cred)) {
		ret = -EPERM;
		goto done;
	}

	binder_node_lock(node);
	if (node->proc == target_proc) {
		if (fp->hdr.type == BINDER_TYPE_HANDLE)
			fp->hdr.type = BINDER_TYPE_BINDER;
		else
			fp->hdr.type = BINDER_TYPE_WEAK_BINDER;
		fp->binder = node->ptr;
		fp->cookie = node->cookie;
		if (node->proc)
			binder_inner_proc_lock(node->proc);
		else
			__acquire(&node->proc->inner_lock);
		binder_inc_node_nilocked(node,
					 fp->hdr.type == BINDER_TYPE_BINDER,
					 0, NULL);
		if (node->proc)
			binder_inner_proc_unlock(node->proc);
		else
			__release(&node->proc->inner_lock);
		trace_binder_transaction_ref_to_node(t, node, &src_rdata);
		binder_debug(BINDER_DEBUG_TRANSACTION,
			     "        ref %d desc %d -> node %d u%016llx\n",
			     src_rdata.debug_id, src_rdata.desc, node->debug_id,
			     (u64)node->ptr);
		binder_node_unlock(node);
	} else {
		struct binder_ref_data dest_rdata;

		binder_node_unlock(node);
		// 为客户端创建binder_ref指向服务的binder_node
		ret = binder_inc_ref_for_node(target_proc, node,
				fp->hdr.type == BINDER_TYPE_HANDLE,
				NULL, &dest_rdata);
		if (ret)
			goto done;

		fp->binder = 0;
		fp->handle = dest_rdata.desc;
		fp->cookie = 0;
		trace_binder_transaction_ref_to_ref(t, node, &src_rdata,
						    &dest_rdata);
		binder_debug(BINDER_DEBUG_TRANSACTION,
			     "        ref %d desc %d -> ref %d desc %d (node %d)\n",
			     src_rdata.debug_id, src_rdata.desc,
			     dest_rdata.debug_id, dest_rdata.desc,
			     node->debug_id);
	}
done:
	binder_put_node(node);
	return ret;
}

static struct binder_node *binder_get_node_from_ref(
		struct binder_proc *proc,
		u32 desc, bool need_strong_ref,
		struct binder_ref_data *rdata)
{
	struct binder_node *node;
	struct binder_ref *ref;

	binder_proc_lock(proc);
	// 根据handle找到binder_ref
	ref = binder_get_ref_olocked(proc, desc, need_strong_ref);
	if (!ref)
		goto err_no_ref;
		
	// 根据binder_ref找到binder_node
	node = ref->node;
	/*
	 * Take an implicit reference on the node to ensure
	 * it stays alive until the call to binder_put_node()
	 */
	binder_inc_node_tmpref(node);
	if (rdata)
		*rdata = ref->data;
	binder_proc_unlock(proc);

	return node;

err_no_ref:
	binder_proc_unlock(proc);
	return NULL;
}

static struct binder_ref *binder_get_ref_olocked(struct binder_proc *proc,
						 u32 desc, bool need_strong_ref)
{
	struct rb_node *n = proc->refs_by_desc.rb_node;
	struct binder_ref *ref;

	while (n) {
		ref = rb_entry(n, struct binder_ref, rb_node_desc);

		if (desc < ref->data.desc) {
			n = n->rb_left;
		} else if (desc > ref->data.desc) {
			n = n->rb_right;
		} else if (need_strong_ref && !ref->data.strong) {
			binder_user_error("tried to use weak ref as strong ref\n");
			return NULL;
		} else {
			return ref;
		}
	}
	return NULL;
}
4.4 为客户端创建binder_ref,指向服务的binder_node
static int binder_inc_ref_for_node(struct binder_proc *proc,
			struct binder_node *node,
			bool strong,
			struct list_head *target_list,
			struct binder_ref_data *rdata)
{
	struct binder_ref *ref;
	struct binder_ref *new_ref = NULL;
	int ret = 0;

	binder_proc_lock(proc);
	// 先查找客户端是否已经有对应的binder_ref,若没有则新建binder_ref
	ref = binder_get_ref_for_node_olocked(proc, node, NULL);
	if (!ref) {
		binder_proc_unlock(proc);
		new_ref = kzalloc(sizeof(*ref), GFP_KERNEL);
		if (!new_ref)
			return -ENOMEM;
		binder_proc_lock(proc);
		ref = binder_get_ref_for_node_olocked(proc, node, new_ref);
	}
	//增加引用计数
	ret = binder_inc_ref_olocked(ref, strong, target_list);
	*rdata = ref->data;
	if (ret && ref == new_ref) {
		/*
		 * Cleanup the failed reference here as the target
		 * could now be dead and have already released its
		 * references by now. Calling on the new reference
		 * with strong=0 and a tmp_refs will not decrement
		 * the node. The new_ref gets kfree'd below.
		 */
		binder_cleanup_ref_olocked(new_ref);
		ref = NULL;
	}

	binder_proc_unlock(proc);
	if (new_ref && ref != new_ref)
		/*
		 * Another thread created the ref first so
		 * free the one we allocated
		 */
		kfree(new_ref);
	return ret;
}

static struct binder_ref *binder_get_ref_for_node_olocked(
					struct binder_proc *proc,
					struct binder_node *node,
					struct binder_ref *new_ref)
{
	struct binder_context *context = proc->context;
	struct rb_node **p = &proc->refs_by_node.rb_node;
	struct rb_node *parent = NULL;
	struct binder_ref *ref;
	struct rb_node *n;

	while (*p) {
		parent = *p;
		ref = rb_entry(parent, struct binder_ref, rb_node_node);

		if (node < ref->node)
			p = &(*p)->rb_left;
		else if (node > ref->node)
			p = &(*p)->rb_right;
		else
			return ref;
	}
	if (!new_ref)
		return NULL;

	binder_stats_created(BINDER_STAT_REF);
	new_ref->data.debug_id = atomic_inc_return(&binder_last_id);
	new_ref->proc = proc;
	new_ref->node = node;
	rb_link_node(&new_ref->rb_node_node, parent, p);
	rb_insert_color(&new_ref->rb_node_node, &proc->refs_by_node);
    
    // 更新binder_ref的handle值,后续客户端通过handle值找到这个binder_ref,进而找到binder_node
	new_ref->data.desc = (node == context->binder_context_mgr_node) ? 0 : 1;
	for (n = rb_first(&proc->refs_by_desc); n != NULL; n = rb_next(n)) {
		ref = rb_entry(n, struct binder_ref, rb_node_desc);
		if (ref->data.desc > new_ref->data.desc)
			break;
		// 客户端引用服务的handle加1
		new_ref->data.desc = ref->data.desc + 1;
	}

	p = &proc->refs_by_desc.rb_node;
	while (*p) {
		parent = *p;
		ref = rb_entry(parent, struct binder_ref, rb_node_desc);

		if (new_ref->data.desc < ref->data.desc)
			p = &(*p)->rb_left;
		else if (new_ref->data.desc > ref->data.desc)
			p = &(*p)->rb_right;
		else
			BUG();
	}
	rb_link_node(&new_ref->rb_node_desc, parent, p);
	rb_insert_color(&new_ref->rb_node_desc, &proc->refs_by_desc);

	binder_node_lock(node);
	hlist_add_head(&new_ref->node_entry, &node->refs);

	binder_debug(BINDER_DEBUG_INTERNAL_REFS,
		     "%d new ref %d desc %d for node %d\n",
		      proc->pid, new_ref->data.debug_id, new_ref->data.desc,
		      node->debug_id);
	binder_node_unlock(node);
	return new_ref;
}
4.5 把数据放到客户端的todo链表,唤醒客户端
static void binder_transaction(struct binder_proc *proc,
                               struct binder_thread *thread,
                               struct binder_transaction_data *tr, int reply,
                               binder_size_t extra_buffers_size)
{
        ......

        if (reply) {// 找到要回复的进程
                binder_inner_proc_lock(proc);
				in_reply_to = thread->transaction_stack;//从栈中取出binder_transaction,获得要回复给谁
				if (in_reply_to == NULL) {
					binder_inner_proc_unlock(proc);
					binder_user_error("%d:%d got reply transaction with no transaction stack\n",
							  proc->pid, thread->pid);
					return_error = BR_FAILED_REPLY;
					return_error_param = -EPROTO;
					return_error_line = __LINE__;
					goto err_empty_call_stack;
				}
				if (in_reply_to->to_thread != thread) {
					spin_lock(&in_reply_to->lock);
					binder_user_error("%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);
					spin_unlock(&in_reply_to->lock);
					binder_inner_proc_unlock(proc);
					return_error = BR_FAILED_REPLY;
					return_error_param = -EPROTO;
					return_error_line = __LINE__;
					in_reply_to = NULL;
					goto err_bad_call_stack;
				}
				thread->transaction_stack = in_reply_to->to_parent;//出栈
				binder_inner_proc_unlock(proc);
				binder_set_nice(in_reply_to->saved_priority);
				target_thread = binder_get_txn_from_and_acq_inner(in_reply_to);
				if (target_thread == NULL) {
					/* annotation for sparse */
					__release(&target_thread->proc->inner_lock);
					binder_txn_error("%d:%d reply target not found\n",
						thread->pid, proc->pid);
					return_error = BR_DEAD_REPLY;
					return_error_line = __LINE__;
					goto err_dead_binder;
				}
				if (target_thread->transaction_stack != in_reply_to) {
					binder_user_error("%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);
					binder_inner_proc_unlock(target_thread->proc);
					return_error = BR_FAILED_REPLY;
					return_error_param = -EPROTO;
					return_error_line = __LINE__;
					in_reply_to = NULL;
					target_thread = NULL;
					goto err_dead_binder;
				}
				// 找到要回复的进程
				target_proc = target_thread->proc;
				target_proc->tmp_ref++;
				binder_inner_proc_unlock(target_thread->proc);
        } else {// 1. 找到要发送的目的进程
                ......
        }
        if (target_thread)
                e->to_thread = target_thread->pid;
        e->to_proc = target_proc->pid;

        /* TODO: reuse incoming transaction for reply */
        // 为binder_transcation分配内存
        t = kzalloc(sizeof(*t), GFP_KERNEL);
        
        .....

        if (!reply && !(tr->flags & TF_ONE_WAY))
                t->from = thread;
        else
                t->from = NULL;
        // 存储发送双方的基本信息
        t->from_pid = proc->pid;
        t->from_tid = thread->pid;
        t->sender_euid = task_euid(proc->tsk);
        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_new_buf(&target_proc->alloc, tr->data_size,
                tr->offsets_size, extra_buffers_size,
                !reply && (t->flags & TF_ONE_WAY));
        ......
        
        t->buffer->debug_id = t->debug_id;
        t->buffer->transaction = t;
        t->buffer->target_node = target_node;
        t->buffer->clear_on_free = !!(t->flags & TF_CLEAR_BUF);
        trace_binder_transaction_alloc_buf(t->buffer);
        
        // 把客户端的数据拷贝到目的进程test_client mmap的内存空间
        if (binder_alloc_copy_user_to_buffer(
                                &target_proc->alloc,
                                t->buffer,
                                ALIGN(tr->data_size, sizeof(void *)),
                                (const void __user *)
                                        (uintptr_t)tr->data.ptr.offsets,
                                tr->offsets_size)) {
                binder_user_error("%d:%d got transaction with invalid offsets ptr\n",
                                proc->pid, thread->pid);
                return_error = BR_FAILED_REPLY;
                return_error_param = -EFAULT;
                return_error_line = __LINE__;
                goto err_copy_data_failed;
        }
        ......
		
		//处理server传入的binder_io.offs数据,这个数据指向用于构建binder_node实体的		flat_binder_object
		for (buffer_offset = off_start_offset; buffer_offset < off_end_offset;
		     buffer_offset += sizeof(binder_size_t)) {
			struct binder_object_header *hdr;
			size_t object_size;
			struct binder_object object;
			binder_size_t object_offset;
			binder_size_t copy_size;
	
			if (binder_alloc_copy_from_buffer(&target_proc->alloc,
							  &object_offset,
							  t->buffer,
							  buffer_offset,
							  sizeof(object_offset))) {
				binder_txn_error("%d:%d copy offset from buffer failed\n",
					thread->pid, proc->pid);
				return_error = BR_FAILED_REPLY;
				return_error_param = -EINVAL;
				return_error_line = __LINE__;
				goto err_bad_offset;
			}
	
			/*
			 * Copy the source user buffer up to the next object
			 * that will be processed.
			 */
			copy_size = object_offset - user_offset;
			if (copy_size && (user_offset > object_offset ||
					binder_alloc_copy_user_to_buffer(
						&target_proc->alloc,
						t->buffer, user_offset,
						user_buffer + user_offset,
						copy_size))) {
				binder_user_error("%d:%d got transaction with invalid data ptr\n",
						proc->pid, thread->pid);
				return_error = BR_FAILED_REPLY;
				return_error_param = -EFAULT;
				return_error_line = __LINE__;
				goto err_copy_data_failed;
			}
			// 将指向flat_binder_object的指针拷贝给object
			object_size = binder_get_object(target_proc, user_buffer,
					t->buffer, object_offset, &object);
			if (object_size == 0 || object_offset < off_min) {
				binder_user_error("%d:%d got transaction with invalid offset (%lld, min %lld max %lld) or object.\n",
						  proc->pid, thread->pid,
						  (u64)object_offset,
						  (u64)off_min,
						  (u64)t->buffer->data_size);
				return_error = BR_FAILED_REPLY;
				return_error_param = -EINVAL;
				return_error_line = __LINE__;
				goto err_bad_offset;
			}
			/*
			 * Set offset to the next buffer fragment to be
			 * copied
			 */
			user_offset = object_offset + object_size;
	
			hdr = &object.hdr;
			off_min = object_offset + object_size;
			// 此处 binder类型的是BINDER_TYPE_HANDLE,通过handle在service_manager的binder-ref中找到hello服务的binder_node
			switch (hdr->type) {
			//处理binder实体
			case BINDER_TYPE_BINDER:
			case BINDER_TYPE_WEAK_BINDER: {
				......
				
			} break;
			//处理binder引用
			case BINDER_TYPE_HANDLE:
			case BINDER_TYPE_WEAK_HANDLE: {
				struct flat_binder_object *fp;
	
				fp = to_flat_binder_object(hdr);
				ret = binder_translate_handle(fp, t, thread);
				if (ret < 0 ||
				    binder_alloc_copy_to_buffer(&target_proc->alloc,
								t->buffer,
								object_offset,
								fp, sizeof(*fp))) {
					binder_txn_error("%d:%d translate handle failed\n",
						thread->pid, proc->pid);
					return_error = BR_FAILED_REPLY;
					return_error_param = ret;
					return_error_line = __LINE__;
					goto err_translate_failed;
				}
			} break;
			......
	 }
	......
	t->work.type = BINDER_WORK_TRANSACTION;

	if (reply) {
		binder_enqueue_thread_work(thread, tcomplete);
		binder_inner_proc_lock(target_proc);
		if (target_thread->is_dead) {
			return_error = BR_DEAD_REPLY;
			binder_inner_proc_unlock(target_proc);
			goto err_dead_proc_or_thread;
		}
		BUG_ON(t->buffer->async_transaction != 0);
		binder_pop_transaction_ilocked(target_thread, in_reply_to);//再次出栈
		// 将数据放到客户端target_thread的todo链表
		binder_enqueue_thread_work_ilocked(target_thread, &t->work);
		target_proc->outstanding_txns++;
		binder_inner_proc_unlock(target_proc);
		// 唤醒客户端
		wake_up_interruptible_sync(&target_thread->wait);
		binder_free_transaction(in_reply_to);
	} else if (!(t->flags & TF_ONE_WAY)) {
		......
	} else {
		......
	}
	if (target_thread)
		binder_thread_dec_tmpref(target_thread);
	binder_proc_dec_tmpref(target_proc);
	if (target_node)
		binder_dec_node_tmpref(target_node);
	/*
	 * write barrier to synchronize with initialization
	 * of log entry
	 */
	smp_wmb();
	WRITE_ONCE(e->debug_id_done, t_debug_id);
	return;
	......
}

static void
binder_enqueue_thread_work_ilocked(struct binder_thread *thread,
				   struct binder_work *work)
{
	WARN_ON(!list_empty(&thread->waiting_thread_node));
	binder_enqueue_work_ilocked(work, &thread->todo);

	/* (e)poll-based threads require an explicit wakeup signal when
	 * queuing their own work; they rely on these events to consume
	 * messages without I/O block. Without it, threads risk waiting
	 * indefinitely without handling the work.
	 */
	if (thread->looper & BINDER_LOOPER_STATE_POLL &&
	    thread->pid == current->pid && !thread->process_todo)
		wake_up_interruptible_sync(&thread->wait);

	thread->process_todo = true;
}

static void
binder_enqueue_work_ilocked(struct binder_work *work,
			   struct list_head *target_list)
{
	BUG_ON(target_list == NULL);
	BUG_ON(work->entry.next && !list_empty(&work->entry));
	list_add_tail(&work->entry, target_list);
}

2.4 客户端被唤醒,获取客户端binder_ref对应的handle

handle = svcmgr_lookup(bs, svcmgr, "hello");

uint32_t svcmgr_lookup(struct binder_state *bs, uint32_t target, const char *name)
{
    uint32_t handle;
    unsigned iodata[512/4];
    struct binder_io msg, reply;

    bio_init(&msg, iodata, sizeof(iodata), 4);
    bio_put_uint32(&msg, 0);  // strict mode header
    bio_put_string16_x(&msg, SVC_MGR_NAME);
    bio_put_string16_x(&msg, name);
    
    // ioctl到内核处理
    if (binder_call(bs, &msg, &reply, target, SVC_MGR_CHECK_SERVICE))
        return 0;
    
    // 获取引用服务binder_node的客户端binder_ref的handle
    handle = bio_get_ref(&reply);

    if (handle)
        binder_acquire(bs, handle);

    binder_done(bs, &msg, &reply);

    return handle;
}

uint32_t bio_get_ref(struct binder_io *bio)
{
    struct flat_binder_object *obj;

    obj = _bio_get_obj(bio);
    if (!obj)
        return 0;

    if (obj->type == BINDER_TYPE_HANDLE)
        return obj->handle;

    return 0;
}

3 服务注册和获取过程的简要总结图

在这里插入图片描述

二、服务的使用过程内核源码解析

上面我们通过源码分析,获得了客户端想要使用的服务的handle,下面我们接着分析,如何使用该服务。

1. 服务使用过程思路

有了之前Binder源码阅读的经验,我们直接看服务使用的思路,应该很容易能够理解,我们基于这个思路进行分析源码,也更容易理解源码。
在这里插入图片描述

2. 客户端使用服务内核源码解析

2.1 向服务端发送数据

int main(int argc, char **argv)
{
    int fd;
    struct binder_state *bs;
    uint32_t svcmgr = BINDER_SERVICE_MANAGER;
    uint32_t handle;
	int ret;

	if (argc < 2){
        fprintf(stderr, "Usage:\n");
        fprintf(stderr, "%s <hello|goodbye>\n", argv[0]);
        fprintf(stderr, "%s <hello|goodbye> <name>\n", argv[0]);
        return -1;
	}
    
    //打开驱动
    bs = binder_open(128*1024);
    if (!bs) {
        fprintf(stderr, "failed to open binder driver\n");
        return -1;
    }
	g_bs = bs;
    
    //向service_manager发送数据,获得hello服务句柄
	handle = svcmgr_lookup(bs, svcmgr, "hello");
	if (!handle) {
        fprintf(stderr, "failed to get hello service\n");
        return -1;
	}
	g_hello_handle = handle;
	fprintf(stderr, "Handle for hello service = %d\n", g_hello_handle);

	/* 向服务端发送数据 */
	if (!strcmp(argv[1], "hello"))
	{
		if (argc == 2) {
			sayhello();
		} else if (argc == 3) {
			ret = sayhello_to(argv[2]);
	        fprintf(stderr, "get ret of sayhello_to = %d\n", ret);		
		}
	}

	binder_release(bs, handle);

    return 0;
}
1. sayhello_to

以调用服务端的sayhello_to函数为例,分析客户端使用服务的过程

int sayhello_to(char *name)
{
	unsigned iodata[512/4];
	struct binder_io msg, reply;
	int ret;
	int exception;

	/* 构造binder_io */
	bio_init(&msg, iodata, sizeof(iodata), 4);
	bio_put_uint32(&msg, 0);  // strict mode header
    bio_put_string16_x(&msg, "IHelloService");

	/* 放入参数 */
    bio_put_string16_x(&msg, name);

	/* 调用binder_call
	msg:客户端的数据
	reply:携带服务端返回的数据
	g_hello_handle:服务端进程的handle
	HELLO_SVR_CMD_SAYHELLO_TO:要调用的服务端提供的服务
	 */
	if (binder_call(g_bs, &msg, &reply, g_hello_handle, HELLO_SVR_CMD_SAYHELLO_TO))
		return 0;
	
	/* 从reply中解析出返回值 */
	exception = bio_get_uint32(&reply);
	if (exception)
		ret = -1;
	else
		ret = bio_get_uint32(&reply);

	binder_done(g_bs, &msg, &reply);

	return ret;
	
}
2. binder_call

binder_call函数,已经分析很多遍了,这里不再详细分析,贴下代码

int binder_call(struct binder_state *bs,
                struct binder_io *msg, struct binder_io *reply,
                uint32_t target, uint32_t code)
{
    int res;
    struct binder_write_read bwr;
    struct {
        uint32_t cmd;
        struct binder_transaction_data txn;
    } __attribute__((packed)) writebuf;
    unsigned readbuf[32];

    if (msg->flags & BIO_F_OVERFLOW) {
        fprintf(stderr,"binder: txn buffer overflow\n");
        goto fail;
    }

    writebuf.cmd = BC_TRANSACTION;//ioclt类型
    writebuf.txn.target.handle = target;//数据发送给哪个进程
    writebuf.txn.code = code;//调用进程的哪个函数
    writebuf.txn.flags = 0;
    writebuf.txn.data_size = msg->data - msg->data0;//数据本身大小
    writebuf.txn.offsets_size = ((char*) msg->offs) - ((char*) msg->offs0);//数据头大小,指向binder_node实体(发送端提供服务函数的地址),bio_put_obj(&msg, ptr);
    writebuf.txn.data.ptr.buffer = (uintptr_t)msg->data0;//指向数据本身内存起点
    writebuf.txn.data.ptr.offsets = (uintptr_t)msg->offs0;//指向数据头内存起点

    bwr.write_size = sizeof(writebuf);
    bwr.write_consumed = 0;
    bwr.write_buffer = (uintptr_t) &writebuf;

    hexdump(msg->data0, msg->data - msg->data0);
    for (;;) {
        bwr.read_size = sizeof(readbuf);
        bwr.read_consumed = 0;
        bwr.read_buffer = (uintptr_t) readbuf;

        res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);//调用ioctl发送数据给驱动程序

        if (res < 0) {
            fprintf(stderr,"binder: ioctl failed (%s)\n", strerror(errno));
            goto fail;
        }

        res = binder_parse(bs, reply, (uintptr_t) readbuf, bwr.read_consumed, 0);
        if (res == 0) return 0;
        if (res < 0) goto fail;
    }

fail:
    memset(reply, 0, sizeof(*reply));
    reply->flags |= BIO_F_IOERROR;
    return -1;
}
3. binder_ioctl

用户态的ioctl调用到内核Binder驱动程序binder_ioctl函数,这个函数也分析很多遍了,相信看到这儿的博友,对这些函数已经很熟悉了。

// res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);进入binder驱动程序
static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
	int ret;
	struct binder_proc *proc = filp->private_data;
	struct binder_thread *thread;
	void __user *ubuf = (void __user *)arg;

	/*pr_info("binder_ioctl: %d:%d %x %lx\n",
			proc->pid, current->pid, cmd, arg);*/

	binder_selftest_alloc(&proc->alloc);

	trace_binder_ioctl(cmd, arg);

	ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);
	if (ret)
		goto err_unlocked;

	//为进程proc创建binder_thread
	thread = binder_get_thread(proc);
	if (thread == NULL) {
		ret = -ENOMEM;
		goto err;
	}

	switch (cmd) {
	case BINDER_WRITE_READ:
		ret = binder_ioctl_write_read(filp, arg, thread);
		if (ret)
			goto err;
		break;
		......
	}
	......
}
4. binder_ioctl_write_read
static int binder_ioctl_write_read(struct file *filp, unsigned long arg,
				struct binder_thread *thread)
{
	int ret = 0;
	struct binder_proc *proc = filp->private_data;
	void __user *ubuf = (void __user *)arg;
	struct binder_write_read bwr;

    //从用户空间拷贝数据到内核空间(这部分内核空间被mmap映射到了目标进程)
	if (copy_from_user(&bwr, ubuf, sizeof(bwr))) {
		ret = -EFAULT;
		goto out;
	}
	binder_debug(BINDER_DEBUG_READ_WRITE,
		     "%d:%d write %lld at %016llx, read %lld at %016llx\n",
		     proc->pid, thread->pid,
		     (u64)bwr.write_size, (u64)bwr.write_buffer,
		     (u64)bwr.read_size, (u64)bwr.read_buffer);

	if (bwr.write_size > 0) {
		ret = binder_thread_write(proc, thread,
					  bwr.write_buffer,
					  bwr.write_size,
					  &bwr.write_consumed);
		trace_binder_write_done(ret);
		if (ret < 0) {
			bwr.read_consumed = 0;
			if (copy_to_user(ubuf, &bwr, sizeof(bwr)))
				ret = -EFAULT;
			goto out;
		}
	}
	if (bwr.read_size > 0) {
		......
	}
	binder_debug(BINDER_DEBUG_READ_WRITE,
		     "%d:%d wrote %lld of %lld, read return %lld of %lld\n",
		     proc->pid, thread->pid,
		     (u64)bwr.write_consumed, (u64)bwr.write_size,
		     (u64)bwr.read_consumed, (u64)bwr.read_size);
	if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {
		ret = -EFAULT;
		goto out;
	}
out:
	return ret;
}
5. binder_thread_write
static int binder_thread_write(struct binder_proc *proc,
                        struct binder_thread *thread,
                        binder_uintptr_t binder_buffer, size_t size,
                        binder_size_t *consumed)
{
        uint32_t cmd;
        struct binder_context *context = proc->context;
        // 获取数据buffer,根据上面总结的发送数据可知,这个buffer由cmd和binder_transcation_data两部分数据组成
        void __user *buffer = (void __user *)(uintptr_t)binder_buffer;
        // 发送来的数据consumed=0,因此ptr指向用户空间数据buffer的起点
        void __user *ptr = buffer + *consumed;
        // 指向数据buffer的末尾
        void __user *end = buffer + size;
        // 逐个读取客户端发送来的数据(cmd+binder_transcation_data)
        while (ptr < end && thread->return_error.cmd == BR_OK) {
                int ret;
                
                // 获取用户空间中buffer的cmd值
                if (get_user(cmd, (uint32_t __user *)ptr))
                        return -EFAULT;
                // 移动指针到cmd的位置之后,指向binder_transcation_data数据的内存起点
                ptr += sizeof(uint32_t);
                trace_binder_command(cmd);
                if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.bc)) {
                        atomic_inc(&binder_stats.bc[_IOC_NR(cmd)]);
                        atomic_inc(&proc->stats.bc[_IOC_NR(cmd)]);
                        atomic_inc(&thread->stats.bc[_IOC_NR(cmd)]);
                }
                // 根据上面总结的发送数据可知,cmd是BC_TRANSACTION
                switch (cmd) {
                   ......
                   /*
                BC_TRANSACTION:进程发送信息的cmd
                BR_TRANSACTION:进程接收BC_TRANSACTION发送信息的cmd
                
                BC_REPLY:进程回复信息的cmd
                BR_REPLY:进程接收BC_REPLY回复信息的cmd
                */
                    case BC_TRANSACTION:
                    case BC_REPLY: {
                            struct binder_transaction_data tr;
                            
                            // 从用户空间拷贝binder_transaction_data到内核空间
                            if (copy_from_user(&tr, ptr, sizeof(tr)))
                                    return -EFAULT;
                            // 移动指针到binder_transaction_data的位置之后,指向下一个cmd数据的内存起点
                            ptr += sizeof(tr);
                            // 处理binder_transaction_data数据
                            binder_transaction(proc, thread, &tr,
                                               cmd == BC_REPLY, 0);
                            break;
                    }
                }
        }
        ......
}

int get_user(int *val, const int __user *ptr) {
    if (copy_from_user(val, ptr, sizeof(int))) {
        return -EFAULT; // 返回错误码
    }
    return 0; // 成功
}
6. binder_transaction

这个函数也分析了很多很多遍了,这里简要分析下

static void binder_transaction(struct binder_proc *proc,
			       struct binder_thread *thread,
			       struct binder_transaction_data *tr, int reply,
			       binder_size_t extra_buffers_size)
{
	int ret;
	struct binder_transaction *t;
	struct binder_work *w;
	struct binder_work *tcomplete;
	binder_size_t buffer_offset = 0;
	binder_size_t off_start_offset, off_end_offset;
	binder_size_t off_min;
	binder_size_t sg_buf_offset, sg_buf_end_offset;
	binder_size_t user_offset = 0;
	struct binder_proc *target_proc = NULL;
	struct binder_thread *target_thread = NULL;
	struct binder_node *target_node = NULL;
	struct binder_transaction *in_reply_to = NULL;
	struct binder_transaction_log_entry *e;
	uint32_t return_error = 0;
	uint32_t return_error_param = 0;
	uint32_t return_error_line = 0;
	binder_size_t last_fixup_obj_off = 0;
	binder_size_t last_fixup_min_off = 0;
	struct binder_context *context = proc->context;
	int t_debug_id = atomic_inc_return(&binder_last_id);
	ktime_t t_start_time = ktime_get();
	char *secctx = NULL;
	u32 secctx_sz = 0;
	struct list_head sgc_head;
	struct list_head pf_head;
	// 客户端发送来的数据buffer
	const void __user *user_buffer = (const void __user *)
				(uintptr_t)tr->data.ptr.buffer;
	INIT_LIST_HEAD(&sgc_head);
	INIT_LIST_HEAD(&pf_head);

	e = binder_transaction_log_add(&binder_transaction_log);
	e->debug_id = t_debug_id;
	e->call_type = reply ? 2 : !!(tr->flags & TF_ONE_WAY);
	e->from_proc = proc->pid;
	e->from_thread = thread->pid;
	e->target_handle = tr->target.handle;
	e->data_size = tr->data_size;
	e->offsets_size = tr->offsets_size;
	strscpy(e->context_name, proc->context->name, BINDERFS_MAX_NAME);

	binder_inner_proc_lock(proc);
	binder_set_extended_error(&thread->ee, t_debug_id, BR_OK, 0);
	binder_inner_proc_unlock(proc);

	if (reply) {//找到要回复的进程
		......
	} else {
	    //1. 找到要发送的目的进程
		if (tr->target.handle) {// tr->target.handle == 0 代表是service_manager进程,否则是其它进程
			struct binder_ref *ref;

			/*
			 * There must already be a strong ref
			 * on this node. If so, do a strong
			 * increment on the node to ensure it
			 * stays alive until the transaction is
			 * done.
			 */
			binder_proc_lock(proc);
			//根据客户端发送来的handle找到获取binder_ref
			ref = binder_get_ref_olocked(proc, tr->target.handle,
						     true);
			if (ref) {
			    // 根据binder_ref拿到目的进程的binder_node和binder_proc
				target_node = binder_get_node_refs_for_txn(
						ref->node, &target_proc,
						&return_error);
			} else {
				binder_user_error("%d:%d got transaction to invalid handle, %u\n",
						  proc->pid, thread->pid, tr->target.handle);
				return_error = BR_FAILED_REPLY;
			}
			binder_proc_unlock(proc);
		} else {
		    //处理service_manager进程
			......
		}
		
		......
		
		binder_inner_proc_unlock(proc);
	}
	
	......
	
	t->work.type = BINDER_WORK_TRANSACTION;
    if (reply) {
		......
	} else if (!(t->flags & TF_ONE_WAY)) {
		BUG_ON(t->buffer->async_transaction != 0);
		binder_inner_proc_lock(proc);
		/*
		 * Defer the TRANSACTION_COMPLETE, so we don't return to
		 * userspace immediately; this allows the target process to
		 * immediately start processing this transaction, reducing
		 * latency. We will then return the TRANSACTION_COMPLETE when
		 * the target replies (or there is an error).
		 */
		binder_enqueue_deferred_thread_work_ilocked(thread, tcomplete);
		t->need_reply = 1;
		t->from_parent = thread->transaction_stack;
		//入栈
		thread->transaction_stack = t;
		binder_inner_proc_unlock(proc);
		//将数据放入目的进程的binder_proc或binder_thread,并唤醒目的进程
		return_error = binder_proc_transaction(t,
				target_proc, target_thread);
		if (return_error) {
			binder_inner_proc_lock(proc);
			binder_pop_transaction_ilocked(thread, t);
			binder_inner_proc_unlock(proc);
			goto err_dead_proc_or_thread;
		}
	} else {
		......
	}

2.2 服务端被被唤醒,处理客户端发送的数据

服务端的binder_loop函数中有一个死循环,一直在等待数据,现在数据来了,可以开始读取和处理数据了

int main(int argc, char **argv)
{
    int fd;
    struct binder_state *bs;
    uint32_t svcmgr = BINDER_SERVICE_MANAGER;
    uint32_t handle;
	int ret;

    bs = binder_open(128*1024);
    if (!bs) {
        fprintf(stderr, "failed to open binder driver\n");
        return -1;
    }

	/* add service */
	ret = svcmgr_publish(bs, svcmgr, "hello", hello_service_handler);
    if (ret) {
        fprintf(stderr, "failed to publish hello service\n");
        return -1;
    }
	ret = svcmgr_publish(bs, svcmgr, "goodbye", goodbye_service_handler);
    if (ret) {
        fprintf(stderr, "failed to publish goodbye service\n");
    }

#if 0
	while (1)
	{
		/* read data */
		/* parse data, and process */
		/* reply */
	}
#endif

	binder_set_maxthreads(bs, 10);
    
    // 死循环等待读取客户端发送来的数据
    binder_loop(bs, test_server_handler);

    return 0;
}

void binder_loop(struct binder_state *bs, binder_handler func)
{
    int res;
    struct binder_write_read bwr;
    uint32_t readbuf[32];

    bwr.write_size = 0;
    bwr.write_consumed = 0;
    bwr.write_buffer = 0;

    readbuf[0] = BC_ENTER_LOOPER;
    binder_write(bs, readbuf, sizeof(uint32_t));
     
    // 死循环等待读取客户端的数据
    for (;;) {
        bwr.read_size = sizeof(readbuf);
        bwr.read_consumed = 0;
        bwr.read_buffer = (uintptr_t) readbuf;
        // 读取客户端发送来的数据(这个内核源码过程和上面service_manager被唤醒后的过程一样,不再赘述)
        res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);

        if (res < 0) {
            ALOGE("binder_loop: ioctl failed (%s)\n", strerror(errno));
            break;
        }
        // 解析客户端发送来的数据
        res = binder_parse(bs, 0, (uintptr_t) readbuf, bwr.read_consumed, func);
        if (res == 0) {
            ALOGE("binder_loop: unexpected reply?!\n");
            break;
        }
        if (res < 0) {
            ALOGE("binder_loop: io error %d %s\n", res, strerror(errno));
            break;
        }
    }
}

int binder_parse(struct binder_state *bs, struct binder_io *bio,
                 uintptr_t ptr, size_t size, binder_handler func)
{
    int r = 1;
    uintptr_t end = ptr + (uintptr_t) size;

    while (ptr < end) {
        uint32_t cmd = *(uint32_t *) ptr;
        ptr += sizeof(uint32_t);
#if TRACE
        fprintf(stderr,"%s:\n", cmd_name(cmd));
#endif
        switch(cmd) {
        ......
        case BR_TRANSACTION: {
            struct binder_transaction_data *txn = (struct binder_transaction_data *) ptr;
            if ((end - ptr) < sizeof(*txn)) {
                ALOGE("parse: txn too small!\n");
                return -1;
            }
            binder_dump_txn(txn);
            if (func) {
                unsigned rdata[256/4];
                struct binder_io msg;
                struct binder_io reply;
                int res;

                bio_init(&reply, rdata, sizeof(rdata), 4);
                bio_init_from_txn(&msg, txn);
                // 这里的msg就是客户端发送来的数据,func是服务端的函数test_server_handler
                res = func(bs, txn, &msg, &reply);
                binder_send_reply(bs, &reply, txn->data.ptr.buffer, res);
            }
            ptr += sizeof(*txn);
            break;
        }
        ......
        }
    }

    return r;
}

int test_server_handler(struct binder_state *bs,
                   struct binder_transaction_data *txn,
                   struct binder_io *msg,
                   struct binder_io *reply)
{
	int (*handler)(struct binder_state *bs,
                   struct binder_transaction_data *txn,
                   struct binder_io *msg,
                   struct binder_io *reply);

	handler = (int (*)(struct binder_state *bs,
                   struct binder_transaction_data *txn,
                   struct binder_io *msg,
                   struct binder_io *reply))txn->target.ptr; // 服务端的函数指针,在向service_manager注册服务的时候写入的,此处是hello_service_handler
	
	return handler(bs, txn, msg, reply);
}

int hello_service_handler(struct binder_state *bs,
                   struct binder_transaction_data *txn,
                   struct binder_io *msg,
                   struct binder_io *reply)
{
	/* 根据txn->code知道要调用哪一个函数
	 * 如果需要参数, 可以从msg取出
	 * 如果要返回结果, 可以把结果放入reply
	 */

	/* sayhello
	 * sayhello_to
	 */
	
    uint16_t *s;
	char name[512];
    size_t len;
    uint32_t handle;
    uint32_t strict_policy;
	int i;


    // Equivalent to Parcel::enforceInterface(), reading the RPC
    // header with the strict mode policy mask and the interface name.
    // Note that we ignore the strict_policy and don't propagate it
    // further (since we do no outbound RPCs anyway).
    strict_policy = bio_get_uint32(msg);


    switch(txn->code) {
    case HELLO_SVR_CMD_SAYHELLO:
		sayhello();
		bio_put_uint32(reply, 0); /* no exception */
        return 0;

    case HELLO_SVR_CMD_SAYHELLO_TO:
		/* 从msg里取出字符串 */
		s = bio_get_string16(msg, &len);  //"IHelloService"
		s = bio_get_string16(msg, &len);  // name
		if (s == NULL) {
			return -1;
		}
		for (i = 0; i < len; i++)
			name[i] = s[i];
		name[i] = '\0';

		/* 调用服务函数处理客户端的数据 */
		i = sayhello_to(name);

		/* 把结果放入reply */
		bio_put_uint32(reply, 0); /* no exception */
		bio_put_uint32(reply, i);
		
        break;

    default:
        fprintf(stderr, "unknown code %d\n", txn->code);
        return -1;
    }

    return 0;
}

2.3 客户端收到服务端处理的数据

从reply中获取服务端处理后的数据

int sayhello_to(char *name)
{
	unsigned iodata[512/4];
	struct binder_io msg, reply;
	int ret;
	int exception;

	/* 构造binder_io */
	bio_init(&msg, iodata, sizeof(iodata), 4);
	bio_put_uint32(&msg, 0);  // strict mode header
    bio_put_string16_x(&msg, "IHelloService");

	/* 放入参数 */
    bio_put_string16_x(&msg, name);

	/* 调用binder_call */
	if (binder_call(g_bs, &msg, &reply, g_hello_handle, HELLO_SVR_CMD_SAYHELLO_TO))
		return 0;
	
	/* 从reply中解析出返回值 */
	exception = bio_get_uint32(&reply);
	if (exception)
		ret = -1;
	else
		ret = bio_get_uint32(&reply);

	binder_done(g_bs, &msg, &reply);

	return ret;
	
}

三、后记

自此,我们通过三篇文章完成了Binder跨进程通信的源码分析,我们深入内核去分析Binder跨进程通信实现的源码,相信通过这三篇文章,我们已经非常深入地理解了Binder跨进程通信的实现方案。其实内核的源码我们只是分析了大概,更加细节的源码没有深入分析,但我相信有了现在的基础,我们再独立去更深入的分析内核源码,应该会轻松不少,至少不会像无头苍蝇一下,无从下手。

说实话,Android Binder的内核源码分析,我自认为写的不是很好,还有很多改善空间,还有很多没有讲清楚的地方,后面我也会不断加强自己的技术能力,希望未来有一天,我会再重新写一篇更加通俗易懂的Binder驱动内核源码分析。

深入内核讲明白Android Binder【一】 本文基于C语言实现Binder跨进程通信Demo,并对Demo的源码进行解析。通过本文可以从用户空间彻底理解Binder跨进程通信的原理和应用。 阅读详情

相关推荐

手写一个C++ Android Binder服务及源码分析

本篇文章介绍如何使用C++语言编写自己的binder服务,并对binder服务源码进行分析。通过阅读本篇文章,你可以灵活的编写自己的android binder服务,也帮助你阅读android源码中一系列系统binder服务。

Mekeater的博客 2012

Android跨进程通信:图文详解 Binder机制 原理

前言 如果你接触过 跨进程通信 (IPC),那么你对Binder一定不陌生 虽然 网上有很多介绍 Binder的文章,可是存在一些问题:浅显的讨论Binder机制 或 一味讲解 Binder源码、逻辑不清楚,最终导致的是读者们还是无法形成一个完整的Binder概念 本文采用 清晰的图文讲解方式,按照 大角度 -&gt; 小角度 去分析Binder,即: 先从 机制、模型的角度 去分析 整个B...

Carson带你学Android 14万+

理解 Android Binder 机制(一):驱动篇

转载: 理解 Android Binder 机制(一):驱动篇 目录Binder机制简介整体架构初识ServiceManager主要结构Binder协议 Binder的实现是比较复杂的,想要完全弄明白是怎么一回事,并不是一件容易的事情。 这里面牵涉到好几个层次,每一层都有一些模块和机制需要理解。 这部分内容预计会分为三篇文章来讲解。本文是第一篇,首先会对整个Binder机制做一个架构性的讲解,然后会将大部分精力用来讲解Binder机制中最核心的部分:Binder驱动的实现。 Binder机制简介 Binde

做有意思的事情 3093

android中的Binder(android内核学习记录)

1、Binder概述Binder,英文的意思是别针,回形针。表面意思是可以把一些东西“绑”在一起。在android中Binder用于完成进程间的通信(IPC),即把多个进程“别”在一起。比如,普通应用程序可以调用音乐播放服务生提供播放、暂停、停止的功能。Binder工作在Linux层面,属于一个驱动,只中这个驱动不需要硬件,或者说操作的硬件属于一小段内存。从线程角度上讲,Binder驱动代码运行在内

androidxiaogang的博客 802

知识图谱初步学习(一)——本体+Protege新手学习

文章目录前言(本体详解)1.本体概念2.本体分类3.本体组成4.本体构建方法一、protege简介二、软件使用步骤1.安装2.使用三、问题解决方案汇总 前言(本体详解) 在开始学习知识图谱的过程中,首先就是要了解什么是本体(ontology)。 1.本体概念 本体的概念最初源自于哲学领域,在哲学中的定义为“对世界上客观事物的系统描述,即存在论”。哲学中的本体关心的是客观现实的抽象本质。而在计算机领域,本体是可以在语义的层次上来对知识进行描述,可以看做是某一个领域知识的通用模型。 本体是从客观世界中抽象出来

qq_43654669的博客 3万+

基于WebGL架构的3D可视化平台—平面图导航(一)

前言 利用CampusBuilder来搭建自己的虚拟世界过程有这样一个问题:如何快速聚焦到虚拟场景的某一位置。当然我们可以创建几个按钮对应查找我们需要去的位置(参照物)并聚焦,但是按钮并不是很炫酷也不能很好的反馈给我们一些信息。接下来我们就用平面导航图来解决这一问题。 第一步:使用CampusBuilder搭建模拟场景,CampusBuilder操作简单,分分钟就可以上手。 ...

nioooom的博客 4171

Android进阶——Android跨进程通讯机制之Binder、IBinder、Parcel、AIDL

前言 Binder机制是Android系统提供的跨进程通讯机制,这篇文章开始会从Linux相关的基础概念知识开始介绍,从基础概念知识中引出Binder机制,归纳Binder机制与Linux系统的跨进程机制的优缺点,接着分析Binder的通信模型和原理,而Binder机制最佳体现就是AIDL,所以在后面会分析AIDL的实现原理,最后简单的提下AMS的Binder体系,整篇文章中间会穿插有IBind...

点击置顶文章查看博客目录(全站式导航) 2万+

初识YUV,实战NV21格式数据转换为Bitmap

初识YUV,并使用YUV数据生成Bitmap图像一、初识YUV二、采样方式2.1、YUV 4:4:42.2、YUV 4:2:22.2、YUV 4:2:2 一、初识YUV 说到YUV我们就必须先从RGB说起了,如下图所示,请各位把每个色块当成一个像素点。通常一个像素点由RGB(Alpha我们先不考虑)三原色组成。 如下图中第一个像素点,其RGB值分别为(236,102,93),而这三个值就组成了我们看到的 红色 。 然而上图中除了RGB值外,我还标出了每个像素点的YUV的值,YUV的值是怎么来的呢?直接给公

乐翁龙 7144

Android 内核--Binder架构分析

一、Binder架构   在Android中,Binder用于完成进程间通信(IPC),即把多个进程关联在一起。比如,普通应用程序可以调用音乐播放服务提供的播放、暂停、停止等功能。Binder工作在Linux层面,属于一个驱动,只是这个驱动不需要硬件,或者说其操作的硬件是基于一小段内存。从线程的角度来讲,Binder驱动代码运行在内核态,客户端程序调用Binder是通过系统调用完成的。   B...

weixin_33943347的博客 207

YOLOv12改进策略【Neck】| arXiv 2024 MAFPN:多分支辅助特征金字塔网络 | 通过双向辅助融合与异构卷积机制,解决传统PAFPN多尺度特征融合不充分与小目标检测不足问题

本文记录的是利用MAFPN颈部结构改进YOLOv12的目标检测网络模型。通过引入双向辅助融合机制优化特征处理流程,在自底向上路径利用 SAF 模块融合主干浅层特征与颈部输出,并保留浅层空间信息,为小目标检测提供更丰富细节;自顶向下路径通过 AAF 模块建立密集连接,聚合浅层高 / 低分辨率层、同级层及前层特征,均衡各层通道数后实现多向梯度信息交互,增强中 / 大目标特征表达。将其应用到中,解决传统特征金字塔在多尺度信息整合中的不足,提升多尺度目标检测的精度与特征表达的丰富性。Multi-Branch Aux

Limiiiing的博客 1270

Altium Designer (AD) 设计软件高频面试题及参考答案(3万字长文)

在Altium Designer(AD)中,设计复用是一种关键的策略,它允许设计师在多个项目中重复使用经过验证的设计元素,如原理图符号、PCB布局、元器件封装和设计规则集。在Altium Designer (AD) 中,手动布线和交互式布线是PCB设计中常见的两种布线模式,它们提供了设计师对布线路径的直接控制,特别是在处理复杂或关键信号路径时尤为有用。在Altium Designer (AD) 中进行电路级仿真是一项重要的设计验证步骤,它允许设计师在实际制造之前对电路的行为进行预测和分析。

大模型大数据攻城狮的专栏 4795

深入内核讲明白Android Binder【二】

本篇文章深入Linux内核,讲解Binder驱动程序中服务注册过程的内核源码

Mekeater的博客 917

点云生成图像

摘要:本文介绍了使用Open3D库将点云投影为RGBD图像的方法。通过project_to_rgbd_image函数,利用小孔相机模型的内参和外参矩阵,实现了点云到彩色图像和深度图的转换。实验使用随机生成的10万个点云数据,通过可视化窗口获取相机参数后,成功生成了对应的RGB图像和深度图像,并使用Matplotlib进行可视化展示。该方法为点云数据处理提供了有效的三维到二维投影方案。

夜空中明亮的星的专栏 139

Android Binder通信01 - 架构介绍

其实这个binder通信就像打电话一样,ServiceManager就相当于运营商,你去向运营商开卡,就相当于注册了服务,这个服务在运营商的网络中可能一直用一个电话卡的ip来标识,由于ip非常难记住,运行商就给起了一个friendly name(友好的名字),也就是电话号码;当你拨通电话号码的过程中,你的拨号软件可能会先去运营商问问,这个这个电话号码的handle(ip地址)是多少,我要发语音信号过去。然后就很好理解了。

Ziwubiancheng的博客 1597

VAY 是 SAP 自动科目确定(OBYC-GBB)中的科目修改码,专用于带科目分配对象的销售订单发货场景,核心是触发 “Dr 成本要素科目(如销售费用 / 特定成本对象) Cr 库存商品” 的分录,

摘要:VAY是SAP中用于带科目分配对象(如成本中心、WBS)的销售订单发货的科目修改码,与标准VAX场景不同,它生成"借成本要素科目/贷库存商品"的分录。配置路径为OBYC-GBB-VAY,需确保借方科目为成本要素。典型业务场景包括免费样品、项目专用发货等。常见问题包括VAY未触发或科目记账错误,需检查销售订单科目分配、移动类型设置及OBYC配置。特殊场景建议单独配置科目以便费用分析。

金牌架构师 1268

2026年软考高级网络规划设计师备考指南

在国家网络安全法律法规和政策的指导下,能够依据网络技术发展的趋势进行计算机网络领域的需求分析、规划设计、部署实施、评测、运行维护等工作。 在需求分析阶段,写出网络系统需求规格说明书;在规划设计阶段,完成逻辑结构设计、物理结构设计,选用适宜的网络设备,按照标准规范编写系统设计文档及项目开发计划;在部署实施阶段,组织项目施工,对项目实施过程进行质量控制、进度控制、成本管理,能具体指导项目实施;在评测运维阶段,能根据相关标准和规范对网络进行评估测试,能制定运行维护、故障分析与处理机制,确保网络提供正常服务;

鹿鸣天涯 1万+

不明白四大组件底层的通信机制是怎样的?写给Android应用工程师的Binder原理剖析!

现在我们可以对 Binder 做个更加全面的定义了:从进程间通信的角度看,Binder 是一种进程间通信的机制;从 Server 进程的角度看,Binder 指的是 Server 中的 Binder 实体对象;从 Client 进程的角度看,Binder 指的是对 Binder 代理对象,是 Binder 实体对象的一个远程代理从传输过程的角度看,Binder 是一个可以跨进程传输的对象;Binder 驱动会对这个跨越进程边界的对象对一点点特殊处理,自动完成代理对象和本地对象之间的转换。

m0_61549953的博客 950

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

Android中binder学习总结

Binder学习总结和SM中binder的使用 1、binder学习总结 1.1、binder驱动和相应的接口函数 1.1.1、java开发者看binder驱动设备 binder驱动和linux驱动一样,以misc设备进行注册,作为虚拟字符设备,没有直接操作硬件,只是对设备内存进行操作。上述话语可能在网上能够搜索,但是笔者在学习过程中一直对这句话有一个思考:对于一个只是java开发者,甚至没有接触过驱动开发的人怎么去理解这句话。 经过对binder的学习现在的我对这句话的理解是:binder设备虽然只是一种

weixin_42166217的博客 270

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

手写一个Java Android Binder服务及源码分析

本篇在讲解如何使用java语言编写自己的binder服务,并通过对代码的分析,深入了解java binder服务的实现机制。

Mekeater的博客 2113

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

大厂Android面试官亲讲:Binder 相关问题到底该怎样回答

我的一个朋友在某互联网大厂(Alibaba)的Android开发岗工作了五年,最近几次奉命去当面试官,面了不少应聘者,这是他吐槽的发生在面试中的一些事情。 原文地址:大厂Android面试官亲讲:Binder 相关问题到底该怎样回答 背景 我们搞技术的也没什么别的人脉圈子,平时也就哥几个吃个饭,喝个酒,吹个牛逼。 前阵子几个朋友小聚,大家喝了点酒就开始吹牛逼,他一边感叹了一下现在越来越少的休息时间一边说老板为什么还不给他转岗的机会,说着说着就开始感慨新来的那些员工。 “现在的这些应聘者,学历工作经验看着.

BUGgogogo的博客 393

Android细说binder机制

Android深入浅出之Binder机制一 说明 Android系统最常见最难搞明白的就是Binder了,很多很多的Service就是通过Binder机制来和客户端通讯交互的。所以搞明白Binder的话,在很大程度上就能理解程序运行的流程。 我们这里将以MediaService的例子来分析Binder的使用:l ServiceManager,这是Android OS的整个服务的管

成长的味道 1013

读安卓开发艺术探索和鸿洋博客有关于binder知识的笔记

首先贴上玉刚大神博客中安卓中binder的知识总结,如下就是玉刚大神的博客里面对进程间知识通信的总结: 摘要 Binder是android中一个很重要且很复杂的概念,它在系统的整体运作中发挥着极其重要的作用,不过本文并不打算从深层次分析Binder机制,有两点原因:1是目前网上已经有2篇很好的文章了,2是对Binder机制进行深入底层乃至驱动的分析这一过程相当困难且相当耗时,因此并

qq_21813505的博客 1035

如何快速搞定Anbox内核模块安装:ashmem与binder完整配置指南

在Linux上跑Android应用,Anbox是个绕不开的名字。它把Android装进容器里直接运行,不用忍受虚拟机的性能损耗,但前提是得先给内核"加装"两个特殊零件——ashmem和binder。这套安装配置,正是本文要带你走完的完整流程。 ## 先弄明白:这两个模块到底在干什么? 打比方说,你买了一台需要特殊发动机的汽车,发动机明明就在工具箱里,但车子出厂时偏偏没装。Anbox就是这辆车,

gitblog_00524的博客 518

android binder 传输文件,Android之Binder通信篇

Binder跨进程通信的本质是依赖内核驱动将属于不同Binder进程的数据,从原始进程复制到目标进程,这样就完成了跨进程通信了。好了就这些,简单吧?逗我玩全国人民都爱的毛爷爷说过一句至理名言:我们要从战略上藐视敌人,从战术上重视敌人!虽然Binder跨进程通信方式跟Linux系统其它跨进程通信方式一样,都是把数据从一个进程发送到另一个进程,但是在具体的实现方式必须独树一帜!Binder确实做到了。...

weixin_35242523的博客 554
上一篇: 深入内核讲明白Android Binder【二】
下一篇: 手写一个C++ Android Binder服务及源码分析
Mekeater
博客等级 码龄11年 1023粉丝 242原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mekeater

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值