本文通過一個具體的例子來說明Binder機制中Server的啓動過程。我們知道,在Android系統中,提供了多媒體播放的功能,這個功能是以服務的形式來提供的。這裏,我們就通過分析MediaPlayerService的實現來了解Media Server的啓動過程。
首先,看一下MediaPlayerService的類圖,以便我們理解下面要描述的內容。
我們將要介紹的主角MediaPlayerService繼承於BnMediaPlayerService類,熟悉Binder機制的同學應該知道BnMediaPlayerService是一個Binder Native類,用來處理Client請求的。BnMediaPlayerService繼承於BnInterface<IMediaPlayerService>類,BnInterface是一個模板類,它定義在frameworks/base/include/binder/IInterface.h文件中:
- template<typename INTERFACE>
- class BnInterface : public INTERFACE, public BBinder
- {
- public:
- virtual sp<IInterface> queryLocalInterface(const String16& _descriptor);
- virtual const String16& getInterfaceDescriptor() const;
- protected:
- virtual IBinder* onAsBinder();
- };
實際上,BnMediaPlayerService並不是直接接收到Client處發送過來的請求,而是使用了IPCThreadState接收Client處發送過來的請求,而IPCThreadState又藉助了ProcessState類來與Binder驅動程序交互。有關IPCThreadState和ProcessState的關係,可以參考上一篇文章淺談Android系統進程間通信(IPC)機制Binder中的Server和Client獲得Service Manager接口之路,接下來也會有相應的描述。IPCThreadState接收到了Client處的請求後,就會調用BBinder類的transact函數,並傳入相關參數,BBinder類的transact函數最終調用BnMediaPlayerService類的onTransact函數,於是,就開始真正地處理Client的請求了。
瞭解了MediaPlayerService類結構之後,就要開始進入到本文的主題了。
首先,看看MediaPlayerService是如何啓動的。啓動MediaPlayerService的代碼位於frameworks/base/media/mediaserver/main_mediaserver.cpp文件中:
- int main(int argc, char** argv)
- {
- sp<ProcessState> proc(ProcessState::self());
- sp<IServiceManager> sm = defaultServiceManager();
- LOGI("ServiceManager: %p", sm.get());
- AudioFlinger::instantiate();
- MediaPlayerService::instantiate();
- CameraService::instantiate();
- AudioPolicyService::instantiate();
- ProcessState::self()->startThreadPool();
- IPCThreadState::self()->joinThreadPool();
- }
先看下面這句代碼:
- sp<ProcessState> proc(ProcessState::self());
- sp<ProcessState> ProcessState::self()
- {
- if (gProcess != NULL) return gProcess;
- AutoMutex _l(gProcessMutex);
- if (gProcess == NULL) gProcess = new ProcessState;
- return gProcess;
- }
- Mutex gProcessMutex;
- sp<ProcessState> gProcess;
- ProcessState::ProcessState()
- : mDriverFD(open_driver())
- , mVMStart(MAP_FAILED)
- , mManagesContexts(false)
- , mBinderContextCheckFunc(NULL)
- , mBinderContextUserData(NULL)
- , mThreadPoolStarted(false)
- , mThreadPoolSeq(1)
- {
- if (mDriverFD >= 0) {
- // XXX Ideally, there should be a specific define for whether we
- // have mmap (or whether we could possibly have the kernel module
- // availabla).
- #if !defined(HAVE_WIN32_IPC)
- // mmap the binder, providing a chunk of virtual address space to receive transactions.
- mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
- if (mVMStart == MAP_FAILED) {
- // *sigh*
- LOGE("Using /dev/binder failed: unable to mmap transaction memory.\n");
- close(mDriverFD);
- mDriverFD = -1;
- }
- #else
- mDriverFD = -1;
- #endif
- }
- if (mDriverFD < 0) {
- // Need to run without the driver, starting our own thread pool.
- }
- }
先看open_driver函數的實現,這個函數同樣位於frameworks/base/libs/binder/ProcessState.cpp文件中:
- static int open_driver()
- {
- if (gSingleProcess) {
- return -1;
- }
- int fd = open("/dev/binder", O_RDWR);
- if (fd >= 0) {
- fcntl(fd, F_SETFD, FD_CLOEXEC);
- int vers;
- #if defined(HAVE_ANDROID_OS)
- status_t result = ioctl(fd, BINDER_VERSION, &vers);
- #else
- status_t result = -1;
- errno = EPERM;
- #endif
- if (result == -1) {
- LOGE("Binder ioctl to obtain version failed: %s", strerror(errno));
- close(fd);
- fd = -1;
- }
- if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
- LOGE("Binder driver protocol does not match user space protocol!");
- close(fd);
- fd = -1;
- }
- #if defined(HAVE_ANDROID_OS)
- size_t maxThreads = 15;
- result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
- if (result == -1) {
- LOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
- }
- #endif
- } else {
- LOGW("Opening '/dev/binder' failed: %s\n", strerror(errno));
- }
- return fd;
- }
open在Binder驅動程序中的具體實現,請參考前面一篇文章淺談Service Manager成爲Android進程間通信(IPC)機制Binder守護進程之路,這裏不再重複描述。打開/dev/binder設備文件後,Binder驅動程序就爲MediaPlayerService進程創建了一個struct binder_proc結構體實例來維護MediaPlayerService進程上下文相關信息。
我們來看一下ioctl文件操作函數執行BINDER_VERSION命令的過程:
- status_t result = ioctl(fd, BINDER_VERSION, &vers);
- 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_VERSION:
- if (size != sizeof(struct binder_version)) {
- ret = -EINVAL;
- goto err;
- }
- if (put_user(BINDER_CURRENT_PROTOCOL_VERSION, &((struct binder_version *)ubuf)->protocol_version)) {
- ret = -EINVAL;
- goto err;
- }
- break;
- ......
- }
- ret = 0;
- err:
- ......
- return ret;
- }
很簡單,只是將BINDER_CURRENT_PROTOCOL_VERSION寫入到傳入的參數arg指向的用戶緩衝區中去就返回了。BINDER_CURRENT_PROTOCOL_VERSION是一個宏,定義在kernel/common/drivers/staging/android/binder.h文件中:
- /* This is the current protocol version. */
- #define BINDER_CURRENT_PROTOCOL_VERSION 7
- /* Use with BINDER_VERSION, driver fills in fields. */
- struct binder_version {
- /* driver protocol version -- increment with incompatible change */
- signed long protocol_version;
- };
這裏有一個重要的地方要注意的是,由於這裏是打開設備文件/dev/binder之後,第一次進入到binder_ioctl函數,因此,這裏調用binder_get_thread的時候,就會爲當前線程創建一個struct binder_thread結構體變量來維護線程上下文信息,具體可以參考淺談Service Manager成爲Android進程間通信(IPC)機制Binder守護進程之路一文。
接着我們再來看一下ioctl文件操作函數執行BINDER_SET_MAX_THREADS命令的過程:
- result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
這個函數調用最終進入到Binder驅動程序的binder_ioctl函數中,我們只關注BINDER_SET_MAX_THREADS相關的部分邏輯:
- 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_SET_MAX_THREADS:
- if (copy_from_user(&proc->max_threads, ubuf, sizeof(proc->max_threads))) {
- ret = -EINVAL;
- goto err;
- }
- break;
- ......
- }
- ret = 0;
- err:
- ......
- return ret;
- }
回到ProcessState的構造函數中,這裏還通過mmap函數來把設備文件/dev/binder映射到內存中,這個函數在淺談Service Manager成爲Android進程間通信(IPC)機制Binder守護進程之路一文也已經有詳細介紹,這裏不再重複描述。宏BINDER_VM_SIZE就定義在ProcessState.cpp文件中:
- #define BINDER_VM_SIZE ((1*1024*1024) - (4096 *2))
這樣,ProcessState全局唯一變量gProcess就創建完畢了,回到frameworks/base/media/mediaserver/main_mediaserver.cpp文件中的main函數,下一步是調用defaultServiceManager函數來獲得Service Manager的遠程接口,這個已經在上一篇文章淺談Android系統進程間通信(IPC)機制Binder中的Server和Client獲得Service Manager接口之路有詳細描述,讀者可以回過頭去參考一下。
再接下來,就進入到MediaPlayerService::instantiate函數把MediaPlayerService添加到Service Manger中去了。這個函數定義在frameworks/base/media/libmediaplayerservice/MediaPlayerService.cpp文件中:
- void MediaPlayerService::instantiate() {
- defaultServiceManager()->addService(
- String16("media.player"), new MediaPlayerService());
- }
在上一篇文章淺談Android系統進程間通信(IPC)機制Binder中的Server和Client獲得Service Manager接口之路中說到,defaultServiceManager返回的實際是一個BpServiceManger類實例,因此,我們看一下BpServiceManger::addService的實現,這個函數實現在frameworks/base/libs/binder/IServiceManager.cpp文件中:
- class BpServiceManager : public BpInterface<IServiceManager>
- {
- public:
- BpServiceManager(const sp<IBinder>& impl)
- : BpInterface<IServiceManager>(impl)
- {
- }
- ......
- virtual status_t addService(const String16& name, const sp<IBinder>& service)
- {
- Parcel data, reply;
- data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
- data.writeString16(name);
- data.writeStrongBinder(service);
- status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);
- return err == NO_ERROR ? reply.readExceptionCode()
- }
- ......
- };
先來看這一句的調用:
- data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
- // Write RPC headers. (previously just the interface token)
- status_t Parcel::writeInterfaceToken(const String16& interface)
- {
- writeInt32(IPCThreadState::self()->getStrictModePolicy() |
- STRICT_MODE_PENALTY_GATHER);
- // currently the interface identification token is just its name as a string
- return writeString16(interface);
- }
再來看下面的調用:
- data.writeString16(name);
往下看:
- data.writeStrongBinder(service);
- status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
- {
- return flatten_binder(ProcessState::self(), val, this);
- }
- /*
- * This is the flattened representation of a Binder object for transfer
- * between processes. The 'offsets' supplied as part of a binder transaction
- * contains offsets into the data where these structures occur. The Binder
- * driver takes care of re-writing the structure type and data as it moves
- * between processes.
- */
- struct flat_binder_object {
- /* 8 bytes for large_flat_header. */
- unsigned long type;
- unsigned long flags;
- /* 8 bytes of data. */
- union {
- void *binder; /* local object */
- signed long handle; /* remote object */
- };
- /* extra data associated with local object */
- void *cookie;
- };
我們進入到flatten_binder函數看看:
- status_t flatten_binder(const sp<ProcessState>& proc,
- const sp<IBinder>& binder, Parcel* out)
- {
- flat_binder_object obj;
- obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
- if (binder != NULL) {
- IBinder *local = binder->localBinder();
- if (!local) {
- BpBinder *proxy = binder->remoteBinder();
- if (proxy == NULL) {
- LOGE("null proxy");
- }
- const int32_t handle = proxy ? proxy->handle() : 0;
- obj.type = BINDER_TYPE_HANDLE;
- obj.handle = handle;
- obj.cookie = NULL;
- } else {
- obj.type = BINDER_TYPE_BINDER;
- obj.binder = local->getWeakRefs();
- obj.cookie = local;
- }
- } else {
- obj.type = BINDER_TYPE_BINDER;
- obj.binder = NULL;
- obj.cookie = NULL;
- }
- return finish_flatten_binder(binder, obj, out);
- }
- obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
傳進來的binder即爲MediaPlayerService::instantiate函數中new出來的MediaPlayerService實例,因此,不爲空。又由於MediaPlayerService繼承自BBinder類,它是一個本地Binder實體,因此binder->localBinder返回一個BBinder指針,而且肯定不爲空,於是執行下面語句:
- obj.type = BINDER_TYPE_BINDER;
- obj.binder = local->getWeakRefs();
- obj.cookie = local;
函數調用finish_flatten_binder來將這個flat_binder_obj寫入到Parcel中去:
- inline static status_t finish_flatten_binder(
- const sp<IBinder>& binder, const flat_binder_object& flat, Parcel* out)
- {
- return out->writeObject(flat, false);
- }
- status_t Parcel::writeObject(const flat_binder_object& val, bool nullMetaData)
- {
- const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;
- const bool enoughObjects = mObjectsSize < mObjectsCapacity;
- if (enoughData && enoughObjects) {
- restart_write:
- *reinterpret_cast<flat_binder_object*>(mData+mDataPos) = val;
- // Need to write meta-data?
- if (nullMetaData || val.binder != NULL) {
- mObjects[mObjectsSize] = mDataPos;
- acquire_object(ProcessState::self(), val, this);
- mObjectsSize++;
- }
- // remember if it's a file descriptor
- if (val.type == BINDER_TYPE_FD) {
- mHasFds = mFdsKnown = true;
- }
- return finishWrite(sizeof(flat_binder_object));
- }
- if (!enoughData) {
- const status_t err = growData(sizeof(val));
- if (err != NO_ERROR) return err;
- }
- if (!enoughObjects) {
- size_t newSize = ((mObjectsSize+2)*3)/2;
- size_t* objects = (size_t*)realloc(mObjects, newSize*sizeof(size_t));
- if (objects == NULL) return NO_MEMORY;
- mObjects = objects;
- mObjectsCapacity = newSize;
- }
- goto restart_write;
- }
- mObjects[mObjectsSize] = mDataPos;
再回到BpServiceManager::addService函數中,調用下面語句:
- status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);
- 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;
- }
再進入到IPCThreadState::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函數準備好一個struct binder_transaction_data結構體變量,這個是等一下要傳輸給Binder驅動程序的。struct binder_transaction_data的定義我們在淺談Service Manager成爲Android進程間通信(IPC)機制Binder守護進程之路一文中有詳細描述,讀者不妨回過去讀一下。這裏爲了方便描述,將struct binder_transaction_data的定義再次列出來:
- struct binder_transaction_data {
- /* The first two are only used for bcTRANSACTION and brTRANSACTION,
- * identifying the target and contents of the transaction.
- */
- union {
- size_t handle; /* target descriptor of command transaction */
- void *ptr; /* target descriptor of return transaction */
- } target;
- void *cookie; /* target object cookie */
- unsigned int code; /* transaction command */
- /* General information about the transaction. */
- unsigned int flags;
- pid_t sender_pid;
- uid_t sender_euid;
- size_t data_size; /* number of bytes of data */
- size_t offsets_size; /* number of bytes of offsets */
- /* If this transaction is inline, the data immediately
- * follows here; otherwise, it ends with a pointer to
- * the data buffer.
- */
- union {
- struct {
- /* transaction data */
- const void *buffer;
- /* offsets from buffer to flat_binder_object structs */
- const void *offsets;
- } ptr;
- uint8_t buf[8];
- } data;
- };
- 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;
- }
注意,這裏的cmd爲BC_TRANSACTION。 這個函數很簡單,在這個場景下,就是執行下面語句來初始化本地變量tr:
- 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();
- writeInt32(IPCThreadState::self()->getStrictModePolicy() |
- STRICT_MODE_PENALTY_GATHER);
- writeString16("android.os.IServiceManager");
- writeString16("media.player");
- writeStrongBinder(new MediaPlayerService());
回到IPCThreadState::transact函數中,接下去看,(flags & TF_ONE_WAY) == 0爲true,並且reply不爲空,所以最終進入到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;
- }
- 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;
- }
- IF_LOG_COMMANDS() {
- TextOutput::Bundle _b(alog);
- if (outAvail != 0) {
- alog << "Sending commands to driver: " << indent;
- const void* cmds = (const void*)bwr.write_buffer;
- const void* end = ((const uint8_t*)cmds)+bwr.write_size;
- alog << HexDump(cmds, bwr.write_size) << endl;
- while (cmds < end) cmds = printCommand(alog, cmds);
- alog << dedent;
- }
- alog << "Size of receive buffer: " << bwr.read_size
- << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
- }
- // 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_LOG_COMMANDS() {
- alog << "About to read/write, write size = " << mOut.dataSize() << endl;
- }
- #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
- IF_LOG_COMMANDS() {
- alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
- }
- } while (err == -EINTR);
- IF_LOG_COMMANDS() {
- alog << "Our err: " << (void*)err << ", write consumed: "
- << bwr.write_consumed << " (of " << mOut.dataSize()
- << "), read consumed: " << bwr.read_consumed << endl;
- }
- 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);
- }
- IF_LOG_COMMANDS() {
- TextOutput::Bundle _b(alog);
- alog << "Remaining data size: " << mOut.dataSize() << endl;
- alog << "Received commands from driver: " << indent;
- const void* cmds = mIn.data();
- const void* end = mIn.data() + mIn.dataSize();
- alog << HexDump(cmds, mIn.dataSize()) << endl;
- while (cmds < end) cmds = printReturnCommand(alog, cmds);
- alog << dedent;
- }
- return NO_ERROR;
- }
- return err;
- }
最後,通過ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr)進行到Binder驅動程序的binder_ioctl函數,我們只關注cmd爲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;
- }
- ......
- }
- ret = 0;
- err:
- ......
- return ret;
- }
- 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;
- }
- 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 (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;
- }
- ......
- 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)) {
- ......
- return_error = BR_FAILED_REPLY;
- goto err_copy_data_failed;
- }
- if (copy_from_user(offp, tr->data.ptr.offsets, tr->offsets_size)) {
- ......
- 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_BINDER:
- case BINDER_TYPE_WEAK_BINDER: {
- struct binder_ref *ref;
- struct binder_node *node = binder_get_node(proc, fp->binder);
- if (node == NULL) {
- node = binder_new_node(proc, fp->binder, fp->cookie);
- if (node == NULL) {
- return_error = BR_FAILED_REPLY;
- goto err_binder_new_node_failed;
- }
- node->min_priority = fp->flags & FLAT_BINDER_FLAG_PRIORITY_MASK;
- node->accept_fds = !!(fp->flags & FLAT_BINDER_FLAG_ACCEPTS_FDS);
- }
- if (fp->cookie != node->cookie) {
- ......
- goto err_binder_get_ref_for_node_failed;
- }
- ref = binder_get_ref_for_node(target_proc, node);
- if (ref == NULL) {
- return_error = BR_FAILED_REPLY;
- goto err_binder_get_ref_for_node_failed;
- }
- if (fp->type == BINDER_TYPE_BINDER)
- fp->type = BINDER_TYPE_HANDLE;
- else
- fp->type = BINDER_TYPE_WEAK_HANDLE;
- fp->handle = ref->desc;
- binder_inc_ref(ref, fp->type == BINDER_TYPE_HANDLE, &thread->todo);
- ......
- } break;
- ......
- }
- }
- 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;
- ......
- }
- target_node = binder_context_mgr_node;
- target_proc = target_node->proc;
- 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;
- }
- ......
- 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)) {
- ......
- return_error = BR_FAILED_REPLY;
- goto err_copy_data_failed;
- }
- if (copy_from_user(offp, tr->data.ptr.offsets, tr->offsets_size)) {
- ......
- return_error = BR_FAILED_REPLY;
- goto err_copy_data_failed;
- }
- t->buffer = binder_alloc_buf(target_proc, tr->data_size,
- tr->offsets_size, !reply && (t->flags & TF_ONE_WAY));
- 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 (copy_from_user(offp, tr->data.ptr.offsets, tr->offsets_size)) {
- ......
- return_error = BR_FAILED_REPLY;
- goto err_copy_data_failed;
- }
- if (target_node)
- binder_inc_node(target_node, 1, 0, NULL);
- switch (fp->type) {
- case BINDER_TYPE_BINDER:
- case BINDER_TYPE_WEAK_BINDER: {
- struct binder_ref *ref;
- struct binder_node *node = binder_get_node(proc, fp->binder);
- if (node == NULL) {
- node = binder_new_node(proc, fp->binder, fp->cookie);
- if (node == NULL) {
- return_error = BR_FAILED_REPLY;
- goto err_binder_new_node_failed;
- }
- node->min_priority = fp->flags & FLAT_BINDER_FLAG_PRIORITY_MASK;
- node->accept_fds = !!(fp->flags & FLAT_BINDER_FLAG_ACCEPTS_FDS);
- }
- if (fp->cookie != node->cookie) {
- ......
- goto err_binder_get_ref_for_node_failed;
- }
- ref = binder_get_ref_for_node(target_proc, node);
- if (ref == NULL) {
- return_error = BR_FAILED_REPLY;
- goto err_binder_get_ref_for_node_failed;
- }
- if (fp->type == BINDER_TYPE_BINDER)
- fp->type = BINDER_TYPE_HANDLE;
- else
- fp->type = BINDER_TYPE_WEAK_HANDLE;
- fp->handle = ref->desc;
- binder_inc_ref(ref, fp->type == BINDER_TYPE_HANDLE, &thread->todo);
- ......
- } break;
現在,由於要把這個Binder實體MediaPlayerService交給target_proc,也就是Service Manager來管理,也就是說Service Manager要引用這個MediaPlayerService了,於是通過binder_get_ref_for_node爲MediaPlayerService創建一個引用,並且通過binder_inc_ref來增加這個引用計數,防止這個引用還在使用過程當中就被銷燬。注意,到了這裏的時候,t->buffer中的flat_binder_obj的type已經改爲BINDER_TYPE_HANDLE,handle已經改爲ref->desc,跟原來不一樣了,因爲這個flat_binder_obj是最終是要傳給Service Manager的,而Service Manager只能夠通過句柄值來引用這個Binder實體。
最後,把待處理事務加入到target_list列表中去:
- list_add_tail(&t->work.entry, target_list);
- list_add_tail(&tcomplete->entry, &thread->todo);
- if (target_wait)
- wake_up_interruptible(target_wait);
這裏我們先忽略一下Service Manager被喚醒之後的場景,繼續MedaPlayerService的啓動過程,然後再回來。
回到binder_ioctl函數,bwr.read_size > 0爲true,於是進入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;
- }
這裏,thread->transaction_stack和thread->todo均不爲空,於是wait_for_proc_work爲false,由於binder_has_thread_work的時候,返回true,這裏因爲thread->todo不爲空,因此,線程雖然調用了wait_event_interruptible,但是不會睡眠,於是繼續往下執行。
由於thread->todo不爲空,執行下列語句:
- if (!list_empty(&thread->todo))
- w = list_first_entry(&thread->todo, struct binder_work, entry);
- 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_ioctl函數返回到用戶空間之前,把數據消耗情況拷貝回用戶空間中:
- if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {
- ret = -EFAULT;
- goto err;
- }
- 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) {
- <pre name="code" class="cpp"> mIn.setDataSize(bwr.read_consumed);
- mIn.setDataPosition(0);
- mOut.setDataSize(0);
- mIn.setDataSize(bwr.read_consumed);
- mIn.setDataPosition(0);
這時候,下面語句執行後:
- const bool needRead = mIn.dataPosition() >= mIn.dataSize();
這時候,下面語句執行後:
- const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
- switch (cmd) {
- case BR_TRANSACTION_COMPLETE:
- if (!reply && !acquireResult) goto finish;
- break;
- ......
- }
這次,needRead就爲true了,而outAvail仍爲0,所以bwr.read_size不爲0,bwr.write_size爲0。於是通過:
- ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr)
- wait_event_interruptible(thread->wait, binder_has_thread_work(thread));
現在,我們可以回到Service Manager被喚醒的過程了。我們接着前面淺談Service Manager成爲Android進程間通信(IPC)機制Binder守護進程之路這篇文章的最後,繼續描述。此時, Service Manager正在binder_thread_read函數中調用wait_event_interruptible_exclusive進入休眠狀態。上面被MediaPlayerService啓動後進程喚醒後,繼續執行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;
- ......
- 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.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)) {
- t->to_parent = thread->transaction_stack;
- t->to_thread = thread;
- thread->transaction_stack = t;
- } else {
- t->buffer->transaction = NULL;
- kfree(t);
- binder_stats.obj_deleted[BINDER_STAT_TRANSACTION]++;
- }
- break;
- }
- done:
- ......
- return 0;
- }
Service Manager被喚醒之後,就進入while循環開始處理事務了。這裏wait_for_proc_work等於1,並且proc->todo不爲空,所以從proc->todo列表中得到第一個工作項:
- w = list_first_entry(&proc->todo, struct binder_work, entry);
- t = container_of(w, struct binder_transaction, work);
- 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;
- ......
- 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.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 *));
- 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 *));
接着就是把tr的內容拷貝到用戶傳進來的緩衝區去了,指針ptr指向這個用戶緩衝區的地址:
- 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);
最後,由於已經處理了這個事務,要把它從todo列表中刪除:
- list_del(&t->work.entry);
- t->buffer->allow_user_free = 1;
- if (cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)) {
- t->to_parent = thread->transaction_stack;
- t->to_thread = thread;
- thread->transaction_stack = t;
- } else {
- t->buffer->transaction = NULL;
- kfree(t);
- binder_stats.obj_deleted[BINDER_STAT_TRANSACTION]++;
- }
- t->to_parent = thread->transaction_stack;
- t->to_thread = thread;
- thread->transaction_stack = t;
這個while最後通過一個break跳了出來,最後返回到binder_ioctl函數中:
- 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;
- ......
- 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 (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 (copy_to_user(ubuf, &bwr, sizeof(bwr))) {
- ret = -EFAULT;
- goto err;
- }
- break;
- }
- ......
- default:
- ret = -EINVAL;
- goto err;
- }
- ret = 0;
- err:
- ......
- return ret;
- }
這裏就是返回到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;
- }
- }
- }
- 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++;
- ......
- case BR_TRANSACTION: {
- struct binder_txn *txn = (void *) ptr;
- if ((end - ptr) * sizeof(uint32_t) < sizeof(struct binder_txn)) {
- LOGE("parse: txn too small!\n");
- return -1;
- }
- binder_dump_txn(txn);
- 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;
- }
- struct binder_txn
- {
- void *target;
- void *cookie;
- uint32_t code;
- uint32_t flags;
- uint32_t sender_pid;
- uint32_t sender_euid;
- uint32_t data_size;
- uint32_t offs_size;
- void *data;
- void *offs;
- };
- struct binder_io
- {
- char *data; /* pointer to read/write from */
- uint32_t *offs; /* array of offsets */
- uint32_t data_avail; /* bytes available in data buffer */
- uint32_t offs_avail; /* entries available in offsets array */
- char *data0; /* start of data buffer */
- uint32_t *offs0; /* start of offsets buffer */
- uint32_t flags;
- uint32_t unused;
- };
- void bio_init(struct binder_io *bio, void *data,
- uint32_t maxdata, uint32_t maxoffs)
- {
- uint32_t n = maxoffs * sizeof(uint32_t);
- if (n > maxdata) {
- bio->flags = BIO_F_OVERFLOW;
- bio->data_avail = 0;
- bio->offs_avail = 0;
- return;
- }
- bio->data = bio->data0 = data + n;
- bio->offs = bio->offs0 = data;
- bio->data_avail = maxdata - n;
- bio->offs_avail = maxoffs;
- bio->flags = 0;
- }
- 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;
- }
- int svcmgr_handler(struct binder_state *bs,
- struct binder_txn *txn,
- struct binder_io *msg,
- struct binder_io *reply)
- {
- struct svcinfo *si;
- uint16_t *s;
- unsigned len;
- void *ptr;
- uint32_t strict_policy;
- if (txn->target != svcmgr_handle)
- 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_ADD_SERVICE:
- s = bio_get_string16(msg, &len);
- ptr = bio_get_ref(msg);
- if (do_add_service(bs, s, len, ptr, txn->sender_euid))
- return -1;
- break;
- ......
- }
- bio_put_uint32(reply, 0);
- return 0;
- }
- writeInt32(IPCThreadState::self()->getStrictModePolicy() | STRICT_MODE_PENALTY_GATHER);
- writeString16("android.os.IServiceManager");
- writeString16("media.player");
- writeStrongBinder(new MediaPlayerService());
- strict_policy = bio_get_uint32(msg);
- s = bio_get_string16(msg, &len);
- s = bio_get_string16(msg, &len);
- ptr = bio_get_ref(msg);
- struct binder_object
- {
- uint32_t type;
- uint32_t flags;
- void *pointer;
- void *cookie;
- };
接着看bio_get_ref實現:
- void *bio_get_ref(struct binder_io *bio)
- {
- struct binder_object *obj;
- obj = _bio_get_obj(bio);
- if (!obj)
- return 0;
- if (obj->type == BINDER_TYPE_HANDLE)
- return obj->pointer;
- return 0;
- }
回到svcmgr_handler函數,調用do_add_service進一步處理:
- int do_add_service(struct binder_state *bs,
- uint16_t *s, unsigned len,
- void *ptr, unsigned uid)
- {
- struct svcinfo *si;
- // LOGI("add_service('%s',%p) uid=%d\n", str8(s), ptr, uid);
- if (!ptr || (len == 0) || (len > 127))
- return -1;
- if (!svc_can_register(uid, s)) {
- LOGE("add_service('%s',%p) uid=%d - PERMISSION DENIED\n",
- str8(s), ptr, uid);
- return -1;
- }
- si = find_svc(s, len);
- if (si) {
- if (si->ptr) {
- LOGE("add_service('%s',%p) uid=%d - ALREADY REGISTERED\n",
- str8(s), ptr, uid);
- return -1;
- }
- si->ptr = ptr;
- } else {
- si = malloc(sizeof(*si) + (len + 1) * sizeof(uint16_t));
- if (!si) {
- LOGE("add_service('%s',%p) uid=%d - OUT OF MEMORY\n",
- str8(s), ptr, uid);
- return -1;
- }
- si->ptr = ptr;
- si->len = len;
- memcpy(si->name, s, (len + 1) * sizeof(uint16_t));
- si->name[len] = '\0';
- si->death.func = svcinfo_death;
- si->death.ptr = si;
- si->next = svclist;
- svclist = si;
- }
- binder_acquire(bs, ptr);
- binder_link_to_death(bs, ptr, &si->death);
- return 0;
- }
這個函數執行完成後,返回到svcmgr_handler函數,函數的最後,將一個錯誤碼0寫到reply變量中去,表示一切正常:
- bio_put_uint32(reply, 0);
svcmgr_handler函數執行完成後,返回到binder_parse函數,執行下面語句:
- binder_send_reply(bs, &reply, txn->data, res);
- 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));
- }
再來看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;
- }
這裏又是一個ioctl的BINDER_WRITE_READ操作。直入到驅動程序的binder_ioctl函數後,執行BINDER_WRITE_READ命令,這裏就不累述了。
最後,從binder_ioctl執行到binder_thread_write函數,我們首先看第一個命令BC_FREE_BUFFER:
- 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_FREE_BUFFER: {
- void __user *data_ptr;
- struct binder_buffer *buffer;
- if (get_user(data_ptr, (void * __user *)ptr))
- return -EFAULT;
- ptr += sizeof(void *);
- buffer = binder_buffer_lookup(proc, data_ptr);
- if (buffer == NULL) {
- binder_user_error("binder: %d:%d "
- "BC_FREE_BUFFER u%p no match\n",
- proc->pid, thread->pid, data_ptr);
- break;
- }
- if (!buffer->allow_user_free) {
- binder_user_error("binder: %d:%d "
- "BC_FREE_BUFFER u%p matched "
- "unreturned buffer\n",
- proc->pid, thread->pid, data_ptr);
- break;
- }
- if (binder_debug_mask & BINDER_DEBUG_FREE_BUFFER)
- printk(KERN_INFO "binder: %d:%d BC_FREE_BUFFER u%p found buffer %d for %s transaction\n",
- proc->pid, thread->pid, data_ptr, buffer->debug_id,
- buffer->transaction ? "active" : "finished");
- if (buffer->transaction) {
- buffer->transaction->buffer = NULL;
- buffer->transaction = NULL;
- }
- if (buffer->async_transaction && buffer->target_node) {
- BUG_ON(!buffer->target_node->has_async_transaction);
- if (list_empty(&buffer->target_node->async_todo))
- buffer->target_node->has_async_transaction = 0;
- else
- list_move_tail(buffer->target_node->async_todo.next, &thread->todo);
- }
- binder_transaction_buffer_release(proc, buffer, NULL);
- binder_free_buf(proc, buffer);
- break;
- }
- ......
- *consumed = ptr - buffer;
- }
- return 0;
- }
- get_user(data_ptr, (void * __user *)ptr)
- buffer = binder_buffer_lookup(proc, data_ptr);
最後,就可以釋放這塊內存了:
- binder_transaction_buffer_release(proc, buffer, NULL);
- binder_free_buf(proc, buffer);
- 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;
- }
- 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;
- }
- binder_set_nice(in_reply_to->saved_priority);
- if (in_reply_to->to_thread != thread) {
- .......
- goto err_bad_call_stack;
- }
- thread->transaction_stack = in_reply_to->to_parent;
- target_thread = in_reply_to->from;
- if (target_thread == NULL) {
- return_error = BR_DEAD_REPLY;
- goto err_dead_binder;
- }
- if (target_thread->transaction_stack != in_reply_to) {
- ......
- return_error = BR_FAILED_REPLY;
- in_reply_to = NULL;
- target_thread = NULL;
- goto err_dead_binder;
- }
- 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;
- }
- 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;
- }
- ......
- 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;
- ......
- }
前面Service Manager正在binder_thread_read函數中被MediaPlayerService啓動後進程喚醒後,在最後會把當前處理完的事務放在thread->transaction_stack中:
- if (cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)) {
- t->to_parent = thread->transaction_stack;
- t->to_thread = thread;
- thread->transaction_stack = t;
- }
- in_reply_to = thread->transaction_stack;
- target_thread = in_reply_to->from;
- target_proc = target_thread->proc;
- target_list = &target_thread->todo;
- target_wait = &target_thread->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;
- }
- 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;
- }
函數本來有一個for循環,用來處理數據中的Binder對象,這裏由於沒有Binder對象,所以就略過了。到了下面這句代碼:
- binder_pop_transaction(target_thread, in_reply_to);
- static void
- binder_pop_transaction(
- struct binder_thread *target_thread, struct binder_transaction *t)
- {
- if (target_thread) {
- BUG_ON(target_thread->transaction_stack != t);
- BUG_ON(target_thread->transaction_stack->from != target_thread);
- target_thread->transaction_stack =
- target_thread->transaction_stack->from_parent;
- t->from = NULL;
- }
- t->need_reply = 0;
- if (t->buffer)
- t->buffer->transaction = NULL;
- kfree(t);
- binder_stats.obj_deleted[BINDER_STAT_TRANSACTION]++;
- }
回到binder_transaction函數:
- 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);
最後,喚醒等待在target_wait隊列上的線程了,就是最初調用IServiceManager::addService的MediaPlayerService的Server主線程了,它最後在binder_thread_read函數中睡眠在thread->wait上,就是這裏的target_wait了:
- if (target_wait)
- wake_up_interruptible(target_wait);
- list_add_tail(&tcomplete->entry, &thread->todo);
- 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;
- ......
- }
上面講到調用IServiceManager::addService的MediaPlayerService的Server主線程被喚醒了,於是,重新執行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;
- }
執行完這個函數後,就返回到binder_ioctl函數,執行下面語句,把數據返回給用戶空間:
- if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {
- ret = -EFAULT;
- goto err;
- }
- 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);
從這裏層層返回,最後回到MediaPlayerService::instantiate函數中。
至此,IServiceManager::addService終於執行完畢了。這個過程非常複雜,但是如果我們能夠深刻地理解這一過程,將能很好地理解Binder機制的設計思想和實現過程。這裏,對IServiceManager::addService過程中MediaPlayerService、ServiceManager和BinderDriver之間的交互作一個小結:
回到frameworks/base/media/mediaserver/main_mediaserver.cpp文件中的main函數,接下去還要執行下面兩個函數:
- ProcessState::self()->startThreadPool();
- IPCThreadState::self()->joinThreadPool();
- void ProcessState::startThreadPool()
- {
- AutoMutex _l(mLock);
- if (!mThreadPoolStarted) {
- mThreadPoolStarted = true;
- spawnPooledThread(true);
- }
- }
- void ProcessState::spawnPooledThread(bool isMain)
- {
- if (mThreadPoolStarted) {
- int32_t s = android_atomic_add(1, &mThreadPoolSeq);
- char buf[32];
- sprintf(buf, "Binder Thread #%d", s);
- LOGV("Spawning new pooled thread, name=%s\n", buf);
- sp<Thread> t = new PoolThread(isMain);
- t->run(buf);
- }
- }
- virtual bool threadLoop()
- {
- IPCThreadState::self()->joinThreadPool(mIsMain);
- return false;
- }
- void IPCThreadState::joinThreadPool(bool isMain)
- {
- LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
- mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
- ......
- status_t result;
- do {
- int32_t cmd;
- .......
- // now get the next command to be processed, waiting if necessary
- result = talkWithDriver();
- if (result >= NO_ERROR) {
- size_t IN = mIn.dataAvail();
- if (IN < sizeof(int32_t)) continue;
- cmd = mIn.readInt32();
- ......
- }
- result = executeCommand(cmd);
- }
- ......
- } while (result != -ECONNREFUSED && result != -EBADF);
- .......
- mOut.writeInt32(BC_EXIT_LOOPER);
- talkWithDriver(false);
- }
- status_t IPCThreadState::executeCommand(int32_t cmd)
- {
- BBinder* obj;
- RefBase::weakref_type* refs;
- status_t result = NO_ERROR;
- switch (cmd) {
- ......
- case BR_TRANSACTION:
- {
- binder_transaction_data tr;
- result = mIn.read(&tr, sizeof(tr));
- ......
- Parcel reply;
- ......
- if (tr.target.ptr) {
- sp<BBinder> b((BBinder*)tr.cookie);
- const status_t error = b->transact(tr.code, buffer, &reply, tr.flags);
- if (error < NO_ERROR) reply.setError(error);
- } else {
- const status_t error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
- if (error < NO_ERROR) reply.setError(error);
- }
- ......
- }
- break;
- .......
- }
- if (result != NO_ERROR) {
- mLastError = result;
- }
- return result;
- }
- status_t BBinder::transact(
- uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
- {
- data.setDataPosition(0);
- status_t err = NO_ERROR;
- switch (code) {
- case PING_TRANSACTION:
- reply->writeInt32(pingBinder());
- break;
- default:
- err = onTransact(code, data, reply, flags);
- break;
- }
- if (reply != NULL) {
- reply->setDataPosition(0);
- }
- return err;
- }
- status_t BnMediaPlayerService::onTransact(
- uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
- {
- switch(code) {
- case CREATE_URL: {
- ......
- } break;
- case CREATE_FD: {
- ......
- } break;
- case DECODE_URL: {
- ......
- } break;
- case DECODE_FD: {
- ......
- } break;
- case CREATE_MEDIA_RECORDER: {
- ......
- } break;
- case CREATE_METADATA_RETRIEVER: {
- ......
- } break;
- case GET_OMX: {
- ......
- } break;
- default:
- return BBinder::onTransact(code, data, reply, flags);
- }
- }
至此,我們就以MediaPlayerService爲例,完整地介紹了Android系統進程間通信Binder機制中的Server啓動過程。Server啓動起來之後,就會在一個無窮循環中等待Client的請求了。在下一篇文章中,我們將介紹Client如何通過Service Manager遠程接口來獲得Server遠程接口,進而調用Server遠程接口來使用Server提供的服務,敬請關注。