本文参考《Android系统源代码情景分析》,作者罗升阳
一、service manager代码:
驱动层代码:
~/Android//kernel/goldfish/drivers/staging/android
----binder.c
----binder.h
~/Android//kernel/goldfish/drivers/staging/android
----binder.c
static int binder_thread_read(struct binder_proc *proc, struct binder_thread *thread, void __user *buffer, int size, signed long *consumed, int non_block) { void __user *ptr = buffer + *consumed; void __user *end = buffer + size; int ret = 0; ......... 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_parent为NULL t->to_thread = thread; thread->transaction_stack = t;//Service Manager进程主线程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);//res为0,注册成功代码0写入binder_io结构体reply中 } 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);//Service Manager进程的引用对象(引用了FregServer进程的实体对象) 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));//返回flat_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引用对象的句柄值。
int do_add_service(struct binder_state *bs, uint16_t *s, unsigned len, void *ptr, unsigned uid) { struct svcinfo *si; ...... if (!svc_can_register(uid, s)) {//检查用户ID为uid的进程是否有权限请求Service Manager注册一个名称为s的Service组件 LOGE("add_service('%s',%p) uid=%d - PERMISSION DENIED\n", str8(s), ptr, uid); return -1; } si = find_svc(s, len);//来检查服务名称s是否被已经注册了的Service组件使用了 if (si) {//现在是NULL if (si->ptr) { ....... return -1; } si->ptr = ptr; } else { si = malloc(sizeof(*si) + (len + 1) * sizeof(uint16_t));//分配svn_info结构体内存 ....... si->ptr = ptr;//要注册的引用对象句柄值 si->len = len;//shy.luo.FregService的长度 memcpy(si->name, s, (len + 1) * sizeof(uint16_t));//shy.luo.FregService si->name[len] = '\0'; si->death.func = svcinfo_death;//死亡通知 si->death.ptr = si; si->next = svclist;//形成链表 svclist = si; } binder_acquire(bs, ptr);//增加相对应的Binder引用对象的引用计数值,避免它过早地被销毁 binder_link_to_death(bs, ptr, &si->death);//向Binder驱动程序注册一个Binder本地对象死亡接受通知 return 0; }参数s表示要注册的Service组件的名称,参数uid表示请求Service Manager注册Service组件的进程的用户ID, 函数首先调用svn_can_register来检查用户ID为uid的进程是否有权限请求Service Manager注册一个名称为s的Service组件。实现如下:
int svc_can_register(unsigned uid, uint16_t *name) { unsigned n; if ((uid == 0) || (uid == AID_SYSTEM))//如果参数uid的值等于0,或者AID_SYSTEM就马上返回1给调用者,表示可以注册一个名称为name的Service组件。因为它们是系统进程 return 1; for (n = 0; n < sizeof(allowed) / sizeof(allowed[0]); n++) if ((uid == allowed[n].uid) && str16eq(name, allowed[n].name))//检查参数uid和name是否对应于数组allowed中的某一个元素。 return 1; return 0; }如果参数uid的值等于0,或者AID_SYSTEM就马上返回1给调用者,表示可以注册一个名称为name的Service组件。因为它们是系统进程。如果不是系统进程,那么检查参数uid和name是否对应于数组allowed中的某一个元素。allowed实现如下:
static struct { unsigned uid; const char *name; } allowed[] = { #ifdef LVMX { AID_MEDIA, "com.lifevibes.mx.ipc" }, #endif { AID_MEDIA, "media.audio_flinger" }, { AID_MEDIA, "media.player" }, { AID_MEDIA, "media.camera" }, { AID_MEDIA, "media.audio_policy" }, { AID_NFC, "nfc" }, { AID_RADIO, "radio.phone" }, { AID_RADIO, "radio.sms" }, { AID_RADIO, "radio.phonesubinfo" }, { AID_RADIO, "radio.simphonebook" }, /* TODO: remove after phone services are updated: */ { AID_RADIO, "phone" }, { AID_RADIO, "sip" }, { AID_RADIO, "isms" }, { AID_RADIO, "iphonesubinfo" }, { AID_RADIO, "simphonebook" }, };返回do_add_service,继续执行,开始执行find_svc,来检查服务名称s是否被已经注册了的Service组件使用了。实现如下:
struct svcinfo *find_svc(uint16_t *s16, unsigned 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 0; }在Service Manager中,每一个被注册了的Service组件都使用一个svcinfo结构体来描述,并且保存在一个全局队列svclist中。
struct svcinfo { struct svcinfo *next; void *ptr; struct binder_death death; unsigned len; uint16_t name[0]; }; struct svcinfo *svclist = 0;在结构体svcinfo中,成员变量next用来指向下一个svcinfo结构体;成员变量ptr是一个句柄值,用来描述一个注册了的Service组件;成员变量name和len分别用来已经注册了的Service组件的名称及其长度;成员变量death指向一个binder_death结构体,用来描述一个死亡接受通知。