本文参考《Android系统源代码情景分析》,作者罗升阳
一、测试代码:
~/Android/external/binder/server
----FregServer.cpp
~/Android/external/binder/common
----IFregService.cpp
----IFregService.h
~/Android/external/binder/client
----FregClient.cpp
Binder库(libbinder)代码:
~/Android/frameworks/base/libs/binder
----BpBinder.cpp
----Parcel.cpp
----ProcessState.cpp
----Binder.cpp
----IInterface.cpp
----IPCThreadState.cpp
----IServiceManager.cpp
----Static.cpp
~/Android/frameworks/base/include/binder
----Binder.h
----BpBinder.h
----IInterface.h
----IPCThreadState.h
----IServiceManager.h
----IBinder.h
----Parcel.h
----ProcessState.h
驱动层代码:
~/Android//kernel/goldfish/drivers/staging/android
----binder.c
----binder.h
~/Android//kernel/goldfish/drivers/staging/android
----binder.c
static intbinder_thread_read(struct binder_proc *proc, struct binder_thread *thread, void __user *buffer, int size, signed long *consumed, int non_block){ void __user *ptr = buffer + *consumed; void __user *end = buffer + size; int ret = 0; ......... while (1) { uint32_t cmd; struct binder_transaction_data tr; struct binder_work *w; struct binder_transaction *t = NULL; if (!list_empty(&thread->todo)) w = list_first_entry(&thread->todo, struct binder_work, entry); else if (!list_empty(&proc->todo) && wait_for_proc_work) w = list_first_entry(&proc->todo, struct binder_work, entry);//将要处理的工作项保存在binder_work结构体w中 else { if (ptr - buffer == 4 && !(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN)) /* no data added */ goto retry; break; } ........ switch (w->type) { case BINDER_WORK_TRANSACTION: { t = container_of(w, struct binder_transaction, work);//由于binder_work结构体w的类型为BINDER_WORK_TRANSACTION,即它是一个嵌入在一个binder_transaction结构体中的工作项,因此可以安全地将它转换为一个binder_transaction结构体t } break; ......... } if (!t) continue; BUG_ON(t->buffer == NULL); if (t->buffer->target_node) { struct binder_node *target_node = t->buffer->target_node; tr.target.ptr = target_node->ptr;//Binder实体对象ptr为NULL tr.cookie = target_node->cookie;//Binder实体对象cookie为NULL 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); cmd = BR_TRANSACTION;//cmd设置BR_TRANSACTION } else { ..... } tr.code = t->code;//ADD_SERVICE_TRANCATION tr.flags = t->flags;//TF_ACCEPTS_FDS tr.sender_euid = t->sender_euid; if (t->from) { struct task_struct *sender = t->from->proc->tsk; tr.sender_pid = task_tgid_nr_ns(sender, current->nsproxy->pid_ns); } else { ....... } tr.data_size = t->buffer->data_size;//数据缓冲区大小 tr.offsets_size = t->buffer->offsets_size;//偏移数组大小 tr.data.ptr.buffer = (void *)t->buffer->data + proc->user_buffer_offset;//内核缓冲区的内核空间地址和用户空间地址相差一个固定值,并且保存在它的成员变量user_buffer_offset中 tr.data.ptr.offsets = tr.data.ptr.buffer + ALIGN(t->buffer->data_size, sizeof(void *));//偏移保存在数据缓冲区的后面 if (put_user(cmd, (uint32_t __user *)ptr))//将命令返回 return -EFAULT; ptr += sizeof(uint32_t); if (copy_to_user(ptr, &tr, sizeof(tr)))//将binder_transaction_data结构体tr返回 return -EFAULT; ptr += sizeof(tr); ....... list_del(&t->work.entry);//删除该任务项 t->buffer->allow_user_free = 1;//允许释放 if (cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)) { t->to_parent = thread->transaction_stack; t->to_thread = thread; thread->transaction_stack = t; } else { t->buffer->transaction = NULL; kfree(t); ........ } break; }done: *consumed = ptr - buffer;//cmd和binder_transaction_data结构体tr大小之和 ........ return 0;}if语句首先检查线程thread自己的todo队列中是否有个工作项需要处理。如果没有,第19行的if语句再检查它所属进程proc的todo队列中是否有工作项需要处理。只要其中的一个todo队列中有工作项需要处理,函数binder_thread_read就将它取出来处理,并且保存在binder_work结构体w中。
void binder_loop(struct binder_state *bs, binder_handler func){ int res; struct binder_write_read bwr; unsigned readbuf[32]; bwr.write_size = 0; bwr.write_consumed = 0; bwr.write_buffer = 0; readbuf[0] = BC_ENTER_LOOPER;//首先将BC_ENTER_LOOPER协议写入缓冲区readbuf中 binder_write(bs, readbuf, sizeof(unsigned));//调用binder_write将它发送到Binder驱动程序中 for (;;) { bwr.read_size = sizeof(readbuf); bwr.read_consumed = 0; bwr.read_buffer = (unsigned) readbuf; res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);//bwr.write_size为0,bwr.read_size不为0 if (res < 0) { LOGE("binder_loop: ioctl failed (%s)\n", strerror(errno)); break; } res = binder_parse(bs, 0, readbuf, bwr.read_consumed, func);//此时readbuf为cmd和binder_transaction_data结构体tr,bwr.read_consumed为cmd和binder_transaction_data结构体tr大小之和 if (res == 0) { LOGE("binder_loop: unexpected reply?!\n"); break; } if (res < 0) { LOGE("binder_loop: io error %d %s\n", res, strerror(errno)); break; } }}开始执行binder_parse。实现如下:
int binder_parse(struct binder_state *bs, struct binder_io *bio, uint32_t *ptr, uint32_t size, binder_handler func){ int r = 1; uint32_t *end = ptr + (size / 4); while (ptr < end) { uint32_t cmd = *ptr++; ....... switch(cmd) {//cmd为BR_TRANSACTION ...... case BR_TRANSACTION: { struct binder_txn *txn = (void *) ptr;//binder_transaction_data结构体tr取出放到binder_txt结构体中 ........ if (func) {//svcmgr_handler函数指针 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); res = func(bs, txn, &msg, &reply);//svcmgr_handler函数指针 binder_send_reply(bs, &reply, txn->data, res); } ptr += sizeof(*txn) / sizeof(uint32_t); break; } ...... } return r;}在介绍binder_parse前,首先看几个结构体。
struct binder_object{ uint32_t type; uint32_t flags; void *pointer; void *cookie;};struct binder_txn{ void *target; void *cookie; uint32_t code; uint32_t flags; uint32_t sender_pid; uint32_t sender_euid; uint32_t data_size; uint32_t offs_size; void *data; void *offs;};struct binder_io //具体含义见英文注释{ char *data; /* pointer to read/write from */ uint32_t *offs; /* array of offsets */ uint32_t data_avail; /* bytes available in data buffer */ uint32_t offs_avail; /* entries available in offsets array */ char *data0; /* start of data buffer */ uint32_t *offs0; /* start of offsets buffer */ uint32_t flags; uint32_t unused;};
void bio_init(struct binder_io *bio, void *data, uint32_t maxdata, uint32_t maxoffs){ uint32_t n = maxoffs * sizeof(uint32_t);//偏移数组所占的大小 if (n > maxdata) {//偏移数组所占的大小不能大于最大能分配大小 bio->flags = BIO_F_OVERFLOW; bio->data_avail = 0; bio->offs_avail = 0; return; } bio->data = bio->data0 = data + n;//偏移数组后面是数据缓冲区 bio->offs = bio->offs0 = data;//开始是偏移数组 bio->data_avail = maxdata - n;//数据缓冲区大小 bio->offs_avail = maxoffs;//偏移数组大小 bio->flags = 0;}bio_init初始化了binder_io结构体reply。返回binder_parse执行bio_init_from_txn函数,实现如下:
void bio_init_from_txn(struct binder_io *bio, struct binder_txn *txn){ bio->data = bio->data0 = txn->data; bio->offs = bio->offs0 = txn->offs; bio->data_avail = txn->data_size; bio->offs_avail = txn->offs_size / 4; bio->flags = BIO_F_SHARED;}bio_init_from_txn初始化了binder_io结构体msg。
int svcmgr_handler(struct binder_state *bs, struct binder_txn *txn, struct binder_io *msg, struct binder_io *reply){ struct svcinfo *si; uint16_t *s; unsigned len; void *ptr; uint32_t strict_policy; ...... if (txn->target != svcmgr_handle)//txn->target为NULL,svcmgr_handle为NULL(void* (0)) return -1; // 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);//strict_policy为STRICT_MODE_PENALTY_GATHER s = bio_get_string16(msg, &len);//s为android.os.IServiceManager if ((len != (sizeof(svcmgr_id) / 2)) || memcmp(svcmgr_id, s, sizeof(svcmgr_id))) {//比较是否一致,如果不一致,直接返回出错 fprintf(stderr,"invalid id %s\n", str8(s)); return -1; } switch(txn->code) {//ADD_SERVICE_TRANSACTION,即SVC_MGR_ADD_SERVICE ........ case SVC_MGR_ADD_SERVICE: s = bio_get_string16(msg, &len);//s为shy.luo.FregService,len为它的长度 ptr = bio_get_ref(msg);//返回Binder引用对象的句柄值 if (do_add_service(bs, s, len, ptr, txn->sender_euid)) return -1; break; ....... bio_put_uint32(reply, 0); return 0;}
uint16_t svcmgr_id[] = { 'a','n','d','r','o','i','d','.','o','s','.', 'I','S','e','r','v','i','c','e','M','a','n','a','g','e','r' };程序从binder_io结构体msg从获取了3个字符串信息,然后调用bio_get_ref函数返回Binder引用对象的句柄值,实现如下:
void *bio_get_ref(struct binder_io *bio){ struct binder_object *obj; obj = _bio_get_obj(bio); if (!obj) return 0; if (obj->type == BINDER_TYPE_HANDLE) return obj->pointer; return 0;}_bio_get_obj实现如下:
static struct binder_object *_bio_get_obj(struct binder_io *bio){ unsigned n; unsigned off = bio->data - bio->data0;//flat_binder_object偏移,由于前面获取字符串移动了data /* TODO: be smarter about this? */ for (n = 0; n < bio->offs_avail; n++) {//offs_avail等于1 if (bio->offs[n] == off) return bio_get(bio, sizeof(struct binder_object)); } bio->data_avail = 0; bio->flags |= BIO_F_OVERFLOW; return 0;}_bio_get_obj首先计算出flat_binder_object偏移,然后看看偏移是否和bio->offs[0]一致,如果一致,那么就调用bio_get函数,实现如下。
static void *bio_get(struct binder_io *bio, uint32_t size){ size = (size + 3) & (~3); if (bio->data_avail < size){ ....... } else { void *ptr = bio->data; bio->data += size;//数据指针增加 bio->data_avail -= size;//可用空间减少 return ptr;//返回了flat_binder_object结构体 }}函数返回了flat_binder_object结构体,最后返回到bio_get_ref函数,转换成binder_object结构体指针。由于type等于BINDER_TYPE_HANDLE,所以返回Binder引用对象的句柄值。