編輯:關於Android編程
在上一篇文章中,我們分析了Android系統進程間通信機制Binder中的Server在啟動過程使用Service Manager的addService接口把自己添加到Service Manager守護過程中接受管理。在這一篇文章中,我們將深入到Binder驅動程序源代碼去分析Client是如何通過Service Manager的getService接口中來獲得Server遠程接口的。Client只有獲得了Server的遠程接口之後,才能進一步調用Server提供的服務。
這裡,我們仍然是通過Android系統中自帶的多媒體播放器為例子來說明Client是如何通過IServiceManager::getService接口來獲得MediaPlayerService這個Server的遠程接口的。假設計讀者已經閱讀過前面三篇文章淺談Service Manager成為Android進程間通信(IPC)機制Binder守護進程之路、淺談Android系統進程間通信(IPC)機制Binder中的Server和Client獲得Service Manager接口之路和Android系統進程間通信(IPC)機制Binder中的Server啟動過程源代碼分析,即假設Service Manager和MediaPlayerService已經啟動完畢,Service Manager現在等待Client的請求。
這裡,我們要舉例子說明的Client便是MediaPlayer了,它聲明和實現在frameworks/base/include/media/mediaplayer.h和frameworks/base/media/libmedia/mediaplayer.cpp文件中。MediaPlayer繼承於IMediaDeathNotifier類,這個類聲明和實現在frameworks/base/include/media/IMediaDeathNotifier.h和frameworks/base/media/libmedia//IMediaDeathNotifier.cpp文件中,裡面有一個靜態成員函數getMeidaPlayerService,它通過IServiceManager::getService接口來獲得MediaPlayerService的遠程接口。
在介紹IMediaDeathNotifier::getMeidaPlayerService函數之前,我們先了解一下這個函數的目標。看來前面淺談Android系統進程間通信(IPC)機制Binder中的Server和Client獲得Service Manager接口之路這篇文章的讀者知道,我們在獲取Service Manager遠程接口時,最終是獲得了一個BpServiceManager對象的IServiceManager接口。類似地,我們要獲得MediaPlayerService的遠程接口,實際上就是要獲得一個稱為BpMediaPlayerService對象的IMediaPlayerService接口。現在,我們就先來看一下BpMediaPlayerService的類圖:
從這個類圖可以看到,BpMediaPlayerService繼承於BpInterface<IMediaPlayerService>類,即BpMediaPlayerService繼承了IMediaPlayerService類和BpRefBase類,這兩個類又分別繼續了RefBase類。BpRefBase類有一個成員變量mRemote,它的類型為IBinder,實際是一個BpBinder對象。BpBinder類使用了IPCThreadState類來與Binder驅動程序進行交互,而IPCThreadState類有一個成員變量mProcess,它的類型為ProcessState,IPCThreadState類借助ProcessState類來打開Binder設備文件/dev/binder,因此,它可以和Binder驅動程序進行交互。
BpMediaPlayerService的構造函數有一個參數impl,它的類型為const sp<IBinder>&,從上面的描述中,這個實際上就是一個BpBinder對象。這樣,要創建一個BpMediaPlayerService對象,首先就要有一個BpBinder對象。再來看BpBinder類的構造函數,它有一個參數handle,類型為int32_t,這個參數的意義就是請求MediaPlayerService這個遠程接口的進程對MediaPlayerService這個Binder實體的引用了。因此,獲取MediaPlayerService這個遠程接口的本質問題就變為從Service Manager中獲得MediaPlayerService的一個句柄了。
現在,我們就來看一下IMediaDeathNotifier::getMeidaPlayerService的實現:
// establish binder interface to MediaPlayerService /*static*/const sp<IMediaPlayerService>& IMediaDeathNotifier::getMediaPlayerService() { LOGV("getMediaPlayerService"); Mutex::Autolock _l(sServiceLock); if (sMediaPlayerService.get() == 0) { sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder; do { binder = sm->getService(String16("media.player")); if (binder != 0) { break; } LOGW("Media player service not published, waiting..."); usleep(500000); // 0.5 s } while(true); if (sDeathNotifier == NULL) { sDeathNotifier = new DeathNotifier(); } binder->linkToDeath(sDeathNotifier); sMediaPlayerService = interface_cast<IMediaPlayerService>(binder); } LOGE_IF(sMediaPlayerService == 0, "no media player service!?"); return sMediaPlayerService; }
函數首先通過defaultServiceManager函數來獲得Service Manager的遠程接口,實際上就是獲得BpServiceManager的IServiceManager接口,具體可以參考淺談Android系統進程間通信(IPC)機制Binder中的Server和Client獲得Service Manager接口之路一文。總的來說,這裡的語句:
sp<IServiceManager> sm = defaultServiceManager();
相當於是:
sp<IServiceManager> sm = new BpServiceManager(new BpBinder(0));
這裡的0表示Service Manager的遠程接口的句柄值是0。
接下去的while循環是通過sm->getService接口來不斷嘗試獲得名稱為“media.player”的Service,即MediaPlayerService。為什麼要通過這無窮循環來得MediaPlayerService呢?因為這時候MediaPlayerService可能還沒有啟動起來,所以這裡如果發現取回來的binder接口為NULL,就睡眠0.5秒,然後再嘗試獲取,這是獲取Service接口的標准做法。
我們來看一下BpServiceManager::getService的實現:
class BpServiceManager : public BpInterface<IServiceManager> { ...... virtual sp<IBinder> getService(const String16& name) const { unsigned n; for (n = 0; n < 5; n++){ sp<IBinder> svc = checkService(name); if (svc != NULL) return svc; LOGI("Waiting for service %s...\n", String8(name).string()); sleep(1); } return NULL; } virtual sp<IBinder> 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(); } ...... };
BpServiceManager::getService通過BpServiceManager::checkService執行操作。
在BpServiceManager::checkService中,首先是通過Parcel::writeInterfaceToken往data寫入一個RPC頭,這個我們在Android系統進程間通信(IPC)機制Binder中的Server啟動過程源代碼分析一文已經介紹過了,就是寫往data裡面寫入了一個整數和一個字符串“android.os.IServiceManager”, Service Manager來處理CHECK_SERVICE_TRANSACTION請求之前,會先驗證一下這個RPC頭,看看是否正確。接著再往data寫入一個字符串name,這裡就是“media.player”了。回憶一下Android系統進程間通信(IPC)機制Binder中的Server啟動過程源代碼分析這篇文章,那裡已經往Service Manager中注冊了一個名字為“media.player”的MediaPlayerService。
這裡的remote()返回的是一個BpBinder,具體可以參考淺談Android系統進程間通信(IPC)機制Binder中的Server和Client獲得Service Manager接口之路一文,於是,就進行到BpBinder::transact函數了:
status_t BpBinder::transact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { // Once a binder has died, it will never come back to life. if (mAlive) { status_t status = IPCThreadState::self()->transact( mHandle, code, data, reply, flags); if (status == DEAD_OBJECT) mAlive = 0; return status; } return DEAD_OBJECT; }
這裡的mHandle = 0,code = CHECK_SERVICE_TRANSACTION,flags = 0。
這裡再進入到IPCThread::transact函數中:
status_t IPCThreadState::transact(int32_t handle, uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { status_t err = data.errorCheck(); flags |= TF_ACCEPT_FDS; IF_LOG_TRANSACTIONS() { TextOutput::Bundle _b(alog); alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand " << handle << " / code " << TypeCode(code) << ": " << indent << data << dedent << endl; } if (err == NO_ERROR) { LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(), (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY"); err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL); } if (err != NO_ERROR) { if (reply) reply->setError(err); return (mLastError = err); } if ((flags & TF_ONE_WAY) == 0) { #if 0 if (code == 4) { // relayout LOGI(">>>>>> CALLING transaction 4"); } else { LOGI(">>>>>> CALLING transaction %d", code); } #endif if (reply) { err = waitForResponse(reply); } else { Parcel fakeReply; err = waitForResponse(&fakeReply); } #if 0 if (code == 4) { // relayout LOGI("<<<<<< RETURNING transaction 4"); } else { LOGI("<<<<<< RETURNING transaction %d", code); } #endif IF_LOG_TRANSACTIONS() { TextOutput::Bundle _b(alog); alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand " << handle << ": "; if (reply) alog << indent << *reply << dedent << endl; else alog << "(none requested)" << endl; } } else { err = waitForResponse(NULL, NULL); } return err; }
首先是調用函數writeTransactionData寫入將要傳輸的數據到IPCThreadState的成員變量mOut中去:
status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags, int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer) { binder_transaction_data tr; tr.target.handle = handle; tr.code = code; tr.flags = binderFlags; const status_t err = data.errorCheck(); if (err == NO_ERROR) { tr.data_size = data.ipcDataSize(); tr.data.ptr.buffer = data.ipcData(); tr.offsets_size = data.ipcObjectsCount()*sizeof(size_t); tr.data.ptr.offsets = data.ipcObjects(); } else if (statusBuffer) { tr.flags |= TF_STATUS_CODE; *statusBuffer = err; tr.data_size = sizeof(status_t); tr.data.ptr.buffer = statusBuffer; tr.offsets_size = 0; tr.data.ptr.offsets = NULL; } else { return (mLastError = err); } mOut.writeInt32(cmd); mOut.write(&tr, sizeof(tr)); return NO_ERROR; }
結構體binder_transaction_data在上一篇文章Android系統進程間通信(IPC)機制Binder中的Server啟動過程源代碼分析已經介紹過,這裡不再累述,這個結構體是用來描述要傳輸的參數的內容的。這裡著重描述一下將要傳輸的參數tr裡面的內容,handle = 0,code = CHECK_SERVICE_TRANSACTION,cmd = BC_TRANSACTION,data裡面的數據分別為:
writeInt32(IPCThreadState::self()->getStrictModePolicy() | STRICT_MODE_PENALTY_GATHER); writeString16("android.os.IServiceManager"); writeString16("media.player");
這是在BpServiceManager::checkService函數裡面寫進去的,其中前兩個是RPC頭,Service Manager在收到這個請求時會驗證這兩個參數是否正確,這點前面也提到了。IPCThread->getStrictModePolicy默認返回0,STRICT_MODE_PENALTY_GATHER定義為:
// Note: must be kept in sync with android/os/StrictMode.java's PENALTY_GATHER
#define STRICT_MODE_PENALTY_GATHER 0x100
我們不關心這個參數的含義,這不會影響我們分析下面的源代碼,有興趣的讀者可以研究一下。這裡要注意的是,要傳輸的參數不包含有Binder對象,因此tr.offsets_size = 0。要傳輸的參數最後寫入到IPCThreadState的成員變量mOut中,包括cmd和tr兩個數據。
回到IPCThread::transact函數中,由於(flags & TF_ONE_WAY) == 0為true,即這是一個同步請求,並且reply != NULL,
最終調用:
err = waitForResponse(reply);
進入到waitForResponse函數中:
status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult) { int32_t cmd; int32_t err; while (1) { if ((err=talkWithDriver()) < NO_ERROR) break; err = mIn.errorCheck(); if (err < NO_ERROR) break; if (mIn.dataAvail() == 0) continue; cmd = mIn.readInt32(); IF_LOG_COMMANDS() { alog << "Processing waitForResponse Command: " << getReturnString(cmd) << endl; } switch (cmd) { case BR_TRANSACTION_COMPLETE: if (!reply && !acquireResult) goto finish; break; case BR_DEAD_REPLY: err = DEAD_OBJECT; goto finish; case BR_FAILED_REPLY: err = FAILED_TRANSACTION; goto finish; case BR_ACQUIRE_RESULT: { LOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT"); const int32_t result = mIn.readInt32(); if (!acquireResult) continue; *acquireResult = result ? NO_ERROR : INVALID_OPERATION; } goto finish; 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 { err = *static_cast<const status_t*>(tr.data.ptr.buffer); freeBuffer(NULL, 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), this); } } else { freeBuffer(NULL, 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), this); continue; } } goto finish; default: err = executeCommand(cmd); if (err != NO_ERROR) goto finish; break; } } finish: if (err != NO_ERROR) { if (acquireResult) *acquireResult = err; if (reply) reply->setError(err); mLastError = err; } return err; }
這個函數通過IPCThreadState::talkWithDriver與驅動程序進行交互:
status_t IPCThreadState::talkWithDriver(bool doReceive) { LOG_ASSERT(mProcess->mDriverFD >= 0, "Binder driver is not opened"); binder_write_read bwr; // Is the read buffer empty? const bool needRead = mIn.dataPosition() >= mIn.dataSize(); // We don't want to write anything if we are still reading // from data left in the input buffer and the caller // has requested to read the next data. const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0; bwr.write_size = outAvail; bwr.write_buffer = (long unsigned int)mOut.data(); // This is what we'll read. if (doReceive && needRead) { bwr.read_size = mIn.dataCapacity(); bwr.read_buffer = (long unsigned int)mIn.data(); } else { bwr.read_size = 0; } ...... // Return immediately if there is nothing to do. if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR; bwr.write_consumed = 0; bwr.read_consumed = 0; status_t err; do { ...... #if defined(HAVE_ANDROID_OS) if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0) err = NO_ERROR; else err = -errno; #else err = INVALID_OPERATION; #endif ...... } while (err == -EINTR); ...... if (err >= NO_ERROR) { if (bwr.write_consumed > 0) { if (bwr.write_consumed < (ssize_t)mOut.dataSize()) mOut.remove(0, bwr.write_consumed); else mOut.setDataSize(0); } if (bwr.read_consumed > 0) { mIn.setDataSize(bwr.read_consumed); mIn.setDataPosition(0); } ...... return NO_ERROR; } return err; }
這裡的needRead為true,因此,bwr.read_size大於0;outAvail也大於0,因此,bwr.write_size也大於0。函數最後通過:
ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr)
進入到Binder驅動程序的binder_ioctl函數中。注意,這裡的mProcess->mDriverFD是在我們前面調用defaultServiceManager函數獲得Service Manager遠程接口時,打開的設備文件/dev/binder的文件描述符,mProcess是IPCSThreadState的成員變量。
Binder驅動程序的binder_ioctl函數中,我們只關注BINDER_WRITE_READ命令相關的邏輯:
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; unsigned int size = _IOC_SIZE(cmd); void __user *ubuf = (void __user *)arg; /*printk(KERN_INFO "binder_ioctl: %d:%d %x %lx\n", proc->pid, current->pid, cmd, arg);*/ ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2); if (ret) return ret; mutex_lock(&binder_lock); thread = binder_get_thread(proc); if (thread == NULL) { ret = -ENOMEM; goto err; } switch (cmd) { case BINDER_WRITE_READ: { struct binder_write_read bwr; if (size != sizeof(struct binder_write_read)) { ret = -EINVAL; goto err; } if (copy_from_user(&bwr, ubuf, sizeof(bwr))) { ret = -EFAULT; goto err; } if (binder_debug_mask & BINDER_DEBUG_READ_WRITE) printk(KERN_INFO "binder: %d:%d write %ld at %08lx, read %ld at %08lx\n", proc->pid, thread->pid, bwr.write_size, bwr.write_buffer, bwr.read_size, bwr.read_buffer); if (bwr.write_size > 0) { ret = binder_thread_write(proc, thread, (void __user *)bwr.write_buffer, bwr.write_size, &bwr.write_consumed); if (ret < 0) { bwr.read_consumed = 0; if (copy_to_user(ubuf, &bwr, sizeof(bwr))) ret = -EFAULT; goto err; } } if (bwr.read_size > 0) { ret = binder_thread_read(proc, thread, (void __user *)bwr.read_buffer, bwr.read_size, &bwr.read_consumed, filp->f_flags & O_NONBLOCK); if (!list_empty(&proc->todo)) wake_up_interruptible(&proc->wait); if (ret < 0) { if (copy_to_user(ubuf, &bwr, sizeof(bwr))) ret = -EFAULT; goto err; } } if (binder_debug_mask & BINDER_DEBUG_READ_WRITE) printk(KERN_INFO "binder: %d:%d wrote %ld of %ld, read return %ld of %ld\n", proc->pid, thread->pid, bwr.write_consumed, bwr.write_size, bwr.read_consumed, bwr.read_size); if (copy_to_user(ubuf, &bwr, sizeof(bwr))) { ret = -EFAULT; goto err; } break; } ...... default: ret = -EINVAL; goto err; } ret = 0; err: ...... return ret; }
這裡的filp->private_data的值是在defaultServiceManager函數創建ProcessState對象時,在ProcessState構造函數通過open文件操作函數打開設備文件/dev/binder時設置好的,它表示的是調用open函數打開設備文件/dev/binder的進程上下文信息,這裡將它取出來保存在proc本地變量中。
這裡的thread本地變量表示當前線程上下文信息,通過binder_get_thread函數獲得。在前面執行ProcessState構造函數時,也會通過ioctl文件操作函數進入到這個函數,那是第一次進入到binder_ioctl這裡,因此,調用binder_get_thread時,表示當前進程上下文信息的proc變量還沒有關於當前線程的上下文信息,因此,會為proc創建一個表示當前線程上下文信息的thread,會保存在proc->threads表示的紅黑樹結構中。這裡調用binder_get_thread就可以直接從proc找到並返回了。
進入到BINDER_WRITE_READ相關的邏輯。先看看BINDER_WRITE_READ的定義:
#define BINDER_WRITE_READ _IOWR('b', 1, struct binder_write_read)
這裡可以看出,BINDER_WRITE_READ命令的參數類型為struct binder_write_read:
struct binder_write_read { signed long write_size; /* bytes to write */ signed long write_consumed; /* bytes consumed by driver */ unsigned long write_buffer; signed long read_size; /* bytes to read */ signed long read_consumed; /* bytes consumed by driver */ unsigned long read_buffer; };
這個結構體的含義可以參考淺談Service Manager成為Android進程間通信(IPC)機制Binder守護進程之路一文。這裡首先是通過copy_from_user函數把用戶傳進來的參數的內容拷貝到本地變量bwr中。
從上面的調用過程,我們知道,這裡bwr.write_size是大於0的,因此進入到binder_thread_write函數中,我們只關注BC_TRANSACTION相關的邏輯:
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; } ...... default: printk(KERN_ERR "binder: %d:%d unknown command %d\n", proc->pid, thread->pid, cmd); return -EINVAL; } *consumed = ptr - buffer; } return 0; }
這裡再次把用戶傳出來的參數拷貝到本地變量tr中,tr的類型為struct binder_transaction_data,這個就是前面我們在IPCThreadState::writeTransactionData寫入的內容了。
接著進入到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) { ...... } else { if (tr->target.handle) { ...... } else { target_node = binder_context_mgr_node; if (target_node == NULL) { return_error = BR_DEAD_REPLY; goto err_no_context_mgr_node; } } ...... target_proc = target_node->proc; if (target_proc == NULL) { return_error = BR_DEAD_REPLY; goto err_dead_binder; } if (!(tr->flags & TF_ONE_WAY) && thread->transaction_stack) { ...... } } if (target_thread) { ...... } else { target_list = &target_proc->todo; target_wait = &target_proc->wait; } ...... /* 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; } binder_stats.obj_created[BINDER_STAT_TRANSACTION_COMPLETE]++; t->debug_id = ++binder_last_id; ...... 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)) { ...... return_error = BR_FAILED_REPLY; goto err_copy_data_failed; } ...... if (reply) { ...... } else if (!(t->flags & TF_ONE_WAY)) { BUG_ON(t->buffer->async_transaction != 0); t->need_reply = 1; t->from_parent = thread->transaction_stack; thread->transaction_stack = t; } 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; ...... }
注意,這裡的參數reply = 0,表示這是一個BC_TRANSACTION命令。
前面我們提到,傳給驅動程序的handle值為0,即這裡的tr->target.handle = 0,表示請求的目標Binder對象是Service Manager,因此有:
target_node = binder_context_mgr_node; target_proc = target_node->proc; target_list = &target_proc->todo; target_wait = &target_proc->wait;
其中binder_context_mgr_node是在Service Manager通知Binder驅動程序它是守護過程時創建的。
接著創建一個待完成事項tcomplete,它的類型為struct binder_work,這是等一會要保存在當前線程的todo隊列去的,表示當前線程有一個待完成的事務。緊跟著創建一個待處理事務t,它的類型為struct binder_transaction,這是等一會要存在到Service Manager的todo隊列去的,表示Service Manager當前有一個事務需要處理。同時,這個待處理事務t也要存放在當前線程的待完成事務transaction_stack列表中去:
t->from_parent = thread->transaction_stack;
thread->transaction_stack = t;
這樣表明當前線程還有事務要處理。
繼續往下看,就是分別把tcomplete和t放在當前線程thread和Service Manager進程的todo隊列去了:
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);
最後,Service Manager有事情可做了,就要喚醒它了:
wake_up_interruptible(target_wait);
前面我們提到,此時Service Manager正在等待Client的請求,也就是Service Manager此時正在進入到Binder驅動程序的binder_thread_read函數中,並且休眠在target->wait上,具體參考淺談Service Manager成為Android進程間通信(IPC)機制Binder守護進程之路一文。
這裡,我們暫時忽略Service Manager被喚醒之後的情景,繼續看當前線程的執行。
函數binder_transaction執行完成之後,就一路返回到binder_ioctl函數裡去了。函數binder_ioctl從binder_thread_write函數調用處返回後,發現bwr.read_size大於0,於是就進入到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; } if (end - ptr < sizeof(tr) + 4) break; 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); binder_stat_br(proc, thread, cmd); if (binder_debug_mask & BINDER_DEBUG_TRANSACTION_COMPLETE) printk(KERN_INFO "binder: %d:%d BR_TRANSACTION_COMPLETE\n", proc->pid, thread->pid); list_del(&w->entry); kfree(w); binder_stats.obj_deleted[BINDER_STAT_TRANSACTION_COMPLETE]++; } break; ...... } if (!t) continue; ...... } done: ...... return 0; }
函數首先是寫入一個操作碼BR_NOOP到用戶傳進來的緩沖區中去。
回憶一下上面的binder_transaction函數,這裡的thread->transaction_stack != NULL,並且thread->todo也不為空,所以線程不會進入休眠狀態。
進入while循環中,首先是從thread->todo隊列中取回待處理事項w,w的類型為BINDER_WORK_TRANSACTION_COMPLETE,這也是在binder_transaction函數裡面設置的。對BINDER_WORK_TRANSACTION_COMPLETE的處理也很簡單,只是把一個操作碼BR_TRANSACTION_COMPLETE寫回到用戶傳進來的緩沖區中去。這時候,用戶傳進來的緩沖區就包含兩個操作碼了,分別是BR_NOOP和BINDER_WORK_TRANSACTION_COMPLETE。
binder_thread_read執行完之後,返回到binder_ioctl函數中,將操作結果寫回到用戶空間中去:
if (copy_to_user(ubuf, &bwr, sizeof(bwr))) { ret = -EFAULT; goto err; }
最後就返回到IPCThreadState::talkWithDriver函數中了。
IPCThreadState::talkWithDriver函數從下面語句:
ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr)
返回後,首先是清空之前寫入Binder驅動程序的內容:
if (bwr.write_consumed > 0) { if (bwr.write_consumed < (ssize_t)mOut.dataSize()) mOut.remove(0, bwr.write_consumed); else mOut.setDataSize(0); }
接著是設置從Binder驅動程序讀取的內容:
if (bwr.read_consumed > 0) { mIn.setDataSize(bwr.read_consumed); mIn.setDataPosition(0); }
然後就返回到IPCThreadState::waitForResponse去了。IPCThreadState::waitForResponse函數的處理也很簡單,就是處理剛才從Binder驅動程序讀入內容了。從前面的分析中,我們知道,從Binder驅動程序讀入的內容就是兩個整數了,分別是BR_NOOP和BR_TRANSACTION_COMPLETE。對BR_NOOP的處理很簡單,正如它的名字所示,什麼也不做;而對BR_TRANSACTION_COMPLETE的處理,就分情況了,如果這個請求是異步的,那個整個BC_TRANSACTION操作就完成了,如果這個請求是同步的,即要等待回復的,也就是reply不為空,那麼還要繼續通過IPCThreadState::talkWithDriver進入到Binder驅動程序中去等待BC_TRANSACTION操作的處理結果。
這裡屬於後一種情況,於是再次通過IPCThreadState::talkWithDriver進入到Binder驅動程序的binder_ioctl函數中。不過這一次在binder_ioctl函數中,bwr.write_size等於0,而bwr.read_size大於0,於是再次進入到binder_thread_read函數中。這時候thread->transaction_stack仍然不為NULL,不過thread->todo隊列已經為空了,因為前面我們已經處理過thread->todo隊列的內容了,於是就通過下面語句:
ret = wait_event_interruptible(thread->wait, binder_has_thread_work(thread));
進入休眠狀態了,等待Service Manager的喚醒。
現在,我們終於可以回到Service Manager被喚醒之後的過程了。前面我們說過,Service Manager此時正在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) { ...... if (non_block) { if (!binder_has_proc_work(proc, thread)) ret = -EAGAIN; } else ret = wait_event_interruptible_exclusive(proc->wait, binder_has_proc_work(proc, thread)); } else { ...... } ...... 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; } if (end - ptr < sizeof(tr) + 4) 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) { struct binder_node *target_node = t->buffer->target_node; tr.target.ptr = target_node->ptr; tr.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); cmd = BR_TRANSACTION; } else { ...... } tr.code = t->code; tr.flags = t->flags; 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; 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)) { t->to_parent = thread->transaction_stack; t->to_thread = thread; thread->transaction_stack = t; } else { ...... } break; } done: *consumed = ptr - buffer; ...... return 0; }
這裡就是從語句中喚醒了:
ret = wait_event_interruptible_exclusive(proc->wait, binder_has_proc_work(proc, thread));
Service Manager喚醒過來看,繼續往下執行,進入到while循環中。首先是從proc->todo中取回待處理事項w。這個事項w的類型是BINDER_WORK_TRANSACTION,這是上面調用binder_transaction的時候設置的,於是通過w得到待處理事務t:
t = container_of(w, struct binder_transaction, work);
接下來的內容,就把cmd和t->buffer的內容拷貝到用戶傳進來的緩沖區去了,這裡就是Service Manager從用戶空間傳進來的緩沖區了:
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);
注意,這裡先是把t->buffer的內容拷貝到本地變量tr中,再拷貝到用戶空間緩沖區去。關於t->buffer內容的拷貝,請參考Android系統進程間通信(IPC)機制Binder中的Server啟動過程源代碼分析一文,它的一個關鍵地方是Binder驅動程序和Service Manager守護進程共享了同一個物理內存的內容,拷貝的只是這個物理內存在用戶空間的虛擬地址回去:
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 *));
對於Binder驅動程序這次操作來說,這個事項就算是處理完了,就要從todo隊列中刪除了:
list_del(&t->work.entry);
緊接著,還不放刪除這個事務,因為它還要等待Service Manager處理完成後,再進一步處理,因此,放在thread->transaction_stack隊列中:
t->to_parent = thread->transaction_stack;
t->to_thread = thread;
thread->transaction_stack = t;
還要注意的一個地方是,上面寫入的cmd = BR_TRANSACTION,告訴Service Manager守護進程,它要做什麼事情,後面我們會看到相應的分析。
這樣,binder_thread_read函數就處理完了,回到binder_ioctl函數中,同樣是操作結果寫回到用戶空間的緩沖區中去:
if (copy_to_user(ubuf, &bwr, sizeof(bwr))) { ret = -EFAULT; goto err; }
最後,就返回到frameworks/base/cmds/servicemanager/binder.c文件中的binder_loop函數去了:
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; binder_write(bs, readbuf, sizeof(unsigned)); for (;;) { bwr.read_size = sizeof(readbuf); bwr.read_consumed = 0; bwr.read_buffer = (unsigned) readbuf; res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr); if (res < 0) { LOGE("binder_loop: ioctl failed (%s)\n", strerror(errno)); break; } res = binder_parse(bs, 0, readbuf, bwr.read_consumed, func); 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; } } }
這裡就是從下面的語句:
res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);
返回來了。接著就進入binder_parse函數處理從Binder驅動程序裡面讀取出來的數據:
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) { ...... case BR_TRANSACTION: { struct binder_txn *txn = (void *) ptr; ...... 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); res = func(bs, txn, &msg, &reply); binder_send_reply(bs, &reply, txn->data, res); } ptr += sizeof(*txn) / sizeof(uint32_t); break; } ...... default: LOGE("parse: OOPS %d\n", cmd); return -1; } } return r; }
前面我們說過,Binder驅動程序寫入到用戶空間的緩沖區中的cmd為BR_TRANSACTION,因此,這裡我們只關注BR_TRANSACTION相關的邏輯。
這裡用到的兩個數據結構struct binder_txn和struct binder_io可以參考前面一篇文章Android系統進程間通信(IPC)機制Binder中的Server啟動過程源代碼分析,這裡就不復述了。
接著往下看,函數調bio_init來初始化reply變量:
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_from_txn來初始化msg變量:
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; }
最後,真正進行處理的函數是從參數中傳進來的函數指針func,這裡就是定義在frameworks/base/cmds/servicemanager/service_manager.c文件中的svcmgr_handler函數:
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; // LOGI("target=%p code=%d pid=%d uid=%d\n", // txn->target, txn->code, txn->sender_pid, txn->sender_euid); if (txn->target != svcmgr_handle) 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); s = bio_get_string16(msg, &len); 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) { case SVC_MGR_GET_SERVICE: case SVC_MGR_CHECK_SERVICE: s = bio_get_string16(msg, &len); ptr = do_find_service(bs, s, len); if (!ptr) break; bio_put_ref(reply, ptr); return 0; ...... } default: LOGE("unknown code %d\n", txn->code); return -1; } bio_put_uint32(reply, 0); return 0; }
這裡, Service Manager要處理的code是SVC_MGR_CHECK_SERVICE,這是在前面的BpServiceManager::checkService函數裡面設置的。
回憶一下,在BpServiceManager::checkService時,傳給Binder驅動程序的參數為:
writeInt32(IPCThreadState::self()->getStrictModePolicy() | STRICT_MODE_PENALTY_GATHER);
writeString16("android.os.IServiceManager");
writeString16("media.player");
這裡的語句:
strict_policy = bio_get_uint32(msg); s = bio_get_string16(msg, &len); s = bio_get_string16(msg, &len);
其中,會驗證一下傳進來的第二個參數,即"android.os.IServiceManager"是否正確,這個是驗證RPC頭,注釋已經說得很清楚了。
最後,就是調用do_find_service函數查找是存在名稱為"media.player"的服務了。回憶一下前面一篇文章Android系統進程間通信(IPC)機制Binder中的Server啟動過程源代碼分析,MediaPlayerService已經把一個名稱為"media.player"的服務注冊到Service Manager中,所以這裡一定能找到。我們看看do_find_service這個函數:
void *do_find_service(struct binder_state *bs, uint16_t *s, unsigned len) { struct svcinfo *si; si = find_svc(s, len); // LOGI("check_service('%s') ptr = %p\n", str8(s), si ? si->ptr : 0); if (si && si->ptr) { return si->ptr; } else { return 0; } }
這裡又調用了find_svc函數:
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; }
就是在svclist列表中查找對應名稱的svcinfo了。
然後返回到do_find_service函數中。回憶一下前面一篇文章Android系統進程間通信(IPC)機制Binder中的Server啟動過程源代碼分析,這裡的si->ptr就是指MediaPlayerService這個Binder實體在Service Manager進程中的句柄值了。
回到svcmgr_handler函數中,調用bio_put_ref函數將這個Binder引用寫回到reply參數。我們看看bio_put_ref的實現:
void bio_put_ref(struct binder_io *bio, void *ptr) { struct binder_object *obj; if (ptr) 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->pointer = ptr; obj->cookie = 0; }
這裡很簡單,就是把一個類型為BINDER_TYPE_HANDLE的binder_object寫入到reply緩沖區中去。這裡的binder_object就是相當於是flat_binder_obj了,具體可以參考Android系統進程間通信(IPC)機制Binder中的Server啟動過程源代碼分析一文。
再回到svcmgr_handler函數中,最後,還寫入一個0值到reply緩沖區中,表示操作結果碼:
bio_put_uint32(reply, 0);
最後返回到binder_parse函數中,調用binder_send_reply函數將操作結果反饋給Binder驅動程序:
void binder_send_reply(struct binder_state *bs, struct binder_io *reply, void *buffer_to_free, int status) { struct { uint32_t cmd_free; void *buffer; uint32_t cmd_reply; struct binder_txn txn; } __attribute__((packed)) data; data.cmd_free = BC_FREE_BUFFER; data.buffer = buffer_to_free; data.cmd_reply = BC_REPLY; data.txn.target = 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.offs_size = 0; data.txn.data = &status; data.txn.offs = 0; } else { data.txn.flags = 0; data.txn.data_size = reply->data - reply->data0; data.txn.offs_size = ((char*) reply->offs) - ((char*) reply->offs0); data.txn.data = reply->data0; data.txn.offs = reply->offs0; } binder_write(bs, &data, sizeof(data)); }
注意,這裡的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機制來進行進程間通信呢?這就是下一篇文章要介紹的內容了,敬請關注。
以上就是對Android IPC Binder Client獲得Server 遠程接口過程的源碼分析,後續繼續補充相關文章,謝謝大家對本站的支持!
效果圖:界面比較粗糙,主要看原理。這個界面主要包括以下幾部分1、座位2、左邊的排數3、左上方的縮略圖4、縮略圖中的紅色區域5、手指移動時跟隨移動6、兩個手指縮放時跟隨縮放
在平時開發過程中,MD5加密是一個比較常用的算法,最常見的使用場景就是在帳號注冊時,用戶輸入的密碼經md5加密後,傳輸至服務器保存起來。雖然md5加密經常用,但是md5的
手機卡未實名會停機、手機實名登記怎麼辦理呢?下文將為大家介紹針對即將於9月1日大規模推行的手機卡實名制認證,怎麼辦理呢?總的來說,辦理實名制可分為線下和線上
GPUImage 是iOS下一個開源的基於GPU的圖像處理庫,提供各種各樣的圖像處理濾鏡,並且支持照相機和攝像機的實時濾鏡。GPUImage for Android是它在