Android服务查询完整过程源码分析

来源:互联网 发布:阿里云ecs地域选择 编辑:程序博客网 时间:2024/06/06 03:38

http://blog.csdn.net/yangwen123/article/details/9196739


目录(?)[+]

Android服务注册完整过程源码分析中从上到下详细分析了Android系统的服务注册过程,本文同样针对AudioService服务来介绍Android服务的查询过程。

客户端进程数据发送过程

[java] view plain copy
  1. private static IAudioService getService()  
  2. {  
  3.     if (sService != null) {  
  4.         return sService;  
  5.     }  
  6.     IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);  
  7.     sService = IAudioService.Stub.asInterface(b);  
  8.     return sService;  
  9. }  

函数调用ServiceManager.getService(Context.AUDIO_SERVICE)函数向ServiceManager进程查询AudioService服务对应的binder代理对象。

[java] view plain copy
  1. public static IBinder getService(String name) {  
  2.     try {  
  3.         IBinder service = sCache.get(name);  
  4.         if (service != null) {  
  5.             return service;  
  6.         } else {  
  7.             return getIServiceManager().getService(name);  
  8.         }  
  9.     } catch (RemoteException e) {  
  10.         Log.e(TAG, "error in getService", e);  
  11.     }  
  12.     return null;  
  13. }  

为了加快查询速度,对每次查找的服务都存储在缓存HashMap<String, IBinder> sCache = new HashMap<String, IBinder>()中,如果是第一次查找AudioService,则缓存中不存在,于是通过getIServiceManager().getService(name)来向ServiceManager进程查询服务。getIServiceManager()函数已经在Android请求注册服务过程源码分析文中进行了详细分析,该函数返回一个ServiceManagerProxy对象,因此调用ServiceManagerProxy对象的getService函数来完成服务查询

frameworks\base\core\Java\android\os\ServiceManagerNative.java

[java] view plain copy
  1. public IBinder getService(String name) throws RemoteException {  
  2.     Parcel data = Parcel.obtain();  
  3.     Parcel reply = Parcel.obtain();  
  4.     data.writeInterfaceToken(IServiceManager.descriptor);  
  5.     data.writeString(name);  
  6.     mRemote.transact(GET_SERVICE_TRANSACTION, data, reply, 0);  
  7.     IBinder binder = reply.readStrongBinder();  
  8.     reply.recycle();  
  9.     data.recycle();  
  10.     return binder;  
  11. }  

发送的数据为:

[cpp] view plain copy
  1. data.writeInterfaceToken("android.os.IServiceManager");  
  2. data.writeString("audio");  

此时Parcel对象中存储的数据如下:

关于数据在Binder驱动中的读写过程在Android服务注册完整过程源码分析中已经详细介绍了,这里不在分析。客户进程通过binder_thread_write函数将以上数据发送给ServiceManager进程,同时唤醒ServiceManager进程,并进入binder_thread_read函数,睡眠等待ServiceManager进程的服务查询结果。

ServiceManager服务查询过程

在binder_parse函数中,通过bio_init和bio_init_from_txn函数分别初始化了reply和msg变量,初始化值为:

[cpp] view plain copy
  1. reply->data = (char *) rdata + n;  
  2. reply->offs = rdata;  
  3. reply->data0 = (char *) rdata + n;  
  4. reply->offs0 = rdata;  
  5. reply->data_avail = sizeof(rdata) - n;  
  6. reply->offs_avail = 4;  
  7. reply->flags = 0;  
  8.   
  9. msg->data = txn->data;  
  10. msg->offs = txn->offs;  
  11. msg->data0 = txn->data;  
  12. msg->offs0 = txn->offs;  
  13. msg->data_avail = txn->data_size;  
  14. msg->offs_avail = txn->offs_size / 4;  
  15. msg->flags = BIO_F_SHARED;  

ServiceManager进程对服务的查询或注册都是通过回调函数svcmgr_handler来完成的

[cpp] view plain copy
  1. int svcmgr_handler(struct binder_state *bs,  
  2.                    struct binder_txn *txn,  
  3.                    struct binder_io *msg,  
  4.                    struct binder_io *reply)  
  5. {  
  6.     struct svcinfo *si;  
  7.     uint16_t *s;  
  8.     unsigned len;  
  9.     void *ptr;  
  10.     uint32_t strict_policy;  
  11.     int allow_isolated;  
  12.     if (txn->target != svcmgr_handle)  
  13.         return -1;  
  14.     //读取RPC头  
  15.     strict_policy = bio_get_uint32(msg);  
  16.     //读取字符串,在AudioService服务查询时,发送了以下数据:  
  17.     //data.writeInterfaceToken("android.os.IServiceManager");  
  18.     //data.writeString("audio");  
  19.     //这里取出来的字符串s = "android.os.IServiceManager"  
  20.     s = bio_get_string16(msg, &len);  
  21.     if ((len != (sizeof(svcmgr_id) / 2)) ||  
  22.     /* 将字符串s和数值svcmgr_id进行比较,uint16_t svcmgr_id[] = {  
  23.     'a','n','d','r','o','i','d','.','o','s','.', 
  24.     'I','S','e','r','v','i','c','e','M','a','n','a','g','e','r'  
  25.     }*/  
  26.         memcmp(svcmgr_id, s, sizeof(svcmgr_id))) {  
  27.         fprintf(stderr,"invalid id %s\n", str8(s));  
  28.         return -1;  
  29.     }  
  30.     //txn->code = GET_SERVICE_TRANSACTION  
  31.     switch(txn->code) {  
  32.     //服务查询  
  33.     case SVC_MGR_GET_SERVICE:  
  34.     case SVC_MGR_CHECK_SERVICE:  
  35.         //读取服务名称,data.writeString("audio");  
  36.         s = bio_get_string16(msg, &len);  
  37.         //查询服务  
  38.         ptr = do_find_service(bs, s, len, txn->sender_euid);  
  39.         if (!ptr)  
  40.             break;  
  41.         bio_put_ref(reply, ptr);  
  42.         return 0;  
  43.     //服务注册  
  44.     case SVC_MGR_ADD_SERVICE:  
  45.         //读取服务名称,data.writeString("audio");  
  46.         s = bio_get_string16(msg, &len);  
  47.         ptr = bio_get_ref(msg);  
  48.         allow_isolated = bio_get_uint32(msg) ? 1 : 0;  
  49.         if (do_add_service(bs, s, len, ptr, txn->sender_euid, allow_isolated))  
  50.             return -1;  
  51.         break;  
  52.     //列出服务  
  53.     case SVC_MGR_LIST_SERVICES: {  
  54.         unsigned n = bio_get_uint32(msg);  
  55.         si = svclist;  
  56.         while ((n-- > 0) && si)  
  57.             si = si->next;  
  58.         if (si) {  
  59.             bio_put_string16(reply, si->name);  
  60.             return 0;  
  61.         }  
  62.         return -1;  
  63.     }  
  64.     default:  
  65.         ALOGE("unknown code %d\n", txn->code);  
  66.         return -1;  
  67.     }  
  68.     bio_put_uint32(reply, 0);  
  69.     return 0;  
  70. }  

客户端进程可以向ServiceManager请求查询服务、注册服务、列出服务。所有服务在ServiceManager进程中的组织方式如下图:

ServiceManager进程查询服务过程

[cpp] view plain copy
  1. case SVC_MGR_GET_SERVICE:  
  2. case SVC_MGR_CHECK_SERVICE:  
  3.     //读取服务名称,data.writeString("audio");  
  4.     s = bio_get_string16(msg, &len);  
  5.     //查询服务  
  6.     ptr = do_find_service(bs, s, len, txn->sender_euid);  
  7.     if (!ptr)  
  8.         break;  
  9.     bio_put_ref(reply, ptr);  
  10.     return 0;  

首先从发送过来的data中读取服务的名称和长度,然后根据服务名称查询对应的服务。

[cpp] view plain copy
  1. void *do_find_service(struct binder_state *bs, uint16_t *s, unsigned len, unsigned uid)  
  2. {  
  3.     struct svcinfo *si;  
  4.     //根据传进来的服务名称在全局链表中查找对应的服务  
  5.     si = find_svc(s, len);  
  6.     if (si && si->ptr) {  
  7.         if (!si->allow_isolated) {  
  8.             // If this service doesn't allow access from isolated processes,  
  9.             // then check the uid to see if it is isolated.  
  10.             unsigned appid = uid % AID_USER;  
  11.             if (appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END) {  
  12.                 return 0;  
  13.             }  
  14.         }  
  15.         return si->ptr;  
  16.     } else {  
  17.         return 0;  
  18.     }  
  19. }  

该函数调用find_svc函数从全局链表中根据服务名称查找对应的服务,然后经过权限检查,最后返回该服务在ServiceManager进程中的Binder引用对象的描述符,在服务注册中介绍过,服务首先在用户空间创建JavaBBinder本地对象,同时在内核空间创建对应的Binder节点,并且为ServiceManager进程创建Binder引用对象,将该引用对象的描述符保存在ServiceManager进程用户空间的全局链表中,就是svcinfor结构体的ptr成员变量中,服务查找过程就是根据服务名称从ServiceManager进程用户空间的服务链表中找到对应的服务,并得到该服务在ServiceManager进程中的Binder引用对象的描述符。

[cpp] view plain copy
  1. struct svcinfo *find_svc(uint16_t *s16, unsigned len)  
  2. {  
  3.     struct svcinfo *si;  
  4.     //循环遍历全局链表svclist  
  5.     for (si = svclist; si; si = si->next) {  
  6.         //首先判断服务名称的长度是否相等,然后判断服务名称是否相同  
  7.         if ((len == si->len) && !memcmp(s16, si->name, len * sizeof(uint16_t))) {  
  8.             //返回指定的服务  
  9.             return si;  
  10.         }  
  11.     }  
  12.     return 0;  
  13. }  

查找到对应的服务后,得到该服务在ServiceManager进程的Binder引用对象的描述符,然后调用函数bio_put_ref生成binder_object结构体

[cpp] view plain copy
  1. void bio_put_ref(struct binder_io *bio, void *ptr)  
  2. {  
  3.     struct binder_object *obj;  
  4.   
  5.     if (ptr)  
  6.         obj = bio_alloc_obj(bio);  
  7.     else  
  8.         obj = bio_alloc(bio, sizeof(*obj));  
  9.   
  10.     if (!obj)  
  11.         return;  
  12.   
  13.     obj->flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;  
  14.     obj->type = BINDER_TYPE_HANDLE;  
  15.     obj->pointer = ptr;  
  16.     obj->cookie = 0;  
  17. }  

flat_binder_object结构与binder_object结构之间的关系
 

因此bio_put_ref()函数其实就是根据查找到服务在ServiceManager进程中的Binder引用对象的描述符构造flat_binder_object结构体,并将对Binder引用对象的描述结构写入到Parcel对象reply中

执行完服务查询后,并将binder_object保存到reply变量中,然后通过binder_send_reply(bs, &reply, txn->data, res)将查询的服务发送给客户进程。

ServiceManager进程发送服务查询结果

[cpp] view plain copy
  1. void binder_send_reply(struct binder_state *bs,  
  2.                        struct binder_io *reply,  
  3.                        void *buffer_to_free,  
  4.                        int status)  
  5. {  
  6.     struct {  
  7.         uint32_t cmd_free;  
  8.         void *buffer;  
  9.         uint32_t cmd_reply;  
  10.         struct binder_txn txn;  
  11.     } __attribute__((packed)) data;  
  12.   
  13.     data.cmd_free = BC_FREE_BUFFER;  
  14.     data.buffer = buffer_to_free;  
  15.     data.cmd_reply = BC_REPLY;  
  16.     data.txn.target = 0;  
  17.     data.txn.cookie = 0;  
  18.     data.txn.code = 0;  
  19.     if (status) {  
  20.         data.txn.flags = TF_STATUS_CODE;  
  21.         data.txn.data_size = sizeof(int);  
  22.         data.txn.offs_size = 0;  
  23.         data.txn.data = &status;  
  24.         data.txn.offs = 0;  
  25.     } else {  
  26.         data.txn.flags = 0;  
  27.         data.txn.data_size = reply->data - reply->data0;  
  28.         data.txn.offs_size = ((char*) reply->offs) - ((char*) reply->offs0);  
  29.         data.txn.data = reply->data0;  
  30.         data.txn.offs = reply->offs0;  
  31.     }  
  32.     binder_write(bs, &data, sizeof(data));  
  33. }  
该函数在Android服务注册完整过程源码分析中详细分析过了,向data中写入BC_FREE_BUFFER、BC_REPLY及这两个命令的数据

BC_FREE_BUFFER命令是用来通知Binder驱动释放内核缓冲区的,而BC_REPLY是向服务查询进程返回服务查询结果的。通过binder_write(bs, &data, sizeof(data))函数向Binder驱动中写入数据data

[cpp] view plain copy
  1. int binder_write(struct binder_state *bs, void *data, unsigned len)  
  2. {  
  3.     struct binder_write_read bwr;  
  4.     int res;  
  5.     bwr.write_size = len;  
  6.     bwr.write_consumed = 0;  
  7.     bwr.write_buffer = (unsigned) data;  
  8.     bwr.read_size = 0;  
  9.     bwr.read_consumed = 0;  
  10.     bwr.read_buffer = 0;  
  11.     res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);  
  12.     if (res < 0) {  
  13.         fprintf(stderr,"binder_write: ioctl failed (%s)\n",  
  14.                 strerror(errno));  
  15.     }  
  16.     return res;  
  17. }  

binder_write函数将需要发送的数据data封装到binder_write_read结构体中,然后使用ioctl系统调用进入内核空间的Binder驱动中,此时的binder_write_read内容为:
bwr.write_consumed = 0;
bwr.write_buffer = (unsigned) data;
bwr.read_size = 0;
bwr.read_consumed = 0;
bwr.read_buffer = 0;
bwr.write_size = len;
由于bwr.read_size = 0,而bwr.write_size >0 因此binder_ioctl函数对BINDER_WRITE_READ命令处理中只会调用binder_thread_write函数进行Binder写操作

[cpp] view plain copy
  1. case BINDER_WRITE_READ: {  
  2.     struct binder_write_read bwr;  
  3.     if (size != sizeof(struct binder_write_read)) {  
  4.         ret = -EINVAL;  
  5.         goto err;  
  6.     }  
  7.     if (copy_from_user(&bwr, ubuf, sizeof(bwr))) {  
  8.         ret = -EFAULT;  
  9.         goto err;  
  10.     }  
  11.     if (bwr.write_size > 0) {  
  12.         ret = binder_thread_write(proc, thread, (void __user *)bwr.write_buffer, bwr.write_size, &bwr.write_consumed);  
  13.         if (ret < 0) {  
  14.             bwr.read_consumed = 0;  
  15.             if (copy_to_user(ubuf, &bwr, sizeof(bwr)))  
  16.                 ret = -EFAULT;  
  17.             goto err;  
  18.         }  
  19.     }  
  20.     if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {  
  21.         ret = -EFAULT;  
  22.         goto err;  
  23.     }  
  24.     break;  
  25. }  

首先调用copy_from_user函数将用户空间的binder_write_read结构体内容拷贝到内核空间的binder_write_read结构体中,然后调用binder_thread_write函数完成数据发送任务,最后调用函数copy_to_user将内核空间的binder_write_read结构体内容拷贝的用户空间的binder_write_read结构体中,数据的发送结果及读取的数据都存放在binder_write_read结构体中

[cpp] view plain copy
  1. int binder_thread_write(struct binder_proc *proc, struct binder_thread *thread,  
  2.             void __user *buffer, int size, signed long *consumed)  
  3. {  
  4.     uint32_t cmd;  
  5.     void __user *ptr = buffer + *consumed;  
  6.     void __user *end = buffer + size;  
  7.   
  8.     while (ptr < end && thread->return_error == BR_OK) {  
  9.         if (get_user(cmd, (uint32_t __user *)ptr))  
  10.             return -EFAULT;  
  11.         ptr += sizeof(uint32_t);  
  12.         if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.bc)) {  
  13.             binder_stats.bc[_IOC_NR(cmd)]++;  
  14.             proc->stats.bc[_IOC_NR(cmd)]++;  
  15.             thread->stats.bc[_IOC_NR(cmd)]++;  
  16.         }  
  17.         switch (cmd) {  
  18.         case BC_FREE_BUFFER: {  
  19.             void __user *data_ptr;  
  20.             struct binder_buffer *buffer;  
  21.   
  22.             if (get_user(data_ptr, (void * __user *)ptr))  
  23.                 return -EFAULT;  
  24.             ptr += sizeof(void *);  
  25.   
  26.             buffer = binder_buffer_lookup(proc, data_ptr);  
  27.             if (buffer == NULL) {  
  28.                 break;  
  29.             }  
  30.             if (!buffer->allow_user_free) {  
  31.                 break;  
  32.             }  
  33.             if (buffer->transaction) {  
  34.                 buffer->transaction->buffer = NULL;  
  35.                 buffer->transaction = NULL;  
  36.             }  
  37.             if (buffer->async_transaction && buffer->target_node) {  
  38.                 BUG_ON(!buffer->target_node->has_async_transaction);  
  39.                 if (list_empty(&buffer->target_node->async_todo))  
  40.                     buffer->target_node->has_async_transaction = 0;  
  41.                 else  
  42.                     list_move_tail(buffer->target_node->async_todo.next, &thread->todo);  
  43.             }  
  44.             binder_transaction_buffer_release(proc, buffer, NULL);  
  45.             binder_free_buf(proc, buffer);  
  46.             break;  
  47.         }  
  48.         case BC_TRANSACTION:  
  49.         case BC_REPLY: {  
  50.             struct binder_transaction_data tr;  
  51.             if (copy_from_user(&tr, ptr, sizeof(tr)))  
  52.                 return -EFAULT;  
  53.             ptr += sizeof(tr);  
  54.             binder_transaction(proc, thread, &tr, cmd == BC_REPLY);  
  55.             break;  
  56.         }  
  57.         default:  
  58.             printk(KERN_ERR "binder: %d:%d unknown command %d\n",  
  59.                    proc->pid, thread->pid, cmd);  
  60.             return -EINVAL;  
  61.         }  
  62.         *consumed = ptr - buffer;  
  63.     }  
  64.     return 0;  
  65. }  

首先介绍一下各个变量的含义,如下图所示:


buffer指向要传输数据的首地址,size表示传输数据的大小,consumed表示已经处理完的数据位置,因此待处理的数据就介于ptr = buffer + *consumed与end = buffer + size之间,应用程序可以向Binder驱动程序一次发送多个Binder命令,它们都是按命令+数据的方式进行存放的,binder_thread_write函数遍历ptr与end指针之间的待处理数据,依次读取Binder命令及该命令对应的数据,并根据Binder命令做相应的处理。
对于命令BC_FREE_BUFFER的处理如下:

[cpp] view plain copy
  1. case BC_FREE_BUFFER: {  
  2.     void __user *data_ptr;  
  3.     struct binder_buffer *buffer;  
  4.   
  5.     if (get_user(data_ptr, (void * __user *)ptr))  
  6.         return -EFAULT;  
  7.     ptr += sizeof(void *);  
  8.   
  9.     buffer = binder_buffer_lookup(proc, data_ptr);  
  10.     if (buffer == NULL) {  
  11.         break;  
  12.     }  
  13.     if (!buffer->allow_user_free) {  
  14.         break;  
  15.     }  
  16.     if (buffer->transaction) {  
  17.         buffer->transaction->buffer = NULL;  
  18.         buffer->transaction = NULL;  
  19.     }  
  20.     if (buffer->async_transaction && buffer->target_node) {  
  21.         BUG_ON(!buffer->target_node->has_async_transaction);  
  22.         if (list_empty(&buffer->target_node->async_todo))  
  23.             buffer->target_node->has_async_transaction = 0;  
  24.         else  
  25.             list_move_tail(buffer->target_node->async_todo.next, &thread->todo);  
  26.     }  
  27.     binder_transaction_buffer_release(proc, buffer, NULL);  
  28.     binder_free_buf(proc, buffer);  
  29.     break;  
  30. }  

首先通过get_user(data_ptr, (void * __user *)ptr)从ptr指向的数据中取出在binder_send_reply函数中设置的buffer_to_free,该指针指向要释放的内核缓冲区,然后通过binder_buffer_lookup函数从当前进程即ServiceManager进程的binder_proc中查找要释放的内核缓冲区binder_buffer,查找过程如下:

[cpp] view plain copy
  1. static struct binder_buffer *binder_buffer_lookup(struct binder_proc *proc,  
  2.                           void __user *user_ptr)  
  3. {  
  4.     struct rb_node *n = proc->allocated_buffers.rb_node;  
  5.     struct binder_buffer *buffer;  
  6.     struct binder_buffer *kern_ptr;  
  7.   
  8.     kern_ptr = user_ptr - proc->user_buffer_offset  
  9.         - offsetof(struct binder_buffer, data);  
  10.   
  11.     while (n) {  
  12.         buffer = rb_entry(n, struct binder_buffer, rb_node);  
  13.         BUG_ON(buffer->free);  
  14.   
  15.         if (kern_ptr < buffer)  
  16.             n = n->rb_left;  
  17.         else if (kern_ptr > buffer)  
  18.             n = n->rb_right;  
  19.         else  
  20.             return buffer;  
  21.     }  
  22.     return NULL;  
  23. }  

user_ptr是指向传输数据的用户空间地址,通过user_ptr - proc->user_buffer_offset可以计算出传输数据在内核空间的地址,proc->user_buffer_offset在介绍内核缓冲区分配时已经接收了,该变量记录了用户空间与内核空间之间的偏移,offsetof(struct binder_buffer, data)是计算出结构体binder_buffer中的data成员变量在该结构体中的偏移量,最后通过

[cpp] view plain copy
  1. kern_ptr = user_ptr - proc->user_buffer_offset - offsetof(struct binder_buffer, data)  

可以得到保存传输数据的binder_buffer在内核空间的地址值,然后变量当前进程的binder_proc的allocated_buffers红黑树,这颗红黑树挂载了所有分配的内核缓冲区binder_buffer,在这颗红黑树中查找需要释放空间的内核缓冲区是否存在,如果存在则释放该内核缓冲区

[cpp] view plain copy
  1. if (buffer->transaction) {  
  2.     buffer->transaction->buffer = NULL;  
  3.     buffer->transaction = NULL;  
  4. }  
  5. if (buffer->async_transaction && buffer->target_node) {  
  6.     BUG_ON(!buffer->target_node->has_async_transaction);  
  7.     if (list_empty(&buffer->target_node->async_todo))  
  8.         buffer->target_node->has_async_transaction = 0;  
  9.     else  
  10.         list_move_tail(buffer->target_node->async_todo.next, &thread->todo);  
  11. }  
  12. binder_transaction_buffer_release(proc, buffer, NULL);  
  13. binder_free_buf(proc, buffer);  
接下来分析BC_REPLY的处理过程:

[cpp] view plain copy
  1. case BC_REPLY: {  
  2.     struct binder_transaction_data tr;  
  3.     if (copy_from_user(&tr, ptr, sizeof(tr)))  
  4.         return -EFAULT;  
  5.     ptr += sizeof(tr);  
  6.     binder_transaction(proc, thread, &tr, cmd == BC_REPLY);  
  7.     break;  
  8. }  
处理过程很简单,就是调用binder_transaction函数向服务查询请求进程发送服务查询结果,binder_transaction函数非常复杂,也是Binder驱动中数据传输的重要函数,在Android IPC数据在内核空间中的发送过程分析中有详细的分析过程,这里再次详细分析一下该函数

[cpp] view plain copy
  1. static void binder_transaction(struct binder_proc *proc,  
  2.                    struct binder_thread *thread,  
  3.                    struct binder_transaction_data *tr, int reply)  
  4. {  
  5.     struct binder_transaction *t;  
  6.     struct binder_work *tcomplete;  
  7.     size_t *offp, *off_end;  
  8.     struct binder_proc *target_proc;  
  9.     struct binder_thread *target_thread = NULL;  
  10.     struct binder_node *target_node = NULL;  
  11.     struct list_head *target_list;  
  12.     wait_queue_head_t *target_wait;  
  13.     struct binder_transaction *in_reply_to = NULL;  
  14.     struct binder_transaction_log_entry *e;  
  15.     uint32_t return_error;  
  16.   
  17.     e = binder_transaction_log_add(&binder_transaction_log);  
  18.     e->call_type = reply ? 2 : !!(tr->flags & TF_ONE_WAY);  
  19.     e->from_proc = proc->pid;  
  20.     e->from_thread = thread->pid;  
  21.     e->target_handle = tr->target.handle;  
  22.     e->data_size = tr->data_size;  
  23.     e->offsets_size = tr->offsets_size;  
  24.   
  25.     if (reply) {  
  26.         in_reply_to = thread->transaction_stack;  
  27.         if (in_reply_to == NULL) {  
  28.             return_error = BR_FAILED_REPLY;  
  29.             goto err_empty_call_stack;  
  30.         }  
  31.         binder_set_nice(in_reply_to->saved_priority);  
  32.         if (in_reply_to->to_thread != thread) {  
  33.             return_error = BR_FAILED_REPLY;  
  34.             in_reply_to = NULL;  
  35.             goto err_bad_call_stack;  
  36.         }  
  37.         thread->transaction_stack = in_reply_to->to_parent;  
  38.         target_thread = in_reply_to->from;  
  39.         if (target_thread == NULL) {  
  40.             return_error = BR_DEAD_REPLY;  
  41.             goto err_dead_binder;  
  42.         }  
  43.         if (target_thread->transaction_stack != in_reply_to) {  
  44.             return_error = BR_FAILED_REPLY;  
  45.             in_reply_to = NULL;  
  46.             target_thread = NULL;  
  47.             goto err_dead_binder;  
  48.         }  
  49.         target_proc = target_thread->proc;  
  50.     } else {  
  51.         if (tr->target.handle) {  
  52.             struct binder_ref *ref;  
  53.             ref = binder_get_ref(proc, tr->target.handle);  
  54.             if (ref == NULL) {  
  55.                 return_error = BR_FAILED_REPLY;  
  56.                 goto err_invalid_target_handle;  
  57.             }  
  58.             target_node = ref->node;  
  59.         } else {  
  60.             target_node = binder_context_mgr_node;  
  61.             if (target_node == NULL) {  
  62.                 return_error = BR_DEAD_REPLY;  
  63.                 goto err_no_context_mgr_node;  
  64.             }  
  65.         }  
  66.         e->to_node = target_node->debug_id;  
  67.         target_proc = target_node->proc;  
  68.         if (target_proc == NULL) {  
  69.             return_error = BR_DEAD_REPLY;  
  70.             goto err_dead_binder;  
  71.         }  
  72.         if (!(tr->flags & TF_ONE_WAY) && thread->transaction_stack) {  
  73.             struct binder_transaction *tmp;  
  74.             tmp = thread->transaction_stack;  
  75.             if (tmp->to_thread != thread) {  
  76.                 return_error = BR_FAILED_REPLY;  
  77.                 goto err_bad_call_stack;  
  78.             }  
  79.             while (tmp) {  
  80.                 if (tmp->from && tmp->from->proc == target_proc)  
  81.                     target_thread = tmp->from;  
  82.                 tmp = tmp->from_parent;  
  83.             }  
  84.         }  
  85.     }  
  86.     if (target_thread) {  
  87.         e->to_thread = target_thread->pid;  
  88.         target_list = &target_thread->todo;  
  89.         target_wait = &target_thread->wait;  
  90.     } else {  
  91.         target_list = &target_proc->todo;  
  92.         target_wait = &target_proc->wait;  
  93.     }  
  94.     e->to_proc = target_proc->pid;  
  95.   
  96.     /* TODO: reuse incoming transaction for reply */  
  97.     t = kzalloc(sizeof(*t), GFP_KERNEL);  
  98.     if (t == NULL) {  
  99.         return_error = BR_FAILED_REPLY;  
  100.         goto err_alloc_t_failed;  
  101.     }  
  102.     binder_stats_created(BINDER_STAT_TRANSACTION);  
  103.   
  104.     tcomplete = kzalloc(sizeof(*tcomplete), GFP_KERNEL);  
  105.     if (tcomplete == NULL) {  
  106.         return_error = BR_FAILED_REPLY;  
  107.         goto err_alloc_tcomplete_failed;  
  108.     }  
  109.     binder_stats_created(BINDER_STAT_TRANSACTION_COMPLETE);  
  110.   
  111.     t->debug_id = ++binder_last_id;  
  112.     e->debug_id = t->debug_id;  
  113.   
  114.     if (!reply && !(tr->flags & TF_ONE_WAY))  
  115.         t->from = thread;  
  116.     else  
  117.         t->from = NULL;  
  118.     t->sender_euid = proc->tsk->cred->euid;  
  119.     t->to_proc = target_proc;  
  120.     t->to_thread = target_thread;  
  121.     t->code = tr->code;  
  122.     t->flags = tr->flags;  
  123.     t->priority = task_nice(current);  
  124.     t->buffer = binder_alloc_buf(target_proc, tr->data_size,  
  125.         tr->offsets_size, !reply && (t->flags & TF_ONE_WAY));  
  126.     if (t->buffer == NULL) {  
  127.         return_error = BR_FAILED_REPLY;  
  128.         goto err_binder_alloc_buf_failed;  
  129.     }  
  130.     t->buffer->allow_user_free = 0;  
  131.     t->buffer->debug_id = t->debug_id;  
  132.     t->buffer->transaction = t;  
  133.     t->buffer->target_node = target_node;  
  134.     if (target_node)  
  135.         binder_inc_node(target_node, 1, 0, NULL);  
  136.   
  137.     offp = (size_t *)(t->buffer->data + ALIGN(tr->data_size, sizeof(void *)));  
  138.   
  139.     if (copy_from_user(t->buffer->data, tr->data.ptr.buffer, tr->data_size)) {  
  140.         return_error = BR_FAILED_REPLY;  
  141.         goto err_copy_data_failed;  
  142.     }  
  143.     if (copy_from_user(offp, tr->data.ptr.offsets, tr->offsets_size)) {  
  144.         return_error = BR_FAILED_REPLY;  
  145.         goto err_copy_data_failed;  
  146.     }  
  147.     if (!IS_ALIGNED(tr->offsets_size, sizeof(size_t))) {  
  148.         return_error = BR_FAILED_REPLY;  
  149.         goto err_bad_offset;  
  150.     }  
  151.     off_end = (void *)offp + tr->offsets_size;  
  152.     for (; offp < off_end; offp++) {  
  153.         struct flat_binder_object *fp;  
  154.         if (*offp > t->buffer->data_size - sizeof(*fp) ||  
  155.             t->buffer->data_size < sizeof(*fp) ||  
  156.             !IS_ALIGNED(*offp, sizeof(void *))) {  
  157.             return_error = BR_FAILED_REPLY;  
  158.             goto err_bad_offset;  
  159.         }  
  160.         fp = (struct flat_binder_object *)(t->buffer->data + *offp);  
  161.         switch (fp->type) {  
  162.         case BINDER_TYPE_BINDER:  
  163.         case BINDER_TYPE_WEAK_BINDER: {  
  164.             struct binder_ref *ref;  
  165.             struct binder_node *node = binder_get_node(proc, fp->binder);  
  166.             if (node == NULL) {  
  167.                 node = binder_new_node(proc, fp->binder, fp->cookie);  
  168.                 if (node == NULL) {  
  169.                     return_error = BR_FAILED_REPLY;  
  170.                     goto err_binder_new_node_failed;  
  171.                 }  
  172.                 node->min_priority = fp->flags & FLAT_BINDER_FLAG_PRIORITY_MASK;  
  173.                 node->accept_fds = !!(fp->flags & FLAT_BINDER_FLAG_ACCEPTS_FDS);  
  174.             }  
  175.             if (fp->cookie != node->cookie) {  
  176.                 goto err_binder_get_ref_for_node_failed;  
  177.             }  
  178.             ref = binder_get_ref_for_node(target_proc, node);  
  179.             if (ref == NULL) {  
  180.                 return_error = BR_FAILED_REPLY;  
  181.                 goto err_binder_get_ref_for_node_failed;  
  182.             }  
  183.             if (fp->type == BINDER_TYPE_BINDER)  
  184.                 fp->type = BINDER_TYPE_HANDLE;  
  185.             else  
  186.                 fp->type = BINDER_TYPE_WEAK_HANDLE;  
  187.             fp->handle = ref->desc;  
  188.             binder_inc_ref(ref, fp->type == BINDER_TYPE_HANDLE,  
  189.                        &thread->todo);  
  190.         } break;  
  191.         case BINDER_TYPE_HANDLE:  
  192.         case BINDER_TYPE_WEAK_HANDLE: {  
  193.             struct binder_ref *ref = binder_get_ref(proc, fp->handle);  
  194.             if (ref == NULL) {  
  195.                 return_error = BR_FAILED_REPLY;  
  196.                 goto err_binder_get_ref_failed;  
  197.             }  
  198.             if (ref->node->proc == target_proc) {  
  199.                 if (fp->type == BINDER_TYPE_HANDLE)  
  200.                     fp->type = BINDER_TYPE_BINDER;  
  201.                 else  
  202.                     fp->type = BINDER_TYPE_WEAK_BINDER;  
  203.                 fp->binder = ref->node->ptr;  
  204.                 fp->cookie = ref->node->cookie;  
  205.                 binder_inc_node(ref->node, fp->type == BINDER_TYPE_BINDER, 0, NULL);  
  206.             } else {  
  207.                 struct binder_ref *new_ref;  
  208.                 new_ref = binder_get_ref_for_node(target_proc, ref->node);  
  209.                 if (new_ref == NULL) {  
  210.                     return_error = BR_FAILED_REPLY;  
  211.                     goto err_binder_get_ref_for_node_failed;  
  212.                 }  
  213.                 fp->handle = new_ref->desc;  
  214.                 binder_inc_ref(new_ref, fp->type == BINDER_TYPE_HANDLE, NULL);  
  215.             }  
  216.         } break;  
  217.   
  218.         case BINDER_TYPE_FD: {  
  219.             int target_fd;  
  220.             struct file *file;  
  221.   
  222.             if (reply) {  
  223.                 if (!(in_reply_to->flags & TF_ACCEPT_FDS)) {  
  224.                     return_error = BR_FAILED_REPLY;  
  225.                     goto err_fd_not_allowed;  
  226.                 }  
  227.             } else if (!target_node->accept_fds) {  
  228.                 return_error = BR_FAILED_REPLY;  
  229.                 goto err_fd_not_allowed;  
  230.             }  
  231.   
  232.             file = fget(fp->handle);  
  233.             if (file == NULL) {  
  234.                 return_error = BR_FAILED_REPLY;  
  235.                 goto err_fget_failed;  
  236.             }  
  237.             target_fd = task_get_unused_fd_flags(target_proc, O_CLOEXEC);  
  238.             if (target_fd < 0) {  
  239.                 fput(file);  
  240.                 return_error = BR_FAILED_REPLY;  
  241.                 goto err_get_unused_fd_failed;  
  242.             }  
  243.             task_fd_install(target_proc, target_fd, file);  
  244.             fp->handle = target_fd;  
  245.         } break;  
  246.   
  247.         default:  
  248.             return_error = BR_FAILED_REPLY;  
  249.             goto err_bad_object_type;  
  250.         }  
  251.     }  
  252.     if (reply) {  
  253.         BUG_ON(t->buffer->async_transaction != 0);  
  254.         binder_pop_transaction(target_thread, in_reply_to);  
  255.     } else if (!(t->flags & TF_ONE_WAY)) {  
  256.         BUG_ON(t->buffer->async_transaction != 0);  
  257.         t->need_reply = 1;  
  258.         t->from_parent = thread->transaction_stack;  
  259.         thread->transaction_stack = t;  
  260.     } else {  
  261.         BUG_ON(target_node == NULL);  
  262.         BUG_ON(t->buffer->async_transaction != 1);  
  263.         if (target_node->has_async_transaction) {  
  264.             target_list = &target_node->async_todo;  
  265.             target_wait = NULL;  
  266.         } else  
  267.             target_node->has_async_transaction = 1;  
  268.     }  
  269.     t->work.type = BINDER_WORK_TRANSACTION;  
  270.     list_add_tail(&t->work.entry, target_list);  
  271.     tcomplete->type = BINDER_WORK_TRANSACTION_COMPLETE;  
  272.     list_add_tail(&tcomplete->entry, &thread->todo);  
  273.     if (target_wait)  
  274.         wake_up_interruptible(target_wait);  
  275.     return;  
  276.   
  277. err_get_unused_fd_failed:  
  278. err_fget_failed:  
  279. err_fd_not_allowed:  
  280. err_binder_get_ref_for_node_failed:  
  281. err_binder_get_ref_failed:  
  282. err_binder_new_node_failed:  
  283. err_bad_object_type:  
  284. err_bad_offset:  
  285. err_copy_data_failed:  
  286.     binder_transaction_buffer_release(target_proc, t->buffer, offp);  
  287.     t->buffer->transaction = NULL;  
  288.     binder_free_buf(target_proc, t->buffer);  
  289. err_binder_alloc_buf_failed:  
  290.     kfree(tcomplete);  
  291.     binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE);  
  292. err_alloc_tcomplete_failed:  
  293.     kfree(t);  
  294.     binder_stats_deleted(BINDER_STAT_TRANSACTION);  
  295. err_alloc_t_failed:  
  296. err_bad_call_stack:  
  297. err_empty_call_stack:  
  298. err_dead_binder:  
  299. err_invalid_target_handle:  
  300. err_no_context_mgr_node:  
  301.     {  
  302.         struct binder_transaction_log_entry *fe;  
  303.         fe = binder_transaction_log_add(&binder_transaction_log_failed);  
  304.         *fe = *e;  
  305.     }  
  306.     BUG_ON(thread->return_error != BR_OK);  
  307.     if (in_reply_to) {  
  308.         thread->return_error = BR_TRANSACTION_COMPLETE;  
  309.         binder_send_failed_reply(in_reply_to, return_error);  
  310.     } else  
  311.         thread->return_error = return_error;  
  312. }  
参数proc是当前ServiceManager进程的binder_proc描述,而thread也是ServiceManager的Binder线程描述,参数tr是指要传输的数据,reply是一个标志位,标示当前是否是BC_REPLY命令下的数据传输,因此在这个场景下reply = 1,因此函数binder_transaction首先执行以下代码片段:

[cpp] view plain copy
  1. //从ServiceManager的Binder线程事务堆栈中取出客户进程向ServiceManager进程请求服务查询的事务项  
  2. in_reply_to = thread->transaction_stack;  
  3. if (in_reply_to == NULL) {  
  4.     return_error = BR_FAILED_REPLY;  
  5.     goto err_empty_call_stack;  
  6. }  
  7. //保存当前线程优先级到binder_transaction的saved_priority成员中  
  8. binder_set_nice(in_reply_to->saved_priority);  
  9. //判断客户进程向ServiceManager进程请求服务查询的事务项发送的目标线程是否为当前线程  
  10. if (in_reply_to->to_thread != thread) {  
  11.     return_error = BR_FAILED_REPLY;  
  12.     in_reply_to = NULL;  
  13.     goto err_bad_call_stack;  
  14. }  
  15. thread->transaction_stack = in_reply_to->to_parent;  
  16. //设置目标线程target_thread为向ServiceManager进程发送请求服务查询事务项的线程  
  17. target_thread = in_reply_to->from;  
  18. if (target_thread == NULL) {  
  19.     return_error = BR_DEAD_REPLY;  
  20.     goto err_dead_binder;  
  21. }  
  22. if (target_thread->transaction_stack != in_reply_to) {  
  23.     return_error = BR_FAILED_REPLY;  
  24.     in_reply_to = NULL;  
  25.     target_thread = NULL;  
  26.     goto err_dead_binder;  
  27. }  
  28. target_proc = target_thread->proc;  
  29.   
  30. if (target_thread) {  
  31.     e->to_thread = target_thread->pid;  
  32.     target_list = &target_thread->todo;  
  33.     target_wait = &target_thread->wait;  
  34. else {  
  35.     target_list = &target_proc->todo;  
  36.     target_wait = &target_proc->wait;  
  37. }  

这里主要是找到数据回复的目标进程及目标线程
target_thread = thread->transaction_stack->from;
target_proc = target_thread->proc;
target_list = &target_thread->todo;
target_wait = &target_thread->wait;
接着创建事务项t,用来封装整个数据的传输过程,同时创建一个binder_work项tcomplete

[cpp] view plain copy
  1. t = kzalloc(sizeof(*t), GFP_KERNEL);  
  2. if (t == NULL) {  
  3.     return_error = BR_FAILED_REPLY;  
  4.     goto err_alloc_t_failed;  
  5. }  
  6. binder_stats_created(BINDER_STAT_TRANSACTION);  
  7.   
  8. tcomplete = kzalloc(sizeof(*tcomplete), GFP_KERNEL);  
  9. if (tcomplete == NULL) {  
  10.     return_error = BR_FAILED_REPLY;  
  11.     goto err_alloc_tcomplete_failed;  
  12. }  
  13. binder_stats_created(BINDER_STAT_TRANSACTION_COMPLETE);  
使用参数tr来初始化事务项t

[cpp] view plain copy
  1. t->debug_id = ++binder_last_id;  
  2. e->debug_id = t->debug_id;  
  3.   
  4. if (!reply && !(tr->flags & TF_ONE_WAY))  
  5.     t->from = thread;  
  6. else  
  7.     t->from = NULL;  
  8. t->sender_euid = proc->tsk->cred->euid;  
  9. t->to_proc = target_proc;  
  10. t->to_thread = target_thread;  
  11. t->code = tr->code;  
  12. t->flags = tr->flags;  
  13. t->priority = task_nice(current);  
  14. //根据此次传输的数据大小分配内核缓冲区  
  15. t->buffer = binder_alloc_buf(target_proc, tr->data_size,tr->offsets_size, !reply && (t->flags & TF_ONE_WAY));  
  16. if (t->buffer == NULL) {  
  17.     return_error = BR_FAILED_REPLY;  
  18.     goto err_binder_alloc_buf_failed;  
  19. }  
  20. t->buffer->allow_user_free = 0;  
  21. t->buffer->debug_id = t->debug_id;  
  22. t->buffer->transaction = t;  
  23. t->buffer->target_node = target_node;  
  24. if (target_node)  
  25.     binder_inc_node(target_node, 1, 0, NULL);  

这里为数据传输事务项t分配了内核缓冲区来保存传输的数据,因此需要将tr中的数据拷贝到传输事务项t的内核缓冲区中

[cpp] view plain copy
  1. offp = (size_t *)(t->buffer->data + ALIGN(tr->data_size, sizeof(void *)));  
  2.   
  3. if (copy_from_user(t->buffer->data, tr->data.ptr.buffer, tr->data_size)) {  
  4.     return_error = BR_FAILED_REPLY;  
  5.     goto err_copy_data_failed;  
  6. }  
  7. if (copy_from_user(offp, tr->data.ptr.offsets, tr->offsets_size)) {  
  8.     return_error = BR_FAILED_REPLY;  
  9.     goto err_copy_data_failed;  
  10. }  
  11. if (!IS_ALIGNED(tr->offsets_size, sizeof(size_t))) {  
  12.     return_error = BR_FAILED_REPLY;  
  13.     goto err_bad_offset;  
  14. }  

因为ServiceManager进程完成服务查询后,将查询结果封装为一个Binder描述结构flat_binder_object发送回服务查询请求进程,该结构的内容如下:

[cpp] view plain copy
  1. obj->flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;  
  2. obj->type = BINDER_TYPE_HANDLE;  
  3. obj->pointer = ptr;  
  4. obj->cookie = 0;  

因此在传输的数据中存在一个flat_binder_object对象,flat_binder_object的存储方式在Android 数据Parcel序列化过程源码分析中已经详细介绍了。binder_transaction函数通过遍历flat_binder_object对象的偏移数组来找出每一个flat_binder_object

[cpp] view plain copy
  1. off_end = (void *)offp + tr->offsets_size;  
  2. for (; offp < off_end; offp++) {  
  3.     struct flat_binder_object *fp;  
  4.     if (*offp > t->buffer->data_size - sizeof(*fp) ||  
  5.         t->buffer->data_size < sizeof(*fp) ||  
  6.         !IS_ALIGNED(*offp, sizeof(void *))) {  
  7.         return_error = BR_FAILED_REPLY;  
  8.         goto err_bad_offset;  
  9.     }  
  10.     fp = (struct flat_binder_object *)(t->buffer->data + *offp);  
  11.     switch (fp->type) {  
  12.     case BINDER_TYPE_BINDER:  
  13.     case BINDER_TYPE_WEAK_BINDER:   
  14.         break;  
  15.     case BINDER_TYPE_HANDLE:  
  16.     case BINDER_TYPE_WEAK_HANDLE:  
  17.         break;  
  18.     case BINDER_TYPE_FD:   
  19.         break;  
  20.     default:  
  21.         return_error = BR_FAILED_REPLY;  
  22.         goto err_bad_object_type;  
  23.     }  
  24. }  
由于ServiceManager进程返回的flat_binder_object类型为BINDER_TYPE_HANDLE,binder_transaction函数对该类型的Binder对象处理如下:

[cpp] view plain copy
  1. case BINDER_TYPE_HANDLE:  
  2. case BINDER_TYPE_WEAK_HANDLE: {  
  3.     struct binder_ref *ref = binder_get_ref(proc, fp->handle);  
  4.     if (ref == NULL) {  
  5.         return_error = BR_FAILED_REPLY;  
  6.         goto err_binder_get_ref_failed;  
  7.     }  
  8.     if (ref->node->proc == target_proc) {  
  9.         if (fp->type == BINDER_TYPE_HANDLE)  
  10.             fp->type = BINDER_TYPE_BINDER;  
  11.         else  
  12.             fp->type = BINDER_TYPE_WEAK_BINDER;  
  13.         fp->binder = ref->node->ptr;  
  14.         fp->cookie = ref->node->cookie;  
  15.         binder_inc_node(ref->node, fp->type == BINDER_TYPE_BINDER, 0, NULL);  
  16.     } else {  
  17.         struct binder_ref *new_ref;  
  18.         new_ref = binder_get_ref_for_node(target_proc, ref->node);  
  19.         if (new_ref == NULL) {  
  20.             return_error = BR_FAILED_REPLY;  
  21.             goto err_binder_get_ref_for_node_failed;  
  22.         }  
  23.         fp->handle = new_ref->desc;  
  24.         binder_inc_ref(new_ref, fp->type == BINDER_TYPE_HANDLE, NULL);  
  25.     }  
  26. break;  
此时的proc代表ServiceManager进程,在Android服务注册完整过程源码分析中介绍了Binder驱动为注册的Binder本地对象在内核缓冲区创建对应的Binder节点,并且为ServiceManager进程创建引用该Binder节点的Binder引用对象,并保存到ServiceManager进程的binder_proc的红黑树中,因此这里通过binder_get_ref函数就可以从ServiceManager进程的binder_proc中根据Binder引用对象句柄值查找到对应的Binder引用对象,查找过程如下:

[cpp] view plain copy
  1. static struct binder_ref *binder_get_ref(struct binder_proc *proc,  
  2.                      uint32_t desc)  
  3. {  
  4.     struct rb_node *n = proc->refs_by_desc.rb_node;  
  5.     struct binder_ref *ref;  
  6.   
  7.     while (n) {  
  8.         ref = rb_entry(n, struct binder_ref, rb_node_desc);  
  9.   
  10.         if (desc < ref->desc)  
  11.             n = n->rb_left;  
  12.         else if (desc > ref->desc)  
  13.             n = n->rb_right;  
  14.         else  
  15.             return ref;  
  16.     }  
  17.     return NULL;  
  18. }  

该函数实现比较简单,就是从binder_proc的refs_by_desc这颗红黑树中根据Binder引用对象的句柄值查找出Binder引用对象。找到该Binder引用对象后,判断该Binder引用对象所引用的Binder节点所属进程是否为目标进程,Binder节点所属进程是指注册该Binder实体对应服务的进程,对于Java服务来说,这些服务对应内核Binder节点所属进程就是SystemServer进程,而这里的target_proc却是请求ServiceManager进程查询服务的进程,比如Android应用程序进程,因此ref->node->proc 不等于target_proc,于是

[cpp] view plain copy
  1. struct binder_ref *new_ref;  
  2. new_ref = binder_get_ref_for_node(target_proc, ref->node);  
  3. if (new_ref == NULL) {  
  4.     return_error = BR_FAILED_REPLY;  
  5.     goto err_binder_get_ref_for_node_failed;  
  6. }  
  7. fp->handle = new_ref->desc;  
  8. binder_inc_ref(new_ref, fp->type == BINDER_TYPE_HANDLE, NULL);  
函数binder_get_ref_for_node是为当前请求服务查询进程创建Binder引用对象,同时修改传输的flat_binder_object结构体的handle句柄值,关于Binder引用对象的创建过程如下:

[cpp] view plain copy
  1. static struct binder_ref *binder_get_ref_for_node(struct binder_proc *proc,  
  2.                           struct binder_node *node)  
  3. {  
  4.     struct rb_node *n;  
  5.     struct rb_node **p = &proc->refs_by_node.rb_node;  
  6.     struct rb_node *parent = NULL;  
  7.     struct binder_ref *ref, *new_ref;  
  8.   
  9.     while (*p) {  
  10.         parent = *p;  
  11.         ref = rb_entry(parent, struct binder_ref, rb_node_node);  
  12.         if (node < ref->node)  
  13.             p = &(*p)->rb_left;  
  14.         else if (node > ref->node)  
  15.             p = &(*p)->rb_right;  
  16.         else  
  17.             return ref;  
  18.     }  
  19.     new_ref = kzalloc(sizeof(*ref), GFP_KERNEL);  
  20.     if (new_ref == NULL)  
  21.         return NULL;  
  22.     binder_stats_created(BINDER_STAT_REF);  
  23.     new_ref->debug_id = ++binder_last_id;  
  24.     new_ref->proc = proc;  
  25.     new_ref->node = node;  
  26.     rb_link_node(&new_ref->rb_node_node, parent, p);  
  27.     rb_insert_color(&new_ref->rb_node_node, &proc->refs_by_node);  
  28.   
  29.     new_ref->desc = (node == binder_context_mgr_node) ? 0 : 1;  
  30.     for (n = rb_first(&proc->refs_by_desc); n != NULL; n = rb_next(n)) {  
  31.         ref = rb_entry(n, struct binder_ref, rb_node_desc);  
  32.         if (ref->desc > new_ref->desc)  
  33.             break;  
  34.         new_ref->desc = ref->desc + 1;  
  35.     }  
  36.   
  37.     p = &proc->refs_by_desc.rb_node;  
  38.     while (*p) {  
  39.         parent = *p;  
  40.         ref = rb_entry(parent, struct binder_ref, rb_node_desc);  
  41.         if (new_ref->desc < ref->desc)  
  42.             p = &(*p)->rb_left;  
  43.         else if (new_ref->desc > ref->desc)  
  44.             p = &(*p)->rb_right;  
  45.         else  
  46.             BUG();  
  47.     }  
  48.     rb_link_node(&new_ref->rb_node_desc, parent, p);  
  49.     rb_insert_color(&new_ref->rb_node_desc, &proc->refs_by_desc);  
  50.     if (node) {  
  51.         hlist_add_head(&new_ref->node_entry, &node->refs);  
  52.     }   
  53.     return new_ref;  
  54. }  
该函数首先从目标进程target_proc的refs_by_node红黑树中根据Binder节点查找对应的Binder引用对象,如果没有查找到,则为目标进程创建一个引用该Binder节点的Binder引用对象,修改该Binder引用对象的描述符,并且插入到目标进程的refs_by_node红黑树中,接着binder_transaction函数将设置发送给请求服务查询进程的flat_binder_object结构体的句柄值为新创建的Binder引用对象的描述符,flat_binder_object结构体最终会传送到请求服务查询进程的用户空间,请求服务查询进程在用户空间通过该句柄值即可从当前进程在内核空间的描述符binder_proc中查找到所查询服务的Binder引用对象,通过Binder引用对象找到Binder节点,然后通过Binder节点找到服务的Binder本地对象,这样就可以调用服务的接口函数了,真正实现RPC远程调用。
Binder本地对象的寻址过程:
handle值 -> 当前进程在内核空间的Binder引用对象 -> 服务在内核空间对应的Binder节点 -> 服务在用户空间的Binder本地对象
此时传输的flat_binder_object结构体内容如下:
[cpp] view plain copy
  1. fp->flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;  
  2. fp->type = BINDER_TYPE_HANDLE;  
  3. fp->handle = new_ref->desc;  
  4. fp->cookie = 0;  

binder_transaction函数接着调用binder_pop_transaction(target_thread, in_reply_to)来释放事务项in_reply_to的内存空间,然后将创建的事物项t挂载到目标线程的待处理队列todo中,同时将传输完成事务项tcomplete挂载到当前线程的待处理队列中,并唤醒目标线程

[cpp] view plain copy
  1. t->work.type = BINDER_WORK_TRANSACTION;  
  2. list_add_tail(&t->work.entry, target_list);  
  3. tcomplete->type = BINDER_WORK_TRANSACTION_COMPLETE;  
  4. list_add_tail(&tcomplete->entry, &thread->todo);  
  5. if (target_wait)  
  6.     wake_up_interruptible(target_wait);  
  7. return;  

ServiceManager的当前Binder线程层层返回到binder_loop函数中,再次通过ioctl进入Binder驱动程序中,因为bwr.read_size > 0 而bwr.write_size = 0,因此binder_ioctl函数会调用binder_thread_read函数读取客户进程发送过来的请求数据,由于传输完成事务项tcomplete挂载到当前线程的待处理队列todo中,此时todo队列不为空,因此binder_thread_read函数对tcomplete事务项的处理过程为:

[cpp] view plain copy
  1. case BINDER_WORK_TRANSACTION_COMPLETE: {  
  2.     cmd = BR_TRANSACTION_COMPLETE;  
  3.     if (put_user(cmd, (uint32_t __user *)ptr))  
  4.         return -EFAULT;  
  5.     ptr += sizeof(uint32_t);  
  6.   
  7.     binder_stat_br(proc, thread, cmd);  
  8.     list_del(&w->entry);  
  9.     kfree(w);  
  10.     binder_stats_deleted(BINDER_STAT_TRANSACTION_COMPLETE);  
  11. break;  

处理完该事务项后,函数层层返回到binder_loop函数中,又再次通过ioctl进入Binder驱动程序中,同样执行binder_thread_read,但此时线程的待处理队列todo为空,因此当前线程会睡眠等待客户端的请求。前面介绍到ServiceManager进程通过binder_transaction函数将服务查询结果封装在一个事务项t中并挂载到服务查询请求进程的Binder线程待处理队列todo中,然后唤醒服务查询请求线程,由于该线程此时正睡眠在binder_thread_read函数中,线程被唤醒后,将读取到ServiceManager进程发送过来的服务查询结果,并返回到用户空间中。

客户进程获取服务代理对象

服务查询进程在用户空间通过IBinder binder = reply.readStrongBinder()来获得ServiceManager进程查询到的服务代理对象。关于readStrongBinder()函数的详细分析请看Android 数据Parcel序列化过程源码分析


函数首先从ServiceManager进程返回来的Parcel对象中取出flat_binder_object,然后根据Binder引用对象的描述符创建BpBinder对象,在创建Java层负责通信的BinderProxy对象,最后创建和业务相关的XXXProxy对象,这样就得到了所查询得到的服务的代理对象。通过该代理对象就可以向该服务的本地对象发送RPC远程调用请求。
总结一下Android服务查询过程
1)客户进程将要查询的服务名称发送给ServiceManager进程;
2)ServiceManager进程根据服务名称在自身用户空间中的全局服务链表中查找对应的服务,并得到ServiceManager进程引用该服务的句柄值;
3)ServiceManager进程将查询得到的句柄值发送给Binder驱动;
4)Binder驱动根据句柄值在ServiceManager进程的binder_proc中查找Binder引用对象;
5)如果服务查询进程不是注册该服务的进程,则在服务查询进程的binder_proc中根据Binder节点查找服务查询进程引用该Binder节点的Binder引用对象,反之,将该服务对应的Binder本地对象地址发送给服务查询进程;
6)如果服务查询进程不是注册该服务的进程并且第一次查询该服务,Binder驱动会为服务查询进程创建引用该服务Binder节点的Binder引用对象,并将该引用对象句柄值返回到客户进程的用户空间中;
7)客户进程得到本进程引用服务的Binder引用对象的句柄值后,创建服务代理对象;


不是注册服务的进程请求查询服务:
name ——> hanlder(servicemanager) ——> binder_ref(servicemanager) ——> binder_node ——>binder_ref(client) ——>hanlder(client)
服务注册进程查询服务:
name ——> hanlder(servicemanager) ——> binder_ref(servicemanager) ——> binder_node ——> JavaBBinder
ServiceManager、服务注册进程、服务查询进程之间的关系如图:



3
0

0 0