注意,这里的status参数为0。从这里可以看出,binder_send_reply告诉Binder驱动程序执行BC_FREE_BUFFER和BC_REPLY命令,前者释放之前在binder_transaction分配的空间,地址为buffer_to_free,buffer_to_free这个地址是Binder驱动程序把自己在内核空间用的地址转换成用户空间地址再传给Service Manager的,所以Binder驱动程序拿到这个地址后,知道怎么样释放这个空间;后者告诉Binder驱动程序,它的SVC_MGR_CHECK_SERVICE操作已经完成了,要查询的服务的句柄值也是保存在data.txn.data,操作结果码是0,也是保存在data.txn.data中。
再来看binder_write函数:
- int binder_write(struct binder_state *bs, void *data, unsigned len)
- {
- struct binder_write_read bwr;
- int res;
- bwr.write_size = len;
- bwr.write_consumed = 0;
- bwr.write_buffer = (unsigned) 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;
- }
这里可以看出,只有写操作,没有读操作,即read_size为0。
这里又是一个ioctl的BINDER_WRITE_READ操作。直入到驱动程序的binder_ioctl函数后,执行BINDER_WRITE_READ命令,这里就不累述了。
最后,从binder_ioctl执行到binder_thread_write函数,首先是执行BC_FREE_BUFFER命令,这个命令的执行在前面一篇文章Android系统进程间通信(IPC)机制Binder中的Server启动过程源代码分析已经介绍过了,这里就不再累述了。
我们重点关注BC_REPLY命令的执行:
- int
- binder_thread_write(struct binder_proc *proc, struct binder_thread *thread,
- void __user *buffer, int size, signed long *consumed)
- {
- uint32_t cmd;
- void __user *ptr = buffer + *consumed;
- void __user *end = buffer + size;
-
- while (ptr < end && thread->return_error == BR_OK) {
- if (get_user(cmd, (uint32_t __user *)ptr))
- return -EFAULT;
- ptr += sizeof(uint32_t);
- if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.bc)) {
- binder_stats.bc[_IOC_NR(cmd)]++;
- proc->stats.bc[_IOC_NR(cmd)]++;
- thread->stats.bc[_IOC_NR(cmd)]++;
- }
- switch (cmd) {
- ......
- case BC_TRANSACTION:
- case BC_REPLY: {
- struct binder_transaction_data tr;
-
- if (copy_from_user(&tr, ptr, sizeof(tr)))
- return -EFAULT;
- ptr += sizeof(tr);
- binder_transaction(proc, thread, &tr, cmd == BC_REPLY);
- break;
- }
-
- ......
- *consumed = ptr - buffer;
- }
- return 0;
- }
又再次进入到binder_transaction函数:
- static void
- binder_transaction(struct binder_proc *proc, struct binder_thread *thread,
- struct binder_transaction_data *tr, int reply)
- {
- struct binder_transaction *t;
- struct binder_work *tcomplete;
- size_t *offp, *off_end;
- struct binder_proc *target_proc;
- struct binder_thread *target_thread = NULL;
- struct binder_node *target_node = NULL;
- struct list_head *target_list;
- wait_queue_head_t *target_wait;
- struct binder_transaction *in_reply_to = NULL;
- struct binder_transaction_log_entry *e;
- uint32_t return_error;
-
- ......
-
- if (reply) {
- in_reply_to = thread->transaction_stack;
- if (in_reply_to == NULL) {
- ......
- return_error = BR_FAILED_REPLY;
- goto err_empty_call_stack;
- }
- ......
- thread->transaction_stack = in_reply_to->to_parent;
- target_thread = in_reply_to->from;
- ......
- target_proc = target_thread->proc;
- } else {
- ......
- }
- if (target_thread) {
- e->to_thread = target_thread->pid;
- target_list = &target_thread->todo;
- target_wait = &target_thread->wait;
- } else {
- ......
- }
-
-
- /* TODO: reuse incoming transaction for reply */
- t = kzalloc(sizeof(*t), GFP_KERNEL);
- if (t == NULL) {
- return_error = BR_FAILED_REPLY;
- goto err_alloc_t_failed;
- }
- binder_stats.obj_created[BINDER_STAT_TRANSACTION]++;
-
- tcomplete = kzalloc(sizeof(*tcomplete), GFP_KERNEL);
- if (tcomplete == NULL) {
- return_error = BR_FAILED_REPLY;
- goto err_alloc_tcomplete_failed;
- }
- ......
-
- if (!reply && !(tr->flags & TF_ONE_WAY))
- t->from = thread;
- else
- t->from = NULL;
- t->sender_euid = proc->tsk->cred->euid;
- t->to_proc = target_proc;
- t->to_thread = target_thread;
- t->code = tr->code;
- t->flags = tr->flags;
- t->priority = task_nice(current);
- t->buffer = binder_alloc_buf(target_proc, tr->data_size,
- tr->offsets_size, !reply && (t->flags & TF_ONE_WAY));
- if (t->buffer == NULL) {
- return_error = BR_FAILED_REPLY;
- goto err_binder_alloc_buf_failed;
- }
- t->buffer->allow_user_free = 0;
- t->buffer->debug_id = t->debug_id;
- t->buffer->transaction = t;
- t->buffer->target_node = target_node;
- if (target_node)
- binder_inc_node(target_node, 1, 0, NULL);
-
- offp = (size_t *)(t->buffer->data + ALIGN(tr->data_size, sizeof(void *)));
-
- if (copy_from_user(t->buffer->data, tr->data.ptr.buffer, tr->data_size)) {
- binder_user_error("binder: %d:%d got transaction with invalid "
- "data ptr\n", proc->pid, thread->pid);
- return_error = BR_FAILED_REPLY;
- goto err_copy_data_failed;
- }
- if (copy_from_user(offp, tr->data.ptr.offsets, tr->offsets_size)) {
- binder_user_error("binder: %d:%d got transaction with invalid "
- "offsets ptr\n", proc->pid, thread->pid);
- return_error = BR_FAILED_REPLY;
- goto err_copy_data_failed;
- }
- ......
-
- off_end = (void *)offp + tr->offsets_size;
- for (; offp < off_end; offp++) {
- struct flat_binder_object *fp;
- ......
- fp = (struct flat_binder_object *)(t->buffer->data + *offp);
- switch (fp->type) {
- ......
- case BINDER_TYPE_HANDLE:
- case BINDER_TYPE_WEAK_HANDLE: {
- struct binder_ref *ref = binder_get_ref(proc, fp->handle);
- if (ref == NULL) {
- ......
- return_error = BR_FAILED_REPLY;
- goto err_binder_get_ref_failed;
- }
- if (ref->node->proc == target_proc) {
- ......
- } else {
- struct binder_ref *new_ref;
- new_ref = binder_get_ref_for_node(target_proc, ref->node);
- if (new_ref == NULL) {
- return_error = BR_FAILED_REPLY;
- goto err_binder_get_ref_for_node_failed;
- }
- fp->handle = new_ref->desc;
- binder_inc_ref(new_ref, fp->type == BINDER_TYPE_HANDLE, NULL);
- ......
- }
- } break;
-
- ......
- }
- }
-
- if (reply) {
- BUG_ON(t->buffer->async_transaction != 0);
- binder_pop_transaction(target_thread, in_reply_to);
- } else if (!(t->flags & TF_ONE_WAY)) {
- ......
- } else {
- ......
- }
-
- t->work.type = BINDER_WORK_TRANSACTION;
- list_add_tail(&t->work.entry, target_list);
- tcomplete->type = BINDER_WORK_TRANSACTION_COMPLETE;
- list_add_tail(&tcomplete->entry, &thread->todo);
- if (target_wait)
- wake_up_interruptible(target_wait);
- return;
-
- ......
- }
这次进入binder_transaction函数的情形和上面介绍的binder_transaction函数的情形基本一致,只是这里的proc、thread和target_proc、target_thread调换了角色,这里的proc和thread指的是Service Manager进程,而target_proc和target_thread指的是刚才请求SVC_MGR_CHECK_SERVICE的进程。
那么,这次是如何找到target_proc和target_thread呢。首先,我们注意到,这里的reply等于1,其次,上面我们提到,Binder驱动程序在唤醒Service Manager,告诉它有一个事务t要处理时,事务t虽然从Service Manager的todo队列中删除了,但是仍然保留在transaction_stack中。因此,这里可以从thread->transaction_stack找回这个等待回复的事务t,然后通过它找回target_proc和target_thread:
- in_reply_to = thread->transaction_stack;
- target_thread = in_reply_to->from;
- target_list = &target_thread->todo;
- target_wait = &target_thread->wait;
再接着往下看,由于Service Manager返回来了一个Binder引用,所以这里要处理一下,就是中间的for循环了。这是一个BINDER_TYPE_HANDLE类型的Binder引用,这是前面设置的。先把t->buffer->data的内容转换为一个struct flat_binder_object对象fp,这里的fp->handle值就是这个Service在Service Manager进程里面的引用值了。接通过调用binder_get_ref函数得到Binder引用对象struct binder_ref类型的对象ref:
- struct binder_ref *ref = binder_get_ref(proc, fp->handle);
这里一定能找到,因为前面MediaPlayerService执行IServiceManager::addService的时候把自己添加到Service Manager的时候,会在Service Manager进程中创建这个Binder引用,然后把这个Binder引用的句柄值返回给Service Manager用户空间。
这里面的ref->node->proc不等于target_proc,因为这个Binder实体是属于创建MediaPlayerService的进程的,而不是请求这个服务的远程接口的进程的,因此,这里调用binder_get_ref_for_node函数为这个Binder实体在target_proc创建一个引用:
- struct binder_ref *new_ref;
- new_ref = binder_get_ref_for_node(target_proc, ref->node);
然后增加引用计数:
- binder_inc_ref(new_ref, fp->type == BINDER_TYPE_HANDLE, NULL);
这样,返回数据中的Binder对象就处理完成了。注意,这里会把fp->handle的值改为在target_proc中的引用值:
- fp->handle = new_ref->desc;
这里就相当于是把t->buffer->data里面的Binder对象的句柄值改写了。因为这是在另外一个不同的进程里面的Binder引用,所以句柄值当然要用新的了。这个值最终是要拷贝回target_proc进程的用户空间去的。
再往下看:
- if (reply) {
- BUG_ON(t->buffer->async_transaction != 0);
- binder_pop_transaction(target_thread, in_reply_to);
- } else if (!(t->flags & TF_ONE_WAY)) {
- ......
- } else {
- ......
- }
这里reply等于1,执行binder_pop_transaction函数把当前事务in_reply_to从target_thread->transaction_stack队列中删掉,这是上次调用binder_transaction函数的时候设置的,现在不需要了,所以把它删掉。
再往后的逻辑就跟前面执行binder_transaction函数时候一样了,这里不再介绍。最后的结果就是唤醒请求SVC_MGR_CHECK_SERVICE操作的线程:
- if (target_wait)
- wake_up_interruptible(target_wait);
这样,Service Manger回复调用SVC_MGR_CHECK_SERVICE请求就算完成了,重新回到frameworks/base/cmds/servicemanager/binder.c文件中的binder_loop函数等待下一个Client请求的到来。事实上,Service Manger回到binder_loop函数再次执行ioctl函数时候,又会再次进入到binder_thread_read函数。这时个会发现thread->todo不为空,这是因为刚才我们调用了:
- list_add_tail(&tcomplete->entry, &thread->todo);
把一个工作项tcompelete放在了在thread->todo中,这个tcompelete的type为BINDER_WORK_TRANSACTION_COMPLETE,因此,Binder驱动程序会执行下面操作:
- switch (w->type) {
- case BINDER_WORK_TRANSACTION_COMPLETE: {
- cmd = BR_TRANSACTION_COMPLETE;
- if (put_user(cmd, (uint32_t __user *)ptr))
- return -EFAULT;
- ptr += sizeof(uint32_t);
-
- list_del(&w->entry);
- kfree(w);
-
- } break;
- ......
- }
binder_loop函数执行完这个ioctl调用后,才会在下一次调用ioctl进入到Binder驱动程序进入休眠状态,等待下一次Client的请求。
上面讲到调用请求SVC_MGR_CHECK_SERVICE操作的线程被唤醒了,于是,重新执行binder_thread_read函数:
- static int
- binder_thread_read(struct binder_proc *proc, struct binder_thread *thread,
- void __user *buffer, int size, signed long *consumed, int non_block)
- {
- void __user *ptr = buffer + *consumed;
- void __user *end = buffer + size;
-
- int ret = 0;
- int wait_for_proc_work;
-
- if (*consumed == 0) {
- if (put_user(BR_NOOP, (uint32_t __user *)ptr))
- return -EFAULT;
- ptr += sizeof(uint32_t);
- }
-
- retry:
- wait_for_proc_work = thread->transaction_stack == NULL && list_empty(&thread->todo);
-
- ......
-
- if (wait_for_proc_work) {
- ......
- } else {
- if (non_block) {
- if (!binder_has_thread_work(thread))
- ret = -EAGAIN;
- } else
- ret = wait_event_interruptible(thread->wait, binder_has_thread_work(thread));
- }
-
- ......
-
- 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);
- 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);
- } break;
- ......
- }
-
- if (!t)
- continue;
-
- BUG_ON(t->buffer == NULL);
- if (t->buffer->target_node) {
- ......
- } else {
- tr.target.ptr = NULL;
- tr.cookie = NULL;
- cmd = BR_REPLY;
- }
- tr.code = t->code;
- tr.flags = t->flags;
- tr.sender_euid = t->sender_euid;
-
- if (t->from) {
- ......
- } else {
- tr.sender_pid = 0;
- }
-
- 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;
- 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)))
- 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)) {
- ......
- } else {
- t->buffer->transaction = NULL;
- kfree(t);
- binder_stats.obj_deleted[BINDER_STAT_TRANSACTION]++;
- }
- break;
- }
-
- done:
- ......
- return 0;
- }
就是从下面这个调用:
- ret = wait_event_interruptible(thread->wait, binder_has_thread_work(thread));
被唤醒过来了。在while循环中,从thread->todo得到w,w->type为BINDER_WORK_TRANSACTION,于是,得到t。从上面可以知道,Service Manager返回来了一个Binder引用和一个结果码0回来,写在t->buffer->data里面,现在把t->buffer->data加上proc->user_buffer_offset,得到用户空间地址,保存在tr.data.ptr.buffer里面,这样用户空间就可以访问这个数据了。由于cmd不等于BR_TRANSACTION,这时就可以把t删除掉了,因为以后都不需要用了。
执行完这个函数后,就返回到binder_ioctl函数,执行下面语句,把数据返回给用户空间:
- if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {
- ret = -EFAULT;
- goto err;
- }
接着返回到用户空间IPCThreadState::talkWithDriver函数,最后返回到IPCThreadState::waitForResponse函数,最终执行到下面语句:
- status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
- {
- int32_t cmd;
- int32_t err;
-
- while (1) {
- if ((err=talkWithDriver()) < NO_ERROR) break;
-
- ......
-
- cmd = mIn.readInt32();
-
- ......
-
- switch (cmd) {
- ......
- case BR_REPLY:
- {
- binder_transaction_data tr;
- err = mIn.read(&tr, sizeof(tr));
- LOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
- if (err != NO_ERROR) goto finish;
-
- if (reply) {
- if ((tr.flags & TF_STATUS_CODE) == 0) {
- reply->ipcSetDataReference(
- reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
- tr.data_size,
- reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
- tr.offsets_size/sizeof(size_t),
- freeBuffer, this);
- } else {
- ......
- }
- } else {
- ......
- }
- }
- goto finish;
-
- ......
- }
- }
-
- finish:
- ......
- return err;
- }
注意,这里的tr.flags等于0,这个是在上面的binder_send_reply函数里设置的。接着就把结果保存在reply了:
- reply->ipcSetDataReference(
- reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
- tr.data_size,
- reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
- tr.offsets_size/sizeof(size_t),
- freeBuffer, this);
我们简单看一下Parcel::ipcSetDataReference函数的实现:
- void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize,
- const size_t* objects, size_t objectsCount, release_func relFunc, void* relCookie)
- {
- freeDataNoInit();
- mError = NO_ERROR;
- mData = const_cast<uint8_t*>(data);
- mDataSize = mDataCapacity = dataSize;
- //LOGI("setDataReference Setting data size of %p to %lu (pid=%d)\n", this, mDataSize, getpid());
- mDataPos = 0;
- LOGV("setDataReference Setting data pos of %p to %d\n", this, mDataPos);
- mObjects = const_cast<size_t*>(objects);
- mObjectsSize = mObjectsCapacity = objectsCount;
- mNextObjectHint = 0;
- mOwner = relFunc;
- mOwnerCookie = relCookie;
- scanForFds();
- }
上面提到,返回来的数据中有一个Binder引用,因此,这里的mObjectSize等于1,这个Binder引用对应的位置记录在mObjects成员变量中。
从这里层层返回,最后回到BpServiceManager::checkService函数中:
- virtual sp<IBinder> BpServiceManager::checkService( const String16& name) const
- {
- Parcel data, reply;
- data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
- data.writeString16(name);
- remote()->transact(CHECK_SERVICE_TRANSACTION, data, &reply);
- return reply.readStrongBinder();
- }
这里就是从:
- remote()->transact(CHECK_SERVICE_TRANSACTION, data, &reply);
返回来了。我们接着看一下reply.readStrongBinder函数的实现:
- sp<IBinder> Parcel::readStrongBinder() const
- {
- sp<IBinder> val;
- unflatten_binder(ProcessState::self(), *this, &val);
- return val;
- }
这里调用了unflatten_binder函数来构造一个Binder对象:
- status_t unflatten_binder(const sp<ProcessState>& proc,
- const Parcel& in, sp<IBinder>* out)
- {
- const flat_binder_object* flat = in.readObject(false);
-
- if (flat) {
- switch (flat->type) {
- case BINDER_TYPE_BINDER:
- *out = static_cast<IBinder*>(flat->cookie);
- return finish_unflatten_binder(NULL, *flat, in);
- case BINDER_TYPE_HANDLE:
- *out = proc->getStrongProxyForHandle(flat->handle);
- return finish_unflatten_binder(
- static_cast<BpBinder*>(out->get()), *flat, in);
- }
- }
- return BAD_TYPE;
- }
这里的flat->type是BINDER_TYPE_HANDLE,因此调用ProcessState::getStrongProxyForHandle函数:
- sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
- {
- sp<IBinder> result;
-
- AutoMutex _l(mLock);
-
- handle_entry* e = lookupHandleLocked(handle);
-
- if (e != NULL) {
- // We need to create a new BpBinder if there isn't currently one, OR we
- // are unable to acquire a weak reference on this current one. See comment
- // in getWeakProxyForHandle() for more info about this.
- IBinder* b = e->binder;
- if (b == NULL || !e->refs->attemptIncWeak(this)) {
- b = new BpBinder(handle);
- e->binder = b;
- if (b) e->refs = b->getWeakRefs();
- result = b;
- } else {
- // This little bit of nastyness is to allow us to add a primary
- // reference to the remote proxy when this team doesn't have one
- // but another team is sending the handle to us.
- result.force_set(b);
- e->refs->decWeak(this);
- }
- }
-
- return result;
- }
这里我们可以看到,ProcessState会把使用过的Binder远程接口(BpBinder)缓存起来,这样下次从Service Manager那里请求得到相同的句柄(Handle)时就可以直接返回这个Binder远程接口了,不用再创建一个出来。这里是第一次使用,因此,e->binder为空,于是创建了一个BpBinder对象:
- b = new BpBinder(handle);
- e->binder = b;
- if (b) e->refs = b->getWeakRefs();
- result = b;
最后,函数返回到IMediaDeathNotifier::getMediaPlayerService这里,从这个语句返回:
- binder = sm->getService(String16("media.player"));
这里,就相当于是:
- binder = new BpBinder(handle);
最后,函数调用:
- sMediaPlayerService = interface_cast<IMediaPlayerService>(binder);
到了这里,我们可以参考一下前面一篇文章浅谈Android系统进程间通信(IPC)机制Binder中的Server和Client获得Service Manager,就会知道,这里的interface_cast实际上最终调用了IMediaPlayerService::asInterface函数:
- android::sp<IMediaPlayerService> IMediaPlayerService::asInterface(const android::sp<android::IBinder>& obj)
- {
- android::sp<IServiceManager> intr;
- if (obj != NULL) {
- intr = static_cast<IMediaPlayerService*>(
- obj->queryLocalInterface(IMediaPlayerService::descriptor).get());
- if (intr == NULL) {
- intr = new BpMediaPlayerService(obj);
- }
- }
- return intr;
- }
这里的obj就是BpBinder,而BpBinder::queryLocalInterface返回NULL,因此就创建了一个BpMediaPlayerService对象:
- intr = new BpMediaPlayerService(new BpBinder(handle));
因此,我们最终就得到了一个BpMediaPlayerService对象,达到我们最初的目标。
有了这个BpMediaPlayerService这个远程接口之后,MediaPlayer就可以调用MediaPlayerService的服务了。
至此,Android系统进程间通信(IPC)机制Binder中的Client如何通过Service Manager的getService函数获得Server远程接口的过程就分析完了,Binder机制的学习就暂告一段落了。
不过,细心的读者可能会发现,我们这里介绍的Binder机制都是基于C/C++语言实现的,但是我们在编写应用程序都是基于Java语言的,那么,我们如何使用Java语言来使用系统的Binder机制来进行进程间通信呢?这就是下一篇文章要介绍的内容了,敬请关注。