Android系統進程間通信(IPC)機制Binder中的Server啓動過程源代碼分析

在前面一篇文章淺談Android系統進程間通信(IPC)機制Binder中的Server和Client獲得Service Manager接口之路中,介紹了在Android系統中Binder進程間通信機制中的Server角色是如何獲得Service Manager遠程接口的,即defaultServiceManager函數的實現。Server獲得了Service Manager遠程接口之後,就要把自己的Service添加到Service Manager中去,然後把自己啓動起來,等待Client的請求。本文將通過分析源代碼瞭解Server的啓動過程是怎麼樣的。

        本文通過一個具體的例子來說明Binder機制中Server的啓動過程。我們知道,在Android系統中,提供了多媒體播放的功能,這個功能是以服務的形式來提供的。這裏,我們就通過分析MediaPlayerService的實現來了解Media Server的啓動過程。

        首先,看一下MediaPlayerService的類圖,以便我們理解下面要描述的內容。


        我們將要介紹的主角MediaPlayerService繼承於BnMediaPlayerService類,熟悉Binder機制的同學應該知道BnMediaPlayerService是一個Binder Native類,用來處理Client請求的。BnMediaPlayerService繼承於BnInterface<IMediaPlayerService>類,BnInterface是一個模板類,它定義在frameworks/base/include/binder/IInterface.h文件中:

  1. template<typename INTERFACE>  
  2. class BnInterface : public INTERFACE, public BBinder  
  3. {  
  4. public:  
  5.     virtual sp<IInterface>      queryLocalInterface(const String16& _descriptor);  
  6.     virtual const String16&     getInterfaceDescriptor() const;  
  7.   
  8. protected:  
  9.     virtual IBinder*            onAsBinder();  
  10. };  
       這裏可以看出,BnMediaPlayerService實際是繼承了IMediaPlayerService和BBinder類。IMediaPlayerService和BBinder類又分別繼承了IInterface和IBinder類,IInterface和IBinder類又同時繼承了RefBase類。

       實際上,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文件中:

  1. int main(int argc, char** argv)  
  2. {  
  3.     sp<ProcessState> proc(ProcessState::self());  
  4.     sp<IServiceManager> sm = defaultServiceManager();  
  5.     LOGI("ServiceManager: %p", sm.get());  
  6.     AudioFlinger::instantiate();  
  7.     MediaPlayerService::instantiate();  
  8.     CameraService::instantiate();  
  9.     AudioPolicyService::instantiate();  
  10.     ProcessState::self()->startThreadPool();  
  11.     IPCThreadState::self()->joinThreadPool();  
  12. }  
       這裏我們不關注AudioFlinger和CameraService相關的代碼。

       先看下面這句代碼:

  1. sp<ProcessState> proc(ProcessState::self());  
       這句代碼的作用是通過ProcessState::self()調用創建一個ProcessState實例。ProcessState::self()是ProcessState類的一個靜態成員變量,定義在frameworks/base/libs/binder/ProcessState.cpp文件中:
  1. sp<ProcessState> ProcessState::self()  
  2. {  
  3.     if (gProcess != NULL) return gProcess;  
  4.       
  5.     AutoMutex _l(gProcessMutex);  
  6.     if (gProcess == NULL) gProcess = new ProcessState;  
  7.     return gProcess;  
  8. }  
       這裏可以看出,這個函數作用是返回一個全局唯一的ProcessState實例gProcess。全局唯一實例變量gProcess定義在frameworks/base/libs/binder/Static.cpp文件中:
  1. Mutex gProcessMutex;  
  2. sp<ProcessState> gProcess;  
       再來看ProcessState的構造函數:
  1. ProcessState::ProcessState()  
  2.     : mDriverFD(open_driver())  
  3.     , mVMStart(MAP_FAILED)  
  4.     , mManagesContexts(false)  
  5.     , mBinderContextCheckFunc(NULL)  
  6.     , mBinderContextUserData(NULL)  
  7.     , mThreadPoolStarted(false)  
  8.     , mThreadPoolSeq(1)  
  9. {  
  10.     if (mDriverFD >= 0) {  
  11.         // XXX Ideally, there should be a specific define for whether we  
  12.         // have mmap (or whether we could possibly have the kernel module  
  13.         // availabla).  
  14. #if !defined(HAVE_WIN32_IPC)  
  15.         // mmap the binder, providing a chunk of virtual address space to receive transactions.  
  16.         mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);  
  17.         if (mVMStart == MAP_FAILED) {  
  18.             // *sigh*  
  19.             LOGE("Using /dev/binder failed: unable to mmap transaction memory.\n");  
  20.             close(mDriverFD);  
  21.             mDriverFD = -1;  
  22.         }  
  23. #else  
  24.         mDriverFD = -1;  
  25. #endif  
  26.     }  
  27.     if (mDriverFD < 0) {  
  28.         // Need to run without the driver, starting our own thread pool.  
  29.     }  
  30. }  
        這個函數有兩個關鍵地方,一是通過open_driver函數打開Binder設備文件/dev/binder,並將打開設備文件描述符保存在成員變量mDriverFD中;二是通過mmap來把設備文件/dev/binder映射到內存中。

        先看open_driver函數的實現,這個函數同樣位於frameworks/base/libs/binder/ProcessState.cpp文件中:

  1. static int open_driver()  
  2. {  
  3.     if (gSingleProcess) {  
  4.         return -1;  
  5.     }  
  6.   
  7.     int fd = open("/dev/binder", O_RDWR);  
  8.     if (fd >= 0) {  
  9.         fcntl(fd, F_SETFD, FD_CLOEXEC);  
  10.         int vers;  
  11. #if defined(HAVE_ANDROID_OS)  
  12.         status_t result = ioctl(fd, BINDER_VERSION, &vers);  
  13. #else  
  14.         status_t result = -1;  
  15.         errno = EPERM;  
  16. #endif  
  17.         if (result == -1) {  
  18.             LOGE("Binder ioctl to obtain version failed: %s", strerror(errno));  
  19.             close(fd);  
  20.             fd = -1;  
  21.         }  
  22.         if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {  
  23.             LOGE("Binder driver protocol does not match user space protocol!");  
  24.             close(fd);  
  25.             fd = -1;  
  26.         }  
  27. #if defined(HAVE_ANDROID_OS)  
  28.         size_t maxThreads = 15;  
  29.         result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);  
  30.         if (result == -1) {  
  31.             LOGE("Binder ioctl to set max threads failed: %s", strerror(errno));  
  32.         }  
  33. #endif  
  34.           
  35.     } else {  
  36.         LOGW("Opening '/dev/binder' failed: %s\n", strerror(errno));  
  37.     }  
  38.     return fd;  
  39. }  
        這個函數的作用主要是通過open文件操作函數來打開/dev/binder設備文件,然後再調用ioctl文件控制函數來分別執行BINDER_VERSION和BINDER_SET_MAX_THREADS兩個命令來和Binder驅動程序進行交互,前者用於獲得當前Binder驅動程序的版本號,後者用於通知Binder驅動程序,MediaPlayerService最多可同時啓動15個線程來處理Client端的請求。

        open在Binder驅動程序中的具體實現,請參考前面一篇文章淺談Service Manager成爲Android進程間通信(IPC)機制Binder守護進程之路,這裏不再重複描述。打開/dev/binder設備文件後,Binder驅動程序就爲MediaPlayerService進程創建了一個struct binder_proc結構體實例來維護MediaPlayerService進程上下文相關信息。

        我們來看一下ioctl文件操作函數執行BINDER_VERSION命令的過程:

  1. status_t result = ioctl(fd, BINDER_VERSION, &vers);  
        這個函數調用最終進入到Binder驅動程序的binder_ioctl函數中,我們只關注BINDER_VERSION相關的部分邏輯:
  1. static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)  
  2. {  
  3.     int ret;  
  4.     struct binder_proc *proc = filp->private_data;  
  5.     struct binder_thread *thread;  
  6.     unsigned int size = _IOC_SIZE(cmd);  
  7.     void __user *ubuf = (void __user *)arg;  
  8.   
  9.     /*printk(KERN_INFO "binder_ioctl: %d:%d %x %lx\n", proc->pid, current->pid, cmd, arg);*/  
  10.   
  11.     ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);  
  12.     if (ret)  
  13.         return ret;  
  14.   
  15.     mutex_lock(&binder_lock);  
  16.     thread = binder_get_thread(proc);  
  17.     if (thread == NULL) {  
  18.         ret = -ENOMEM;  
  19.         goto err;  
  20.     }  
  21.   
  22.     switch (cmd) {  
  23.     ......  
  24.     case BINDER_VERSION:  
  25.         if (size != sizeof(struct binder_version)) {  
  26.             ret = -EINVAL;  
  27.             goto err;  
  28.         }  
  29.         if (put_user(BINDER_CURRENT_PROTOCOL_VERSION, &((struct binder_version *)ubuf)->protocol_version)) {  
  30.             ret = -EINVAL;  
  31.             goto err;  
  32.         }  
  33.         break;  
  34.     ......  
  35.     }  
  36.     ret = 0;  
  37. err:  
  38.         ......  
  39.     return ret;  
  40. }  

        很簡單,只是將BINDER_CURRENT_PROTOCOL_VERSION寫入到傳入的參數arg指向的用戶緩衝區中去就返回了。BINDER_CURRENT_PROTOCOL_VERSION是一個宏,定義在kernel/common/drivers/staging/android/binder.h文件中:

  1. /* This is the current protocol version. */  
  2. #define BINDER_CURRENT_PROTOCOL_VERSION 7  
       這裏爲什麼要把ubuf轉換成struct binder_version之後,再通過其protocol_version成員變量再來寫入呢,轉了一圈,最終內容還是寫入到ubuf中。我們看一下struct binder_version的定義就會明白,同樣是在kernel/common/drivers/staging/android/binder.h文件中:
  1. /* Use with BINDER_VERSION, driver fills in fields. */  
  2. struct binder_version {  
  3.     /* driver protocol version -- increment with incompatible change */  
  4.     signed long protocol_version;  
  5. };  
        從註釋中可以看出來,這裏是考慮到兼容性,因爲以後很有可能不是用signed long來表示版本號。

        這裏有一個重要的地方要注意的是,由於這裏是打開設備文件/dev/binder之後,第一次進入到binder_ioctl函數,因此,這裏調用binder_get_thread的時候,就會爲當前線程創建一個struct binder_thread結構體變量來維護線程上下文信息,具體可以參考淺談Service Manager成爲Android進程間通信(IPC)機制Binder守護進程之路一文。

        接着我們再來看一下ioctl文件操作函數執行BINDER_SET_MAX_THREADS命令的過程:

  1. result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);  

        這個函數調用最終進入到Binder驅動程序的binder_ioctl函數中,我們只關注BINDER_SET_MAX_THREADS相關的部分邏輯:

  1. static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)  
  2. {  
  3.     int ret;  
  4.     struct binder_proc *proc = filp->private_data;  
  5.     struct binder_thread *thread;  
  6.     unsigned int size = _IOC_SIZE(cmd);  
  7.     void __user *ubuf = (void __user *)arg;  
  8.   
  9.     /*printk(KERN_INFO "binder_ioctl: %d:%d %x %lx\n", proc->pid, current->pid, cmd, arg);*/  
  10.   
  11.     ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);  
  12.     if (ret)  
  13.         return ret;  
  14.   
  15.     mutex_lock(&binder_lock);  
  16.     thread = binder_get_thread(proc);  
  17.     if (thread == NULL) {  
  18.         ret = -ENOMEM;  
  19.         goto err;  
  20.     }  
  21.   
  22.     switch (cmd) {  
  23.     ......  
  24.     case BINDER_SET_MAX_THREADS:  
  25.         if (copy_from_user(&proc->max_threads, ubuf, sizeof(proc->max_threads))) {  
  26.             ret = -EINVAL;  
  27.             goto err;  
  28.         }  
  29.         break;  
  30.     ......  
  31.     }  
  32.     ret = 0;  
  33. err:  
  34.     ......  
  35.     return ret;  
  36. }  
        這裏實現也是非常簡單,只是簡單地把用戶傳進來的參數保存在proc->max_threads中就完畢了。注意,這裏再調用binder_get_thread函數的時候,就可以在proc->threads中找到當前線程對應的struct binder_thread結構了,因爲前面已經創建好並保存在proc->threads紅黑樹中。

        回到ProcessState的構造函數中,這裏還通過mmap函數來把設備文件/dev/binder映射到內存中,這個函數在淺談Service Manager成爲Android進程間通信(IPC)機制Binder守護進程之路一文也已經有詳細介紹,這裏不再重複描述。宏BINDER_VM_SIZE就定義在ProcessState.cpp文件中:

  1. #define BINDER_VM_SIZE ((1*1024*1024) - (4096 *2))  
        mmap函數調用完成之後,Binder驅動程序就爲當前進程預留了BINDER_VM_SIZE大小的內存空間了。

        這樣,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文件中:

  1. void MediaPlayerService::instantiate() {  
  2.     defaultServiceManager()->addService(  
  3.             String16("media.player"), new MediaPlayerService());  
  4. }  
        我們重點看一下IServiceManger::addService的過程,這有助於我們加深對Binder機制的理解。

        在上一篇文章淺談Android系統進程間通信(IPC)機制Binder中的Server和Client獲得Service Manager接口之路中說到,defaultServiceManager返回的實際是一個BpServiceManger類實例,因此,我們看一下BpServiceManger::addService的實現,這個函數實現在frameworks/base/libs/binder/IServiceManager.cpp文件中:

  1. class BpServiceManager : public BpInterface<IServiceManager>  
  2. {  
  3. public:  
  4.     BpServiceManager(const sp<IBinder>& impl)  
  5.         : BpInterface<IServiceManager>(impl)  
  6.     {  
  7.     }  
  8.   
  9.     ......  
  10.   
  11.     virtual status_t addService(const String16& name, const sp<IBinder>& service)  
  12.     {  
  13.         Parcel data, reply;  
  14.         data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());  
  15.         data.writeString16(name);  
  16.         data.writeStrongBinder(service);  
  17.         status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);  
  18.         return err == NO_ERROR ? reply.readExceptionCode()   
  19.     }  
  20.   
  21.     ......  
  22.   
  23. };  
         這裏的Parcel類是用來於序列化進程間通信數據用的。

         先來看這一句的調用:

  1. data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());  
         IServiceManager::getInterfaceDescriptor()返回來的是一個字符串,即"android.os.IServiceManager",具體可以參考IServiceManger的實現。我們看一下Parcel::writeInterfaceToken的實現,位於frameworks/base/libs/binder/Parcel.cpp文件中:
  1. // Write RPC headers.  (previously just the interface token)  
  2. status_t Parcel::writeInterfaceToken(const String16& interface)  
  3. {  
  4.     writeInt32(IPCThreadState::self()->getStrictModePolicy() |  
  5.                STRICT_MODE_PENALTY_GATHER);  
  6.     // currently the interface identification token is just its name as a string  
  7.     return writeString16(interface);  
  8. }  
         它的作用是寫入一個整數和一個字符串到Parcel中去。

         再來看下面的調用:

  1. data.writeString16(name);  
        這裏又是寫入一個字符串到Parcel中去,這裏的name即是上面傳進來的“media.player”字符串。

        往下看:

  1. data.writeStrongBinder(service);  
        這裏定入一個Binder對象到Parcel去。我們重點看一下這個函數的實現,因爲它涉及到進程間傳輸Binder實體的問題,比較複雜,需要重點關注,同時,也是理解Binder機制的一個重點所在。注意,這裏的service參數是一個MediaPlayerService對象。
  1. status_t Parcel::writeStrongBinder(const sp<IBinder>& val)  
  2. {  
  3.     return flatten_binder(ProcessState::self(), val, this);  
  4. }  
        看到flatten_binder函數,是不是似曾相識的感覺?我們在前面一篇文章淺談Service Manager成爲Android進程間通信(IPC)機制Binder守護進程之路中,曾經提到在Binder驅動程序中,使用struct flat_binder_object來表示傳輸中的一個binder對象,它的定義如下所示:
  1. /* 
  2.  * This is the flattened representation of a Binder object for transfer 
  3.  * between processes.  The 'offsets' supplied as part of a binder transaction 
  4.  * contains offsets into the data where these structures occur.  The Binder 
  5.  * driver takes care of re-writing the structure type and data as it moves 
  6.  * between processes. 
  7.  */  
  8. struct flat_binder_object {  
  9.     /* 8 bytes for large_flat_header. */  
  10.     unsigned long       type;  
  11.     unsigned long       flags;  
  12.   
  13.     /* 8 bytes of data. */  
  14.     union {  
  15.         void        *binder;    /* local object */  
  16.         signed long handle;     /* remote object */  
  17.     };  
  18.   
  19.     /* extra data associated with local object */  
  20.     void            *cookie;  
  21. };  
        各個成員變量的含義請參考資料Android Binder設計與實現

        我們進入到flatten_binder函數看看:

  1. status_t flatten_binder(const sp<ProcessState>& proc,  
  2.     const sp<IBinder>& binder, Parcel* out)  
  3. {  
  4.     flat_binder_object obj;  
  5.       
  6.     obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;  
  7.     if (binder != NULL) {  
  8.         IBinder *local = binder->localBinder();  
  9.         if (!local) {  
  10.             BpBinder *proxy = binder->remoteBinder();  
  11.             if (proxy == NULL) {  
  12.                 LOGE("null proxy");  
  13.             }  
  14.             const int32_t handle = proxy ? proxy->handle() : 0;  
  15.             obj.type = BINDER_TYPE_HANDLE;  
  16.             obj.handle = handle;  
  17.             obj.cookie = NULL;  
  18.         } else {  
  19.             obj.type = BINDER_TYPE_BINDER;  
  20.             obj.binder = local->getWeakRefs();  
  21.             obj.cookie = local;  
  22.         }  
  23.     } else {  
  24.         obj.type = BINDER_TYPE_BINDER;  
  25.         obj.binder = NULL;  
  26.         obj.cookie = NULL;  
  27.     }  
  28.       
  29.     return finish_flatten_binder(binder, obj, out);  
  30. }  
        首先是初始化flat_binder_object的flags域:
  1. obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;  
        0x7f表示處理本Binder實體請求數據包的線程的最低優先級,FLAT_BINDER_FLAG_ACCEPTS_FDS表示這個Binder實體可以接受文件描述符,Binder實體在收到文件描述符時,就會在本進程中打開這個文件。

       傳進來的binder即爲MediaPlayerService::instantiate函數中new出來的MediaPlayerService實例,因此,不爲空。又由於MediaPlayerService繼承自BBinder類,它是一個本地Binder實體,因此binder->localBinder返回一個BBinder指針,而且肯定不爲空,於是執行下面語句:

  1. obj.type = BINDER_TYPE_BINDER;  
  2. obj.binder = local->getWeakRefs();  
  3. obj.cookie = local;  
        設置了flat_binder_obj的其他成員變量,注意,指向這個Binder實體地址的指針local保存在flat_binder_obj的成員變量cookie中。

        函數調用finish_flatten_binder來將這個flat_binder_obj寫入到Parcel中去:

  1. inline static status_t finish_flatten_binder(  
  2.     const sp<IBinder>& binder, const flat_binder_object& flat, Parcel* out)  
  3. {  
  4.     return out->writeObject(flat, false);  
  5. }  
       Parcel::writeObject的實現如下:
  1. status_t Parcel::writeObject(const flat_binder_object& val, bool nullMetaData)  
  2. {  
  3.     const bool enoughData = (mDataPos+sizeof(val)) <= mDataCapacity;  
  4.     const bool enoughObjects = mObjectsSize < mObjectsCapacity;  
  5.     if (enoughData && enoughObjects) {  
  6. restart_write:  
  7.         *reinterpret_cast<flat_binder_object*>(mData+mDataPos) = val;  
  8.           
  9.         // Need to write meta-data?  
  10.         if (nullMetaData || val.binder != NULL) {  
  11.             mObjects[mObjectsSize] = mDataPos;  
  12.             acquire_object(ProcessState::self(), val, this);  
  13.             mObjectsSize++;  
  14.         }  
  15.           
  16.         // remember if it's a file descriptor  
  17.         if (val.type == BINDER_TYPE_FD) {  
  18.             mHasFds = mFdsKnown = true;  
  19.         }  
  20.   
  21.         return finishWrite(sizeof(flat_binder_object));  
  22.     }  
  23.   
  24.     if (!enoughData) {  
  25.         const status_t err = growData(sizeof(val));  
  26.         if (err != NO_ERROR) return err;  
  27.     }  
  28.     if (!enoughObjects) {  
  29.         size_t newSize = ((mObjectsSize+2)*3)/2;  
  30.         size_t* objects = (size_t*)realloc(mObjects, newSize*sizeof(size_t));  
  31.         if (objects == NULL) return NO_MEMORY;  
  32.         mObjects = objects;  
  33.         mObjectsCapacity = newSize;  
  34.     }  
  35.       
  36.     goto restart_write;  
  37. }  
        這裏除了把flat_binder_obj寫到Parcel裏面之內,還要記錄這個flat_binder_obj在Parcel裏面的偏移位置:
  1. mObjects[mObjectsSize] = mDataPos;  
       這裏因爲,如果進程間傳輸的數據間帶有Binder對象的時候,Binder驅動程序需要作進一步的處理,以維護各個Binder實體的一致性,下面我們將會看到Binder驅動程序是怎麼處理這些Binder對象的。

       再回到BpServiceManager::addService函數中,調用下面語句:

  1. status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);  
       回到淺談Android系統進程間通信(IPC)機制Binder中的Server和Client獲得Service Manager接口之路一文中的類圖中去看一下,這裏的remote成員函數來自於BpRefBase類,它返回一個BpBinder指針。因此,我們繼續進入到BpBinder::transact函數中去看看:
  1. status_t BpBinder::transact(  
  2.     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)  
  3. {  
  4.     // Once a binder has died, it will never come back to life.  
  5.     if (mAlive) {  
  6.         status_t status = IPCThreadState::self()->transact(  
  7.             mHandle, code, data, reply, flags);  
  8.         if (status == DEAD_OBJECT) mAlive = 0;  
  9.         return status;  
  10.     }  
  11.   
  12.     return DEAD_OBJECT;  
  13. }  
       這裏又調用了IPCThreadState::transact進執行實際的操作。注意,這裏的mHandle爲0,code爲ADD_SERVICE_TRANSACTION。ADD_SERVICE_TRANSACTION是上面以參數形式傳進來的,那mHandle爲什麼是0呢?因爲這裏表示的是Service Manager遠程接口,它的句柄值一定是0,具體請參考淺談Android系統進程間通信(IPC)機制Binder中的Server和Client獲得Service Manager接口之路一文。
       再進入到IPCThreadState::transact函數,看看做了些什麼事情:
  1. status_t IPCThreadState::transact(int32_t handle,  
  2.                                   uint32_t code, const Parcel& data,  
  3.                                   Parcel* reply, uint32_t flags)  
  4. {  
  5.     status_t err = data.errorCheck();  
  6.   
  7.     flags |= TF_ACCEPT_FDS;  
  8.   
  9.     IF_LOG_TRANSACTIONS() {  
  10.         TextOutput::Bundle _b(alog);  
  11.         alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "  
  12.             << handle << " / code " << TypeCode(code) << ": "  
  13.             << indent << data << dedent << endl;  
  14.     }  
  15.       
  16.     if (err == NO_ERROR) {  
  17.         LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),  
  18.             (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");  
  19.         err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);  
  20.     }  
  21.       
  22.     if (err != NO_ERROR) {  
  23.         if (reply) reply->setError(err);  
  24.         return (mLastError = err);  
  25.     }  
  26.       
  27.     if ((flags & TF_ONE_WAY) == 0) {  
  28.         #if 0  
  29.         if (code == 4) { // relayout  
  30.             LOGI(">>>>>> CALLING transaction 4");  
  31.         } else {  
  32.             LOGI(">>>>>> CALLING transaction %d", code);  
  33.         }  
  34.         #endif  
  35.         if (reply) {  
  36.             err = waitForResponse(reply);  
  37.         } else {  
  38.             Parcel fakeReply;  
  39.             err = waitForResponse(&fakeReply);  
  40.         }  
  41.         #if 0  
  42.         if (code == 4) { // relayout  
  43.             LOGI("<<<<<< RETURNING transaction 4");  
  44.         } else {  
  45.             LOGI("<<<<<< RETURNING transaction %d", code);  
  46.         }  
  47.         #endif  
  48.           
  49.         IF_LOG_TRANSACTIONS() {  
  50.             TextOutput::Bundle _b(alog);  
  51.             alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "  
  52.                 << handle << ": ";  
  53.             if (reply) alog << indent << *reply << dedent << endl;  
  54.             else alog << "(none requested)" << endl;  
  55.         }  
  56.     } else {  
  57.         err = waitForResponse(NULL, NULL);  
  58.     }  
  59.       
  60.     return err;  
  61. }  
        IPCThreadState::transact函數的參數flags是一個默認值爲0的參數,上面沒有傳相應的實參進來,因此,這裏就爲0。

        函數首先調用writeTransactionData函數準備好一個struct binder_transaction_data結構體變量,這個是等一下要傳輸給Binder驅動程序的。struct binder_transaction_data的定義我們在淺談Service Manager成爲Android進程間通信(IPC)機制Binder守護進程之路一文中有詳細描述,讀者不妨回過去讀一下。這裏爲了方便描述,將struct binder_transaction_data的定義再次列出來:

  1. struct binder_transaction_data {  
  2.     /* The first two are only used for bcTRANSACTION and brTRANSACTION, 
  3.      * identifying the target and contents of the transaction. 
  4.      */  
  5.     union {  
  6.         size_t  handle; /* target descriptor of command transaction */  
  7.         void    *ptr;   /* target descriptor of return transaction */  
  8.     } target;  
  9.     void        *cookie;    /* target object cookie */  
  10.     unsigned int    code;       /* transaction command */  
  11.   
  12.     /* General information about the transaction. */  
  13.     unsigned int    flags;  
  14.     pid_t       sender_pid;  
  15.     uid_t       sender_euid;  
  16.     size_t      data_size;  /* number of bytes of data */  
  17.     size_t      offsets_size;   /* number of bytes of offsets */  
  18.   
  19.     /* If this transaction is inline, the data immediately 
  20.      * follows here; otherwise, it ends with a pointer to 
  21.      * the data buffer. 
  22.      */  
  23.     union {  
  24.         struct {  
  25.             /* transaction data */  
  26.             const void  *buffer;  
  27.             /* offsets from buffer to flat_binder_object structs */  
  28.             const void  *offsets;  
  29.         } ptr;  
  30.         uint8_t buf[8];  
  31.     } data;  
  32. };  
         writeTransactionData函數的實現如下:
  1. status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,  
  2.     int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)  
  3. {  
  4.     binder_transaction_data tr;  
  5.   
  6.     tr.target.handle = handle;  
  7.     tr.code = code;  
  8.     tr.flags = binderFlags;  
  9.       
  10.     const status_t err = data.errorCheck();  
  11.     if (err == NO_ERROR) {  
  12.         tr.data_size = data.ipcDataSize();  
  13.         tr.data.ptr.buffer = data.ipcData();  
  14.         tr.offsets_size = data.ipcObjectsCount()*sizeof(size_t);  
  15.         tr.data.ptr.offsets = data.ipcObjects();  
  16.     } else if (statusBuffer) {  
  17.         tr.flags |= TF_STATUS_CODE;  
  18.         *statusBuffer = err;  
  19.         tr.data_size = sizeof(status_t);  
  20.         tr.data.ptr.buffer = statusBuffer;  
  21.         tr.offsets_size = 0;  
  22.         tr.data.ptr.offsets = NULL;  
  23.     } else {  
  24.         return (mLastError = err);  
  25.     }  
  26.       
  27.     mOut.writeInt32(cmd);  
  28.     mOut.write(&tr, sizeof(tr));  
  29.       
  30.     return NO_ERROR;  
  31. }  

        注意,這裏的cmd爲BC_TRANSACTION。 這個函數很簡單,在這個場景下,就是執行下面語句來初始化本地變量tr:

  1. tr.data_size = data.ipcDataSize();  
  2. tr.data.ptr.buffer = data.ipcData();  
  3. tr.offsets_size = data.ipcObjectsCount()*sizeof(size_t);  
  4. tr.data.ptr.offsets = data.ipcObjects();  
       回憶一下上面的內容,寫入到tr.data.ptr.buffer的內容相當於下面的內容:
  1. writeInt32(IPCThreadState::self()->getStrictModePolicy() |  
  2.                STRICT_MODE_PENALTY_GATHER);  
  3. writeString16("android.os.IServiceManager");  
  4. writeString16("media.player");  
  5. writeStrongBinder(new MediaPlayerService());  
       其中包含了一個Binder實體MediaPlayerService,因此需要設置tr.offsets_size就爲1,tr.data.ptr.offsets就指向了這個MediaPlayerService的地址在tr.data.ptr.buffer中的偏移量。最後,將tr的內容保存在IPCThreadState的成員變量mOut中。
       回到IPCThreadState::transact函數中,接下去看,(flags & TF_ONE_WAY) == 0爲true,並且reply不爲空,所以最終進入到waitForResponse(reply)這條路徑來。我們看一下waitForResponse函數的實現:
  1. status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)  
  2. {  
  3.     int32_t cmd;  
  4.     int32_t err;  
  5.   
  6.     while (1) {  
  7.         if ((err=talkWithDriver()) < NO_ERROR) break;  
  8.         err = mIn.errorCheck();  
  9.         if (err < NO_ERROR) break;  
  10.         if (mIn.dataAvail() == 0) continue;  
  11.           
  12.         cmd = mIn.readInt32();  
  13.           
  14.         IF_LOG_COMMANDS() {  
  15.             alog << "Processing waitForResponse Command: "  
  16.                 << getReturnString(cmd) << endl;  
  17.         }  
  18.   
  19.         switch (cmd) {  
  20.         case BR_TRANSACTION_COMPLETE:  
  21.             if (!reply && !acquireResult) goto finish;  
  22.             break;  
  23.           
  24.         case BR_DEAD_REPLY:  
  25.             err = DEAD_OBJECT;  
  26.             goto finish;  
  27.   
  28.         case BR_FAILED_REPLY:  
  29.             err = FAILED_TRANSACTION;  
  30.             goto finish;  
  31.           
  32.         case BR_ACQUIRE_RESULT:  
  33.             {  
  34.                 LOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");  
  35.                 const int32_t result = mIn.readInt32();  
  36.                 if (!acquireResult) continue;  
  37.                 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;  
  38.             }  
  39.             goto finish;  
  40.           
  41.         case BR_REPLY:  
  42.             {  
  43.                 binder_transaction_data tr;  
  44.                 err = mIn.read(&tr, sizeof(tr));  
  45.                 LOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");  
  46.                 if (err != NO_ERROR) goto finish;  
  47.   
  48.                 if (reply) {  
  49.                     if ((tr.flags & TF_STATUS_CODE) == 0) {  
  50.                         reply->ipcSetDataReference(  
  51.                             reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),  
  52.                             tr.data_size,  
  53.                             reinterpret_cast<const size_t*>(tr.data.ptr.offsets),  
  54.                             tr.offsets_size/sizeof(size_t),  
  55.                             freeBuffer, this);  
  56.                     } else {  
  57.                         err = *static_cast<const status_t*>(tr.data.ptr.buffer);  
  58.                         freeBuffer(NULL,  
  59.                             reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),  
  60.                             tr.data_size,  
  61.                             reinterpret_cast<const size_t*>(tr.data.ptr.offsets),  
  62.                             tr.offsets_size/sizeof(size_t), this);  
  63.                     }  
  64.                 } else {  
  65.                     freeBuffer(NULL,  
  66.                         reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),  
  67.                         tr.data_size,  
  68.                         reinterpret_cast<const size_t*>(tr.data.ptr.offsets),  
  69.                         tr.offsets_size/sizeof(size_t), this);  
  70.                     continue;  
  71.                 }  
  72.             }  
  73.             goto finish;  
  74.   
  75.         default:  
  76.             err = executeCommand(cmd);  
  77.             if (err != NO_ERROR) goto finish;  
  78.             break;  
  79.         }  
  80.     }  
  81.   
  82. finish:  
  83.     if (err != NO_ERROR) {  
  84.         if (acquireResult) *acquireResult = err;  
  85.         if (reply) reply->setError(err);  
  86.         mLastError = err;  
  87.     }  
  88.       
  89.     return err;  
  90. }  
        這個函數雖然很長,但是主要調用了talkWithDriver函數來與Binder驅動程序進行交互:
  1. status_t IPCThreadState::talkWithDriver(bool doReceive)  
  2. {  
  3.     LOG_ASSERT(mProcess->mDriverFD >= 0, "Binder driver is not opened");  
  4.       
  5.     binder_write_read bwr;  
  6.       
  7.     // Is the read buffer empty?  
  8.     const bool needRead = mIn.dataPosition() >= mIn.dataSize();  
  9.       
  10.     // We don't want to write anything if we are still reading  
  11.     // from data left in the input buffer and the caller  
  12.     // has requested to read the next data.  
  13.     const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;  
  14.       
  15.     bwr.write_size = outAvail;  
  16.     bwr.write_buffer = (long unsigned int)mOut.data();  
  17.   
  18.     // This is what we'll read.  
  19.     if (doReceive && needRead) {  
  20.         bwr.read_size = mIn.dataCapacity();  
  21.         bwr.read_buffer = (long unsigned int)mIn.data();  
  22.     } else {  
  23.         bwr.read_size = 0;  
  24.     }  
  25.       
  26.     IF_LOG_COMMANDS() {  
  27.         TextOutput::Bundle _b(alog);  
  28.         if (outAvail != 0) {  
  29.             alog << "Sending commands to driver: " << indent;  
  30.             const void* cmds = (const void*)bwr.write_buffer;  
  31.             const void* end = ((const uint8_t*)cmds)+bwr.write_size;  
  32.             alog << HexDump(cmds, bwr.write_size) << endl;  
  33.             while (cmds < end) cmds = printCommand(alog, cmds);  
  34.             alog << dedent;  
  35.         }  
  36.         alog << "Size of receive buffer: " << bwr.read_size  
  37.             << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;  
  38.     }  
  39.       
  40.     // Return immediately if there is nothing to do.  
  41.     if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;  
  42.       
  43.     bwr.write_consumed = 0;  
  44.     bwr.read_consumed = 0;  
  45.     status_t err;  
  46.     do {  
  47.         IF_LOG_COMMANDS() {  
  48.             alog << "About to read/write, write size = " << mOut.dataSize() << endl;  
  49.         }  
  50. #if defined(HAVE_ANDROID_OS)  
  51.         if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)  
  52.             err = NO_ERROR;  
  53.         else  
  54.             err = -errno;  
  55. #else  
  56.         err = INVALID_OPERATION;  
  57. #endif  
  58.         IF_LOG_COMMANDS() {  
  59.             alog << "Finished read/write, write size = " << mOut.dataSize() << endl;  
  60.         }  
  61.     } while (err == -EINTR);  
  62.       
  63.     IF_LOG_COMMANDS() {  
  64.         alog << "Our err: " << (void*)err << ", write consumed: "  
  65.             << bwr.write_consumed << " (of " << mOut.dataSize()  
  66.             << "), read consumed: " << bwr.read_consumed << endl;  
  67.     }  
  68.   
  69.     if (err >= NO_ERROR) {  
  70.         if (bwr.write_consumed > 0) {  
  71.             if (bwr.write_consumed < (ssize_t)mOut.dataSize())  
  72.                 mOut.remove(0, bwr.write_consumed);  
  73.             else  
  74.                 mOut.setDataSize(0);  
  75.         }  
  76.         if (bwr.read_consumed > 0) {  
  77.             mIn.setDataSize(bwr.read_consumed);  
  78.             mIn.setDataPosition(0);  
  79.         }  
  80.         IF_LOG_COMMANDS() {  
  81.             TextOutput::Bundle _b(alog);  
  82.             alog << "Remaining data size: " << mOut.dataSize() << endl;  
  83.             alog << "Received commands from driver: " << indent;  
  84.             const void* cmds = mIn.data();  
  85.             const void* end = mIn.data() + mIn.dataSize();  
  86.             alog << HexDump(cmds, mIn.dataSize()) << endl;  
  87.             while (cmds < end) cmds = printReturnCommand(alog, cmds);  
  88.             alog << dedent;  
  89.         }  
  90.         return NO_ERROR;  
  91.     }  
  92.       
  93.     return err;  
  94. }  
        這裏doReceive和needRead均爲1,有興趣的讀者可以自已分析一下。因此,這裏告訴Binder驅動程序,先執行write操作,再執行read操作,下面我們將會看到。

        最後,通過ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr)進行到Binder驅動程序的binder_ioctl函數,我們只關注cmd爲BINDER_WRITE_READ的邏輯:

  1. static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)  
  2. {  
  3.     int ret;  
  4.     struct binder_proc *proc = filp->private_data;  
  5.     struct binder_thread *thread;  
  6.     unsigned int size = _IOC_SIZE(cmd);  
  7.     void __user *ubuf = (void __user *)arg;  
  8.   
  9.     /*printk(KERN_INFO "binder_ioctl: %d:%d %x %lx\n", proc->pid, current->pid, cmd, arg);*/  
  10.   
  11.     ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);  
  12.     if (ret)  
  13.         return ret;  
  14.   
  15.     mutex_lock(&binder_lock);  
  16.     thread = binder_get_thread(proc);  
  17.     if (thread == NULL) {  
  18.         ret = -ENOMEM;  
  19.         goto err;  
  20.     }  
  21.   
  22.     switch (cmd) {  
  23.     case BINDER_WRITE_READ: {  
  24.         struct binder_write_read bwr;  
  25.         if (size != sizeof(struct binder_write_read)) {  
  26.             ret = -EINVAL;  
  27.             goto err;  
  28.         }  
  29.         if (copy_from_user(&bwr, ubuf, sizeof(bwr))) {  
  30.             ret = -EFAULT;  
  31.             goto err;  
  32.         }  
  33.         if (binder_debug_mask & BINDER_DEBUG_READ_WRITE)  
  34.             printk(KERN_INFO "binder: %d:%d write %ld at %08lx, read %ld at %08lx\n",  
  35.             proc->pid, thread->pid, bwr.write_size, bwr.write_buffer, bwr.read_size, bwr.read_buffer);  
  36.         if (bwr.write_size > 0) {  
  37.             ret = binder_thread_write(proc, thread, (void __user *)bwr.write_buffer, bwr.write_size, &bwr.write_consumed);  
  38.             if (ret < 0) {  
  39.                 bwr.read_consumed = 0;  
  40.                 if (copy_to_user(ubuf, &bwr, sizeof(bwr)))  
  41.                     ret = -EFAULT;  
  42.                 goto err;  
  43.             }  
  44.         }  
  45.         if (bwr.read_size > 0) {  
  46.             ret = binder_thread_read(proc, thread, (void __user *)bwr.read_buffer, bwr.read_size, &bwr.read_consumed, filp->f_flags & O_NONBLOCK);  
  47.             if (!list_empty(&proc->todo))  
  48.                 wake_up_interruptible(&proc->wait);  
  49.             if (ret < 0) {  
  50.                 if (copy_to_user(ubuf, &bwr, sizeof(bwr)))  
  51.                     ret = -EFAULT;  
  52.                 goto err;  
  53.             }  
  54.         }  
  55.         if (binder_debug_mask & BINDER_DEBUG_READ_WRITE)  
  56.             printk(KERN_INFO "binder: %d:%d wrote %ld of %ld, read return %ld of %ld\n",  
  57.             proc->pid, thread->pid, bwr.write_consumed, bwr.write_size, bwr.read_consumed, bwr.read_size);  
  58.         if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {  
  59.             ret = -EFAULT;  
  60.             goto err;  
  61.         }  
  62.         break;  
  63.     }  
  64.     ......  
  65.     }  
  66.     ret = 0;  
  67. err:  
  68.     ......  
  69.     return ret;  
  70. }  
         函數首先是將用戶傳進來的參數拷貝到本地變量struct binder_write_read bwr中去。這裏bwr.write_size > 0爲true,因此,進入到binder_thread_write函數中,我們只關注BC_TRANSACTION部分的邏輯:
  1. binder_thread_write(struct binder_proc *proc, struct binder_thread *thread,  
  2.                     void __user *buffer, int size, signed long *consumed)  
  3. {  
  4.     uint32_t cmd;  
  5.     void __user *ptr = buffer + *consumed;  
  6.     void __user *end = buffer + size;  
  7.   
  8.     while (ptr < end && thread->return_error == BR_OK) {  
  9.         if (get_user(cmd, (uint32_t __user *)ptr))  
  10.             return -EFAULT;  
  11.         ptr += sizeof(uint32_t);  
  12.         if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.bc)) {  
  13.             binder_stats.bc[_IOC_NR(cmd)]++;  
  14.             proc->stats.bc[_IOC_NR(cmd)]++;  
  15.             thread->stats.bc[_IOC_NR(cmd)]++;  
  16.         }  
  17.         switch (cmd) {  
  18.             .....  
  19.         case BC_TRANSACTION:  
  20.         case BC_REPLY: {  
  21.             struct binder_transaction_data tr;  
  22.   
  23.             if (copy_from_user(&tr, ptr, sizeof(tr)))  
  24.                 return -EFAULT;  
  25.             ptr += sizeof(tr);  
  26.             binder_transaction(proc, thread, &tr, cmd == BC_REPLY);  
  27.             break;  
  28.         }  
  29.         ......  
  30.         }  
  31.         *consumed = ptr - buffer;  
  32.     }  
  33.     return 0;  
  34. }  
         首先將用戶傳進來的transact參數拷貝在本地變量struct binder_transaction_data tr中去,接着調用binder_transaction函數進一步處理,這裏我們忽略掉無關代碼:
  1. static void  
  2. binder_transaction(struct binder_proc *proc, struct binder_thread *thread,  
  3. struct binder_transaction_data *tr, int reply)  
  4. {  
  5.     struct binder_transaction *t;  
  6.     struct binder_work *tcomplete;  
  7.     size_t *offp, *off_end;  
  8.     struct binder_proc *target_proc;  
  9.     struct binder_thread *target_thread = NULL;  
  10.     struct binder_node *target_node = NULL;  
  11.     struct list_head *target_list;  
  12.     wait_queue_head_t *target_wait;  
  13.     struct binder_transaction *in_reply_to = NULL;  
  14.     struct binder_transaction_log_entry *e;  
  15.     uint32_t return_error;  
  16.   
  17.         ......  
  18.   
  19.     if (reply) {  
  20.          ......  
  21.     } else {  
  22.         if (tr->target.handle) {  
  23.             ......  
  24.         } else {  
  25.             target_node = binder_context_mgr_node;  
  26.             if (target_node == NULL) {  
  27.                 return_error = BR_DEAD_REPLY;  
  28.                 goto err_no_context_mgr_node;  
  29.             }  
  30.         }  
  31.         ......  
  32.         target_proc = target_node->proc;  
  33.         if (target_proc == NULL) {  
  34.             return_error = BR_DEAD_REPLY;  
  35.             goto err_dead_binder;  
  36.         }  
  37.         ......  
  38.     }  
  39.     if (target_thread) {  
  40.         ......  
  41.     } else {  
  42.         target_list = &target_proc->todo;  
  43.         target_wait = &target_proc->wait;  
  44.     }  
  45.       
  46.     ......  
  47.   
  48.     /* TODO: reuse incoming transaction for reply */  
  49.     t = kzalloc(sizeof(*t), GFP_KERNEL);  
  50.     if (t == NULL) {  
  51.         return_error = BR_FAILED_REPLY;  
  52.         goto err_alloc_t_failed;  
  53.     }  
  54.     ......  
  55.   
  56.     tcomplete = kzalloc(sizeof(*tcomplete), GFP_KERNEL);  
  57.     if (tcomplete == NULL) {  
  58.         return_error = BR_FAILED_REPLY;  
  59.         goto err_alloc_tcomplete_failed;  
  60.     }  
  61.       
  62.     ......  
  63.   
  64.     if (!reply && !(tr->flags & TF_ONE_WAY))  
  65.         t->from = thread;  
  66.     else  
  67.         t->from = NULL;  
  68.     t->sender_euid = proc->tsk->cred->euid;  
  69.     t->to_proc = target_proc;  
  70.     t->to_thread = target_thread;  
  71.     t->code = tr->code;  
  72.     t->flags = tr->flags;  
  73.     t->priority = task_nice(current);  
  74.     t->buffer = binder_alloc_buf(target_proc, tr->data_size,  
  75.         tr->offsets_size, !reply && (t->flags & TF_ONE_WAY));  
  76.     if (t->buffer == NULL) {  
  77.         return_error = BR_FAILED_REPLY;  
  78.         goto err_binder_alloc_buf_failed;  
  79.     }  
  80.     t->buffer->allow_user_free = 0;  
  81.     t->buffer->debug_id = t->debug_id;  
  82.     t->buffer->transaction = t;  
  83.     t->buffer->target_node = target_node;  
  84.     if (target_node)  
  85.         binder_inc_node(target_node, 1, 0, NULL);  
  86.   
  87.     offp = (size_t *)(t->buffer->data + ALIGN(tr->data_size, sizeof(void *)));  
  88.   
  89.     if (copy_from_user(t->buffer->data, tr->data.ptr.buffer, tr->data_size)) {  
  90.         ......  
  91.         return_error = BR_FAILED_REPLY;  
  92.         goto err_copy_data_failed;  
  93.     }  
  94.     if (copy_from_user(offp, tr->data.ptr.offsets, tr->offsets_size)) {  
  95.         ......  
  96.         return_error = BR_FAILED_REPLY;  
  97.         goto err_copy_data_failed;  
  98.     }  
  99.     ......  
  100.   
  101.     off_end = (void *)offp + tr->offsets_size;  
  102.     for (; offp < off_end; offp++) {  
  103.         struct flat_binder_object *fp;  
  104.         ......  
  105.         fp = (struct flat_binder_object *)(t->buffer->data + *offp);  
  106.         switch (fp->type) {  
  107.         case BINDER_TYPE_BINDER:  
  108.         case BINDER_TYPE_WEAK_BINDER: {  
  109.             struct binder_ref *ref;  
  110.             struct binder_node *node = binder_get_node(proc, fp->binder);  
  111.             if (node == NULL) {  
  112.                 node = binder_new_node(proc, fp->binder, fp->cookie);  
  113.                 if (node == NULL) {  
  114.                     return_error = BR_FAILED_REPLY;  
  115.                     goto err_binder_new_node_failed;  
  116.                 }  
  117.                 node->min_priority = fp->flags & FLAT_BINDER_FLAG_PRIORITY_MASK;  
  118.                 node->accept_fds = !!(fp->flags & FLAT_BINDER_FLAG_ACCEPTS_FDS);  
  119.             }  
  120.             if (fp->cookie != node->cookie) {  
  121.                 ......  
  122.                 goto err_binder_get_ref_for_node_failed;  
  123.             }  
  124.             ref = binder_get_ref_for_node(target_proc, node);  
  125.             if (ref == NULL) {  
  126.                 return_error = BR_FAILED_REPLY;  
  127.                 goto err_binder_get_ref_for_node_failed;  
  128.             }  
  129.             if (fp->type == BINDER_TYPE_BINDER)  
  130.                 fp->type = BINDER_TYPE_HANDLE;  
  131.             else  
  132.                 fp->type = BINDER_TYPE_WEAK_HANDLE;  
  133.             fp->handle = ref->desc;  
  134.             binder_inc_ref(ref, fp->type == BINDER_TYPE_HANDLE, &thread->todo);  
  135.             ......  
  136.                                 
  137.         } break;  
  138.         ......  
  139.         }  
  140.     }  
  141.   
  142.     if (reply) {  
  143.         ......  
  144.     } else if (!(t->flags & TF_ONE_WAY)) {  
  145.         BUG_ON(t->buffer->async_transaction != 0);  
  146.         t->need_reply = 1;  
  147.         t->from_parent = thread->transaction_stack;  
  148.         thread->transaction_stack = t;  
  149.     } else {  
  150.         ......  
  151.     }  
  152.     t->work.type = BINDER_WORK_TRANSACTION;  
  153.     list_add_tail(&t->work.entry, target_list);  
  154.     tcomplete->type = BINDER_WORK_TRANSACTION_COMPLETE;  
  155.     list_add_tail(&tcomplete->entry, &thread->todo);  
  156.     if (target_wait)  
  157.         wake_up_interruptible(target_wait);  
  158.     return;  
  159.     ......  
  160. }  
       注意,這裏傳進來的參數reply爲0,tr->target.handle也爲0。因此,target_proc、target_thread、target_node、target_list和target_wait的值分別爲:
  1. target_node = binder_context_mgr_node;  
  2. target_proc = target_node->proc;  
  3. target_list = &target_proc->todo;  
  4. target_wait = &target_proc->wait;   
       接着,分配了一個待處理事務t和一個待完成工作項tcomplete,並執行初始化工作:
  1. /* TODO: reuse incoming transaction for reply */  
  2. t = kzalloc(sizeof(*t), GFP_KERNEL);  
  3. if (t == NULL) {  
  4.     return_error = BR_FAILED_REPLY;  
  5.     goto err_alloc_t_failed;  
  6. }  
  7. ......  
  8.   
  9. tcomplete = kzalloc(sizeof(*tcomplete), GFP_KERNEL);  
  10. if (tcomplete == NULL) {  
  11.     return_error = BR_FAILED_REPLY;  
  12.     goto err_alloc_tcomplete_failed;  
  13. }  
  14.   
  15. ......  
  16.   
  17. if (!reply && !(tr->flags & TF_ONE_WAY))  
  18.     t->from = thread;  
  19. else  
  20.     t->from = NULL;  
  21. t->sender_euid = proc->tsk->cred->euid;  
  22. t->to_proc = target_proc;  
  23. t->to_thread = target_thread;  
  24. t->code = tr->code;  
  25. t->flags = tr->flags;  
  26. t->priority = task_nice(current);  
  27. t->buffer = binder_alloc_buf(target_proc, tr->data_size,  
  28.     tr->offsets_size, !reply && (t->flags & TF_ONE_WAY));  
  29. if (t->buffer == NULL) {  
  30.     return_error = BR_FAILED_REPLY;  
  31.     goto err_binder_alloc_buf_failed;  
  32. }  
  33. t->buffer->allow_user_free = 0;  
  34. t->buffer->debug_id = t->debug_id;  
  35. t->buffer->transaction = t;  
  36. t->buffer->target_node = target_node;  
  37. if (target_node)  
  38.     binder_inc_node(target_node, 1, 0, NULL);  
  39.   
  40. offp = (size_t *)(t->buffer->data + ALIGN(tr->data_size, sizeof(void *)));  
  41.   
  42. if (copy_from_user(t->buffer->data, tr->data.ptr.buffer, tr->data_size)) {  
  43.     ......  
  44.     return_error = BR_FAILED_REPLY;  
  45.     goto err_copy_data_failed;  
  46. }  
  47. if (copy_from_user(offp, tr->data.ptr.offsets, tr->offsets_size)) {  
  48.     ......  
  49.     return_error = BR_FAILED_REPLY;  
  50.     goto err_copy_data_failed;  
  51. }  
         注意,這裏的事務t是要交給target_proc處理的,在這個場景之下,就是Service Manager了。因此,下面的語句:
  1. t->buffer = binder_alloc_buf(target_proc, tr->data_size,  
  2.         tr->offsets_size, !reply && (t->flags & TF_ONE_WAY));  
         就是在Service Manager的進程空間中分配一塊內存來保存用戶傳進入的參數了:
  1. if (copy_from_user(t->buffer->data, tr->data.ptr.buffer, tr->data_size)) {  
  2.     ......  
  3.     return_error = BR_FAILED_REPLY;  
  4.     goto err_copy_data_failed;  
  5. }  
  6. if (copy_from_user(offp, tr->data.ptr.offsets, tr->offsets_size)) {  
  7.     ......  
  8.     return_error = BR_FAILED_REPLY;  
  9.     goto err_copy_data_failed;  
  10. }  
         由於現在target_node要被使用了,增加它的引用計數:
  1. if (target_node)  
  2.         binder_inc_node(target_node, 1, 0, NULL);  
        接下去的for循環,就是用來處理傳輸數據中的Binder對象了。在我們的場景中,有一個類型爲BINDER_TYPE_BINDER的Binder實體MediaPlayerService:
  1.    switch (fp->type) {  
  2.    case BINDER_TYPE_BINDER:  
  3.    case BINDER_TYPE_WEAK_BINDER: {  
  4. struct binder_ref *ref;  
  5. struct binder_node *node = binder_get_node(proc, fp->binder);  
  6. if (node == NULL) {  
  7.     node = binder_new_node(proc, fp->binder, fp->cookie);  
  8.     if (node == NULL) {  
  9.         return_error = BR_FAILED_REPLY;  
  10.         goto err_binder_new_node_failed;  
  11.     }  
  12.     node->min_priority = fp->flags & FLAT_BINDER_FLAG_PRIORITY_MASK;  
  13.     node->accept_fds = !!(fp->flags & FLAT_BINDER_FLAG_ACCEPTS_FDS);  
  14. }  
  15. if (fp->cookie != node->cookie) {  
  16.     ......  
  17.     goto err_binder_get_ref_for_node_failed;  
  18. }  
  19. ref = binder_get_ref_for_node(target_proc, node);  
  20. if (ref == NULL) {  
  21.     return_error = BR_FAILED_REPLY;  
  22.     goto err_binder_get_ref_for_node_failed;  
  23. }  
  24. if (fp->type == BINDER_TYPE_BINDER)  
  25.     fp->type = BINDER_TYPE_HANDLE;  
  26. else  
  27.     fp->type = BINDER_TYPE_WEAK_HANDLE;  
  28. fp->handle = ref->desc;  
  29. binder_inc_ref(ref, fp->type == BINDER_TYPE_HANDLE, &thread->todo);  
  30. ......  
  31.                             
  32. break;  
        由於是第一次在Binder驅動程序中傳輸這個MediaPlayerService,調用binder_get_node函數查詢這個Binder實體時,會返回空,於是binder_new_node在proc中新建一個,下次就可以直接使用了。

        現在,由於要把這個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列表中去:

  1. list_add_tail(&t->work.entry, target_list);  
        並且把待完成工作項加入到本線程的todo等待執行列表中去:
  1. list_add_tail(&tcomplete->entry, &thread->todo);  
        現在目標進程有事情可做了,於是喚醒它:
  1. if (target_wait)  
  2.     wake_up_interruptible(target_wait);  
       這裏就是要喚醒Service Manager進程了。回憶一下前面淺談Service Manager成爲Android進程間通信(IPC)機制Binder守護進程之路這篇文章,此時, Service Manager正在binder_thread_read函數中調用wait_event_interruptible進入休眠狀態。

       這裏我們先忽略一下Service Manager被喚醒之後的場景,繼續MedaPlayerService的啓動過程,然後再回來。

       回到binder_ioctl函數,bwr.read_size > 0爲true,於是進入binder_thread_read函數:

  1. static int  
  2. binder_thread_read(struct binder_proc *proc, struct binder_thread *thread,  
  3.                    void  __user *buffer, int size, signed long *consumed, int non_block)  
  4. {  
  5.     void __user *ptr = buffer + *consumed;  
  6.     void __user *end = buffer + size;  
  7.   
  8.     int ret = 0;  
  9.     int wait_for_proc_work;  
  10.   
  11.     if (*consumed == 0) {  
  12.         if (put_user(BR_NOOP, (uint32_t __user *)ptr))  
  13.             return -EFAULT;  
  14.         ptr += sizeof(uint32_t);  
  15.     }  
  16.   
  17. retry:  
  18.     wait_for_proc_work = thread->transaction_stack == NULL && list_empty(&thread->todo);  
  19.       
  20.     .......  
  21.   
  22.     if (wait_for_proc_work) {  
  23.         .......  
  24.     } else {  
  25.         if (non_block) {  
  26.             if (!binder_has_thread_work(thread))  
  27.                 ret = -EAGAIN;  
  28.         } else  
  29.             ret = wait_event_interruptible(thread->wait, binder_has_thread_work(thread));  
  30.     }  
  31.       
  32.     ......  
  33.   
  34.     while (1) {  
  35.         uint32_t cmd;  
  36.         struct binder_transaction_data tr;  
  37.         struct binder_work *w;  
  38.         struct binder_transaction *t = NULL;  
  39.   
  40.         if (!list_empty(&thread->todo))  
  41.             w = list_first_entry(&thread->todo, struct binder_work, entry);  
  42.         else if (!list_empty(&proc->todo) && wait_for_proc_work)  
  43.             w = list_first_entry(&proc->todo, struct binder_work, entry);  
  44.         else {  
  45.             if (ptr - buffer == 4 && !(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN)) /* no data added */  
  46.                 goto retry;  
  47.             break;  
  48.         }  
  49.   
  50.         if (end - ptr < sizeof(tr) + 4)  
  51.             break;  
  52.   
  53.         switch (w->type) {  
  54.         ......  
  55.         case BINDER_WORK_TRANSACTION_COMPLETE: {  
  56.             cmd = BR_TRANSACTION_COMPLETE;  
  57.             if (put_user(cmd, (uint32_t __user *)ptr))  
  58.                 return -EFAULT;  
  59.             ptr += sizeof(uint32_t);  
  60.   
  61.             binder_stat_br(proc, thread, cmd);  
  62.             if (binder_debug_mask & BINDER_DEBUG_TRANSACTION_COMPLETE)  
  63.                 printk(KERN_INFO "binder: %d:%d BR_TRANSACTION_COMPLETE\n",  
  64.                 proc->pid, thread->pid);  
  65.   
  66.             list_del(&w->entry);  
  67.             kfree(w);  
  68.             binder_stats.obj_deleted[BINDER_STAT_TRANSACTION_COMPLETE]++;  
  69.                                                } break;  
  70.         ......  
  71.         }  
  72.   
  73.         if (!t)  
  74.             continue;  
  75.   
  76.         ......  
  77.     }  
  78.   
  79. done:  
  80.     ......  
  81.     return 0;  
  82. }  

        這裏,thread->transaction_stack和thread->todo均不爲空,於是wait_for_proc_work爲false,由於binder_has_thread_work的時候,返回true,這裏因爲thread->todo不爲空,因此,線程雖然調用了wait_event_interruptible,但是不會睡眠,於是繼續往下執行。

        由於thread->todo不爲空,執行下列語句:

  1. if (!list_empty(&thread->todo))  
  2.      w = list_first_entry(&thread->todo, struct binder_work, entry);  
        w->type爲BINDER_WORK_TRANSACTION_COMPLETE,這是在上面的binder_transaction函數設置的,於是執行:
  1.    switch (w->type) {  
  2.    ......  
  3.    case BINDER_WORK_TRANSACTION_COMPLETE: {  
  4. cmd = BR_TRANSACTION_COMPLETE;  
  5. if (put_user(cmd, (uint32_t __user *)ptr))  
  6.     return -EFAULT;  
  7. ptr += sizeof(uint32_t);  
  8.   
  9.        ......  
  10. list_del(&w->entry);  
  11. kfree(w);  
  12.           
  13. break;  
  14. ......  
  15.    }  
        這裏就將w從thread->todo刪除了。由於這裏t爲空,重新執行while循環,這時由於已經沒有事情可做了,最後就返回到binder_ioctl函數中。注間,這裏一共往用戶傳進來的緩衝區buffer寫入了兩個整數,分別是BR_NOOP和BR_TRANSACTION_COMPLETE。

        binder_ioctl函數返回到用戶空間之前,把數據消耗情況拷貝回用戶空間中:

  1. if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {  
  2.     ret = -EFAULT;  
  3.     goto err;  
  4. }  
        最後返回到IPCThreadState::talkWithDriver函數中,執行下面語句:
  1.     if (err >= NO_ERROR) {  
  2.         if (bwr.write_consumed > 0) {  
  3.             if (bwr.write_consumed < (ssize_t)mOut.dataSize())  
  4.                 mOut.remove(0, bwr.write_consumed);  
  5.             else  
  6.                 mOut.setDataSize(0);  
  7.         }  
  8.         if (bwr.read_consumed > 0) {  
  9. <pre name="code" class="cpp">            mIn.setDataSize(bwr.read_consumed);  
  10.             mIn.setDataPosition(0);  
} ...... return NO_ERROR; }        首先是把mOut的數據清空:
  1. mOut.setDataSize(0);  
        然後設置已經讀取的內容的大小:
  1. mIn.setDataSize(bwr.read_consumed);  
  2. mIn.setDataPosition(0);  
        然後返回到IPCThreadState::waitForResponse函數中。在IPCThreadState::waitForResponse函數,先是從mIn讀出一個整數,這個便是BR_NOOP了,這是一個空操作,什麼也不做。然後繼續進入IPCThreadState::talkWithDriver函數中。
        這時候,下面語句執行後:
  1. const bool needRead = mIn.dataPosition() >= mIn.dataSize();  
        needRead爲false,因爲在mIn中,尚有一個整數BR_TRANSACTION_COMPLETE未讀出。

       這時候,下面語句執行後:

  1. const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;  
        outAvail等於0。因此,最後bwr.write_size和bwr.read_size均爲0,IPCThreadState::talkWithDriver函數什麼也不做,直接返回到IPCThreadState::waitForResponse函數中。在IPCThreadState::waitForResponse函數,又繼續從mIn讀出一個整數,這個便是BR_TRANSACTION_COMPLETE:
  1. switch (cmd) {  
  2. case BR_TRANSACTION_COMPLETE:  
  3.        if (!reply && !acquireResult) goto finish;  
  4.        break;  
  5. ......  
  6. }  
        reply不爲NULL,因此,IPCThreadState::waitForResponse的循環沒有結束,繼續執行,又進入到IPCThreadState::talkWithDrive中。

        這次,needRead就爲true了,而outAvail仍爲0,所以bwr.read_size不爲0,bwr.write_size爲0。於是通過:

  1. ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr)  
        進入到Binder驅動程序中的binder_ioctl函數中。由於bwr.write_size爲0,bwr.read_size不爲0,這次直接就進入到binder_thread_read函數中。這時候,thread->transaction_stack不等於0,但是thread->todo爲空,於是線程就通過:
  1. wait_event_interruptible(thread->wait, binder_has_thread_work(thread));  
        進入睡眠狀態,等待Service Manager來喚醒了。

        現在,我們可以回到Service Manager被喚醒的過程了。我們接着前面淺談Service Manager成爲Android進程間通信(IPC)機制Binder守護進程之路這篇文章的最後,繼續描述。此時, Service Manager正在binder_thread_read函數中調用wait_event_interruptible_exclusive進入休眠狀態。上面被MediaPlayerService啓動後進程喚醒後,繼續執行binder_thread_read函數:

  1. static int  
  2. binder_thread_read(struct binder_proc *proc, struct binder_thread *thread,  
  3.                    void  __user *buffer, int size, signed long *consumed, int non_block)  
  4. {  
  5.     void __user *ptr = buffer + *consumed;  
  6.     void __user *end = buffer + size;  
  7.   
  8.     int ret = 0;  
  9.     int wait_for_proc_work;  
  10.   
  11.     if (*consumed == 0) {  
  12.         if (put_user(BR_NOOP, (uint32_t __user *)ptr))  
  13.             return -EFAULT;  
  14.         ptr += sizeof(uint32_t);  
  15.     }  
  16.   
  17. retry:  
  18.     wait_for_proc_work = thread->transaction_stack == NULL && list_empty(&thread->todo);  
  19.   
  20.     ......  
  21.   
  22.     if (wait_for_proc_work) {  
  23.         ......  
  24.         if (non_block) {  
  25.             if (!binder_has_proc_work(proc, thread))  
  26.                 ret = -EAGAIN;  
  27.         } else  
  28.             ret = wait_event_interruptible_exclusive(proc->wait, binder_has_proc_work(proc, thread));  
  29.     } else {  
  30.         ......  
  31.     }  
  32.       
  33.     ......  
  34.   
  35.     while (1) {  
  36.         uint32_t cmd;  
  37.         struct binder_transaction_data tr;  
  38.         struct binder_work *w;  
  39.         struct binder_transaction *t = NULL;  
  40.   
  41.         if (!list_empty(&thread->todo))  
  42.             w = list_first_entry(&thread->todo, struct binder_work, entry);  
  43.         else if (!list_empty(&proc->todo) && wait_for_proc_work)  
  44.             w = list_first_entry(&proc->todo, struct binder_work, entry);  
  45.         else {  
  46.             if (ptr - buffer == 4 && !(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN)) /* no data added */  
  47.                 goto retry;  
  48.             break;  
  49.         }  
  50.   
  51.         if (end - ptr < sizeof(tr) + 4)  
  52.             break;  
  53.   
  54.         switch (w->type) {  
  55.         case BINDER_WORK_TRANSACTION: {  
  56.             t = container_of(w, struct binder_transaction, work);  
  57.                                       } break;  
  58.         ......  
  59.         }  
  60.   
  61.         if (!t)  
  62.             continue;  
  63.   
  64.         BUG_ON(t->buffer == NULL);  
  65.         if (t->buffer->target_node) {  
  66.             struct binder_node *target_node = t->buffer->target_node;  
  67.             tr.target.ptr = target_node->ptr;  
  68.             tr.cookie =  target_node->cookie;  
  69.             ......  
  70.             cmd = BR_TRANSACTION;  
  71.         } else {  
  72.             ......  
  73.         }  
  74.         tr.code = t->code;  
  75.         tr.flags = t->flags;  
  76.         tr.sender_euid = t->sender_euid;  
  77.   
  78.         if (t->from) {  
  79.             struct task_struct *sender = t->from->proc->tsk;  
  80.             tr.sender_pid = task_tgid_nr_ns(sender, current->nsproxy->pid_ns);  
  81.         } else {  
  82.             tr.sender_pid = 0;  
  83.         }  
  84.   
  85.         tr.data_size = t->buffer->data_size;  
  86.         tr.offsets_size = t->buffer->offsets_size;  
  87.         tr.data.ptr.buffer = (void *)t->buffer->data + proc->user_buffer_offset;  
  88.         tr.data.ptr.offsets = tr.data.ptr.buffer + ALIGN(t->buffer->data_size, sizeof(void *));  
  89.   
  90.         if (put_user(cmd, (uint32_t __user *)ptr))  
  91.             return -EFAULT;  
  92.         ptr += sizeof(uint32_t);  
  93.         if (copy_to_user(ptr, &tr, sizeof(tr)))  
  94.             return -EFAULT;  
  95.         ptr += sizeof(tr);  
  96.   
  97.         ......  
  98.   
  99.         list_del(&t->work.entry);  
  100.         t->buffer->allow_user_free = 1;  
  101.         if (cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)) {  
  102.             t->to_parent = thread->transaction_stack;  
  103.             t->to_thread = thread;  
  104.             thread->transaction_stack = t;  
  105.         } else {  
  106.             t->buffer->transaction = NULL;  
  107.             kfree(t);  
  108.             binder_stats.obj_deleted[BINDER_STAT_TRANSACTION]++;  
  109.         }  
  110.         break;  
  111.     }  
  112.   
  113. done:  
  114.   
  115.     ......  
  116.     return 0;  
  117. }  

        Service Manager被喚醒之後,就進入while循環開始處理事務了。這裏wait_for_proc_work等於1,並且proc->todo不爲空,所以從proc->todo列表中得到第一個工作項:

  1. w = list_first_entry(&proc->todo, struct binder_work, entry);  
        從上面的描述中,我們知道,這個工作項的類型爲BINDER_WORK_TRANSACTION,於是通過下面語句得到事務項:
  1. t = container_of(w, struct binder_transaction, work);  
       接着就是把事務項t中的數據拷貝到本地局部變量struct binder_transaction_data tr中去了:
  1. if (t->buffer->target_node) {  
  2.     struct binder_node *target_node = t->buffer->target_node;  
  3.     tr.target.ptr = target_node->ptr;  
  4.     tr.cookie =  target_node->cookie;  
  5.     ......  
  6.     cmd = BR_TRANSACTION;  
  7. else {  
  8.     ......  
  9. }  
  10. tr.code = t->code;  
  11. tr.flags = t->flags;  
  12. tr.sender_euid = t->sender_euid;  
  13.   
  14. if (t->from) {  
  15.     struct task_struct *sender = t->from->proc->tsk;  
  16.     tr.sender_pid = task_tgid_nr_ns(sender, current->nsproxy->pid_ns);  
  17. else {  
  18.     tr.sender_pid = 0;  
  19. }  
  20.   
  21. tr.data_size = t->buffer->data_size;  
  22. tr.offsets_size = t->buffer->offsets_size;  
  23. tr.data.ptr.buffer = (void *)t->buffer->data + proc->user_buffer_offset;  
  24. tr.data.ptr.offsets = tr.data.ptr.buffer + ALIGN(t->buffer->data_size, sizeof(void *));  
        這裏有一個非常重要的地方,是Binder進程間通信機制的精髓所在:
  1. tr.data.ptr.buffer = (void *)t->buffer->data + proc->user_buffer_offset;  
  2. tr.data.ptr.offsets = tr.data.ptr.buffer + ALIGN(t->buffer->data_size, sizeof(void *));  
        t->buffer->data所指向的地址是內核空間的,現在要把數據返回給Service Manager進程的用戶空間,而Service Manager進程的用戶空間是不能訪問內核空間的數據的,所以這裏要作一下處理。怎麼處理呢?我們在學面嚮對象語言的時候,對象的拷貝有深拷貝和淺拷貝之分,深拷貝是把另外分配一塊新內存,然後把原始對象的內容搬過去,淺拷貝是並沒有爲新對象分配一塊新空間,而只是分配一個引用,而個引用指向原始對象。Binder機制用的是類似淺拷貝的方法,通過在用戶空間分配一個虛擬地址,然後讓這個用戶空間虛擬地址與 t->buffer->data這個內核空間虛擬地址指向同一個物理地址,這樣就可以實現淺拷貝了。怎麼樣用戶空間和內核空間的虛擬地址同時指向同一個物理地址呢?請參考前面一篇文章淺談Service Manager成爲Android進程間通信(IPC)機制Binder守護進程之路,那裏有詳細描述。這裏只要將t->buffer->data加上一個偏移值proc->user_buffer_offset就可以得到t->buffer->data對應的用戶空間虛擬地址了。調整了tr.data.ptr.buffer的值之後,不要忘記也要一起調整tr.data.ptr.offsets的值。

        接着就是把tr的內容拷貝到用戶傳進來的緩衝區去了,指針ptr指向這個用戶緩衝區的地址:

  1. if (put_user(cmd, (uint32_t __user *)ptr))  
  2.     return -EFAULT;  
  3. ptr += sizeof(uint32_t);  
  4. if (copy_to_user(ptr, &tr, sizeof(tr)))  
  5.     return -EFAULT;  
  6. ptr += sizeof(tr);  
         這裏可以看出,這裏只是對作tr.data.ptr.bufferr和tr.data.ptr.offsets的內容作了淺拷貝。

         最後,由於已經處理了這個事務,要把它從todo列表中刪除:

  1. list_del(&t->work.entry);  
  2. t->buffer->allow_user_free = 1;  
  3. if (cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)) {  
  4.     t->to_parent = thread->transaction_stack;  
  5.     t->to_thread = thread;  
  6.     thread->transaction_stack = t;  
  7. else {  
  8.     t->buffer->transaction = NULL;  
  9.     kfree(t);  
  10.     binder_stats.obj_deleted[BINDER_STAT_TRANSACTION]++;  
  11. }  
         注意,這裏的cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)爲true,表明這個事務雖然在驅動程序中已經處理完了,但是它仍然要等待Service Manager完成之後,給驅動程序一個確認,也就是需要等待回覆,於是把當前事務t放在thread->transaction_stack隊列的頭部:
  1. t->to_parent = thread->transaction_stack;  
  2. t->to_thread = thread;  
  3. thread->transaction_stack = t;  
         如果cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)爲false,那就不需要等待回覆了,直接把事務t刪掉。

         這個while最後通過一個break跳了出來,最後返回到binder_ioctl函數中:

  1. static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)  
  2. {  
  3.     int ret;  
  4.     struct binder_proc *proc = filp->private_data;  
  5.     struct binder_thread *thread;  
  6.     unsigned int size = _IOC_SIZE(cmd);  
  7.     void __user *ubuf = (void __user *)arg;  
  8.   
  9.     ......  
  10.   
  11.     switch (cmd) {  
  12.     case BINDER_WRITE_READ: {  
  13.         struct binder_write_read bwr;  
  14.         if (size != sizeof(struct binder_write_read)) {  
  15.             ret = -EINVAL;  
  16.             goto err;  
  17.         }  
  18.         if (copy_from_user(&bwr, ubuf, sizeof(bwr))) {  
  19.             ret = -EFAULT;  
  20.             goto err;  
  21.         }  
  22.         ......  
  23.         if (bwr.read_size > 0) {  
  24.             ret = binder_thread_read(proc, thread, (void __user *)bwr.read_buffer, bwr.read_size, &bwr.read_consumed, filp->f_flags & O_NONBLOCK);  
  25.             if (!list_empty(&proc->todo))  
  26.                 wake_up_interruptible(&proc->wait);  
  27.             if (ret < 0) {  
  28.                 if (copy_to_user(ubuf, &bwr, sizeof(bwr)))  
  29.                     ret = -EFAULT;  
  30.                 goto err;  
  31.             }  
  32.         }  
  33.         ......  
  34.         if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {  
  35.             ret = -EFAULT;  
  36.             goto err;  
  37.         }  
  38.         break;  
  39.         }  
  40.     ......  
  41.     default:  
  42.         ret = -EINVAL;  
  43.         goto err;  
  44.     }  
  45.     ret = 0;  
  46. err:  
  47.     ......  
  48.     return ret;  
  49. }  
         從binder_thread_read返回來後,再看看proc->todo是否還有事務等待處理,如果是,就把睡眠在proc->wait隊列的線程喚醒來處理。最後,把本地變量struct binder_write_read bwr的內容拷貝回到用戶傳進來的緩衝區中,就返回了。

        這裏就是返回到frameworks/base/cmds/servicemanager/binder.c文件中的binder_loop函數了:

  1. void binder_loop(struct binder_state *bs, binder_handler func)  
  2. {  
  3.     int res;  
  4.     struct binder_write_read bwr;  
  5.     unsigned readbuf[32];  
  6.   
  7.     bwr.write_size = 0;  
  8.     bwr.write_consumed = 0;  
  9.     bwr.write_buffer = 0;  
  10.       
  11.     readbuf[0] = BC_ENTER_LOOPER;  
  12.     binder_write(bs, readbuf, sizeof(unsigned));  
  13.   
  14.     for (;;) {  
  15.         bwr.read_size = sizeof(readbuf);  
  16.         bwr.read_consumed = 0;  
  17.         bwr.read_buffer = (unsigned) readbuf;  
  18.   
  19.         res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);  
  20.   
  21.         if (res < 0) {  
  22.             LOGE("binder_loop: ioctl failed (%s)\n", strerror(errno));  
  23.             break;  
  24.         }  
  25.   
  26.         res = binder_parse(bs, 0, readbuf, bwr.read_consumed, func);  
  27.         if (res == 0) {  
  28.             LOGE("binder_loop: unexpected reply?!\n");  
  29.             break;  
  30.         }  
  31.         if (res < 0) {  
  32.             LOGE("binder_loop: io error %d %s\n", res, strerror(errno));  
  33.             break;  
  34.         }  
  35.     }  
  36. }  
       返回來的數據都放在readbuf中,接着調用binder_parse進行解析:
  1. int binder_parse(struct binder_state *bs, struct binder_io *bio,  
  2.                  uint32_t *ptr, uint32_t size, binder_handler func)  
  3. {  
  4.     int r = 1;  
  5.     uint32_t *end = ptr + (size / 4);  
  6.   
  7.     while (ptr < end) {  
  8.         uint32_t cmd = *ptr++;  
  9.         ......  
  10.         case BR_TRANSACTION: {  
  11.             struct binder_txn *txn = (void *) ptr;  
  12.             if ((end - ptr) * sizeof(uint32_t) < sizeof(struct binder_txn)) {  
  13.                 LOGE("parse: txn too small!\n");  
  14.                 return -1;  
  15.             }  
  16.             binder_dump_txn(txn);  
  17.             if (func) {  
  18.                 unsigned rdata[256/4];  
  19.                 struct binder_io msg;  
  20.                 struct binder_io reply;  
  21.                 int res;  
  22.   
  23.                 bio_init(&reply, rdata, sizeof(rdata), 4);  
  24.                 bio_init_from_txn(&msg, txn);  
  25.                 res = func(bs, txn, &msg, &reply);  
  26.                 binder_send_reply(bs, &reply, txn->data, res);  
  27.             }  
  28.             ptr += sizeof(*txn) / sizeof(uint32_t);  
  29.             break;  
  30.                              }  
  31.         ......  
  32.         default:  
  33.             LOGE("parse: OOPS %d\n", cmd);  
  34.             return -1;  
  35.         }  
  36.     }  
  37.   
  38.     return r;  
  39. }  
        首先把從Binder驅動程序讀出來的數據轉換爲一個struct binder_txn結構體,保存在txn本地變量中,struct binder_txn定義在frameworks/base/cmds/servicemanager/binder.h文件中:
  1. struct binder_txn  
  2. {  
  3.     void *target;  
  4.     void *cookie;  
  5.     uint32_t code;  
  6.     uint32_t flags;  
  7.   
  8.     uint32_t sender_pid;  
  9.     uint32_t sender_euid;  
  10.   
  11.     uint32_t data_size;  
  12.     uint32_t offs_size;  
  13.     void *data;  
  14.     void *offs;  
  15. };  
       函數中還用到了另外一個數據結構struct binder_io,也是定義在frameworks/base/cmds/servicemanager/binder.h文件中:
  1. struct binder_io  
  2. {  
  3.     char *data;            /* pointer to read/write from */  
  4.     uint32_t *offs;        /* array of offsets */  
  5.     uint32_t data_avail;   /* bytes available in data buffer */  
  6.     uint32_t offs_avail;   /* entries available in offsets array */  
  7.   
  8.     char *data0;           /* start of data buffer */  
  9.     uint32_t *offs0;       /* start of offsets buffer */  
  10.     uint32_t flags;  
  11.     uint32_t unused;  
  12. };  
       接着往下看,函數調bio_init來初始化reply變量:
  1. void bio_init(struct binder_io *bio, void *data,  
  2.               uint32_t maxdata, uint32_t maxoffs)  
  3. {  
  4.     uint32_t n = maxoffs * sizeof(uint32_t);  
  5.   
  6.     if (n > maxdata) {  
  7.         bio->flags = BIO_F_OVERFLOW;  
  8.         bio->data_avail = 0;  
  9.         bio->offs_avail = 0;  
  10.         return;  
  11.     }  
  12.   
  13.     bio->data = bio->data0 = data + n;  
  14.     bio->offs = bio->offs0 = data;  
  15.     bio->data_avail = maxdata - n;  
  16.     bio->offs_avail = maxoffs;  
  17.     bio->flags = 0;  
  18. }  
       接着又調用bio_init_from_txn來初始化msg變量:
  1. void bio_init_from_txn(struct binder_io *bio, struct binder_txn *txn)  
  2. {  
  3.     bio->data = bio->data0 = txn->data;  
  4.     bio->offs = bio->offs0 = txn->offs;  
  5.     bio->data_avail = txn->data_size;  
  6.     bio->offs_avail = txn->offs_size / 4;  
  7.     bio->flags = BIO_F_SHARED;  
  8. }  
      最後,真正進行處理的函數是從參數中傳進來的函數指針func,這裏就是定義在frameworks/base/cmds/servicemanager/service_manager.c文件中的svcmgr_handler函數:
  1. int svcmgr_handler(struct binder_state *bs,  
  2.                    struct binder_txn *txn,  
  3.                    struct binder_io *msg,  
  4.                    struct binder_io *reply)  
  5. {  
  6.     struct svcinfo *si;  
  7.     uint16_t *s;  
  8.     unsigned len;  
  9.     void *ptr;  
  10.     uint32_t strict_policy;  
  11.   
  12.     if (txn->target != svcmgr_handle)  
  13.         return -1;  
  14.   
  15.     // Equivalent to Parcel::enforceInterface(), reading the RPC  
  16.     // header with the strict mode policy mask and the interface name.  
  17.     // Note that we ignore the strict_policy and don't propagate it  
  18.     // further (since we do no outbound RPCs anyway).  
  19.     strict_policy = bio_get_uint32(msg);  
  20.     s = bio_get_string16(msg, &len);  
  21.     if ((len != (sizeof(svcmgr_id) / 2)) ||  
  22.         memcmp(svcmgr_id, s, sizeof(svcmgr_id))) {  
  23.             fprintf(stderr,"invalid id %s\n", str8(s));  
  24.             return -1;  
  25.     }  
  26.   
  27.     switch(txn->code) {  
  28.     ......  
  29.     case SVC_MGR_ADD_SERVICE:  
  30.         s = bio_get_string16(msg, &len);  
  31.         ptr = bio_get_ref(msg);  
  32.         if (do_add_service(bs, s, len, ptr, txn->sender_euid))  
  33.             return -1;  
  34.         break;  
  35.     ......  
  36.     }  
  37.   
  38.     bio_put_uint32(reply, 0);  
  39.     return 0;  
  40. }  
         回憶一下,在BpServiceManager::addService時,傳給Binder驅動程序的參數爲:
  1. writeInt32(IPCThreadState::self()->getStrictModePolicy() | STRICT_MODE_PENALTY_GATHER);  
  2. writeString16("android.os.IServiceManager");  
  3. writeString16("media.player");  
  4. writeStrongBinder(new MediaPlayerService());  
         這裏的語句:
  1. strict_policy = bio_get_uint32(msg);  
  2. s = bio_get_string16(msg, &len);  
  3. s = bio_get_string16(msg, &len);  
  4. ptr = bio_get_ref(msg);  
         就是依次把它們讀取出來了,這裏,我們只要看一下bio_get_ref的實現。先看一個數據結構struct binder_obj的定義:
  1. struct binder_object  
  2. {  
  3.     uint32_t type;  
  4.     uint32_t flags;  
  5.     void *pointer;  
  6.     void *cookie;  
  7. };  
        這個結構體其實就是對應struct flat_binder_obj的。

        接着看bio_get_ref實現:

  1. void *bio_get_ref(struct binder_io *bio)  
  2. {  
  3.     struct binder_object *obj;  
  4.   
  5.     obj = _bio_get_obj(bio);  
  6.     if (!obj)  
  7.         return 0;  
  8.   
  9.     if (obj->type == BINDER_TYPE_HANDLE)  
  10.         return obj->pointer;  
  11.   
  12.     return 0;  
  13. }  
       _bio_get_obj這個函數就不跟進去看了,它的作用就是從binder_io中取得第一個還沒取獲取過的binder_object。在這個場景下,就是我們最開始傳過來代表MediaPlayerService的flat_binder_obj了,這個原始的flat_binder_obj的type爲BINDER_TYPE_BINDER,binder爲指向MediaPlayerService的弱引用的地址。在前面我們說過,在Binder驅動驅動程序裏面,會把這個flat_binder_obj的type改爲BINDER_TYPE_HANDLE,handle改爲一個句柄值。這裏的handle值就等於obj->pointer的值。

        回到svcmgr_handler函數,調用do_add_service進一步處理:

  1. int do_add_service(struct binder_state *bs,  
  2.                    uint16_t *s, unsigned len,  
  3.                    void *ptr, unsigned uid)  
  4. {  
  5.     struct svcinfo *si;  
  6. //    LOGI("add_service('%s',%p) uid=%d\n", str8(s), ptr, uid);  
  7.   
  8.     if (!ptr || (len == 0) || (len > 127))  
  9.         return -1;  
  10.   
  11.     if (!svc_can_register(uid, s)) {  
  12.         LOGE("add_service('%s',%p) uid=%d - PERMISSION DENIED\n",  
  13.              str8(s), ptr, uid);  
  14.         return -1;  
  15.     }  
  16.   
  17.     si = find_svc(s, len);  
  18.     if (si) {  
  19.         if (si->ptr) {  
  20.             LOGE("add_service('%s',%p) uid=%d - ALREADY REGISTERED\n",  
  21.                  str8(s), ptr, uid);  
  22.             return -1;  
  23.         }  
  24.         si->ptr = ptr;  
  25.     } else {  
  26.         si = malloc(sizeof(*si) + (len + 1) * sizeof(uint16_t));  
  27.         if (!si) {  
  28.             LOGE("add_service('%s',%p) uid=%d - OUT OF MEMORY\n",  
  29.                  str8(s), ptr, uid);  
  30.             return -1;  
  31.         }  
  32.         si->ptr = ptr;  
  33.         si->len = len;  
  34.         memcpy(si->name, s, (len + 1) * sizeof(uint16_t));  
  35.         si->name[len] = '\0';  
  36.         si->death.func = svcinfo_death;  
  37.         si->death.ptr = si;  
  38.         si->next = svclist;  
  39.         svclist = si;  
  40.     }  
  41.   
  42.     binder_acquire(bs, ptr);  
  43.     binder_link_to_death(bs, ptr, &si->death);  
  44.     return 0;  
  45. }  
        這個函數的實現很簡單,就是把MediaPlayerService這個Binder實體的引用寫到一個struct svcinfo結構體中,主要是它的名稱和句柄值,然後插入到鏈接svclist的頭部去。這樣,Client來向Service Manager查詢服務接口時,只要給定服務名稱,Service Manger就可以返回相應的句柄值了。

        這個函數執行完成後,返回到svcmgr_handler函數,函數的最後,將一個錯誤碼0寫到reply變量中去,表示一切正常:

  1. bio_put_uint32(reply, 0);  

       svcmgr_handler函數執行完成後,返回到binder_parse函數,執行下面語句:

  1. binder_send_reply(bs, &reply, txn->data, res);  
       我們看一下binder_send_reply的實現,從函數名就可以猜到它要做什麼了,告訴Binder驅動程序,它完成了Binder驅動程序交給它的任務了。
  1. void binder_send_reply(struct binder_state *bs,  
  2.                        struct binder_io *reply,  
  3.                        void *buffer_to_free,  
  4.                        int status)  
  5. {  
  6.     struct {  
  7.         uint32_t cmd_free;  
  8.         void *buffer;  
  9.         uint32_t cmd_reply;  
  10.         struct binder_txn txn;  
  11.     } __attribute__((packed)) data;  
  12.   
  13.     data.cmd_free = BC_FREE_BUFFER;  
  14.     data.buffer = buffer_to_free;  
  15.     data.cmd_reply = BC_REPLY;  
  16.     data.txn.target = 0;  
  17.     data.txn.cookie = 0;  
  18.     data.txn.code = 0;  
  19.     if (status) {  
  20.         data.txn.flags = TF_STATUS_CODE;  
  21.         data.txn.data_size = sizeof(int);  
  22.         data.txn.offs_size = 0;  
  23.         data.txn.data = &status;  
  24.         data.txn.offs = 0;  
  25.     } else {  
  26.         data.txn.flags = 0;  
  27.         data.txn.data_size = reply->data - reply->data0;  
  28.         data.txn.offs_size = ((char*) reply->offs) - ((char*) reply->offs0);  
  29.         data.txn.data = reply->data0;  
  30.         data.txn.offs = reply->offs0;  
  31.     }  
  32.     binder_write(bs, &data, sizeof(data));  
  33. }  
       從這裏可以看出,binder_send_reply告訴Binder驅動程序執行BC_FREE_BUFFER和BC_REPLY命令,前者釋放之前在binder_transaction分配的空間,地址爲buffer_to_free,buffer_to_free這個地址是Binder驅動程序把自己在內核空間用的地址轉換成用戶空間地址再傳給Service Manager的,所以Binder驅動程序拿到這個地址後,知道怎麼樣釋放這個空間;後者告訴MediaPlayerService,它的addService操作已經完成了,錯誤碼是0,保存在data.txn.data中。

       再來看binder_write函數:

  1. int binder_write(struct binder_state *bs, void *data, unsigned len)  
  2. {  
  3.     struct binder_write_read bwr;  
  4.     int res;  
  5.     bwr.write_size = len;  
  6.     bwr.write_consumed = 0;  
  7.     bwr.write_buffer = (unsigned) data;  
  8.     bwr.read_size = 0;  
  9.     bwr.read_consumed = 0;  
  10.     bwr.read_buffer = 0;  
  11.     res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);  
  12.     if (res < 0) {  
  13.         fprintf(stderr,"binder_write: ioctl failed (%s)\n",  
  14.                 strerror(errno));  
  15.     }  
  16.     return res;  
  17. }  
       這裏可以看出,只有寫操作,沒有讀操作,即read_size爲0。

       這裏又是一個ioctl的BINDER_WRITE_READ操作。直入到驅動程序的binder_ioctl函數後,執行BINDER_WRITE_READ命令,這裏就不累述了。

       最後,從binder_ioctl執行到binder_thread_write函數,我們首先看第一個命令BC_FREE_BUFFER:

  1. int  
  2. binder_thread_write(struct binder_proc *proc, struct binder_thread *thread,  
  3.                     void __user *buffer, int size, signed long *consumed)  
  4. {  
  5.     uint32_t cmd;  
  6.     void __user *ptr = buffer + *consumed;  
  7.     void __user *end = buffer + size;  
  8.   
  9.     while (ptr < end && thread->return_error == BR_OK) {  
  10.         if (get_user(cmd, (uint32_t __user *)ptr))  
  11.             return -EFAULT;  
  12.         ptr += sizeof(uint32_t);  
  13.         if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.bc)) {  
  14.             binder_stats.bc[_IOC_NR(cmd)]++;  
  15.             proc->stats.bc[_IOC_NR(cmd)]++;  
  16.             thread->stats.bc[_IOC_NR(cmd)]++;  
  17.         }  
  18.         switch (cmd) {  
  19.         ......  
  20.         case BC_FREE_BUFFER: {  
  21.             void __user *data_ptr;  
  22.             struct binder_buffer *buffer;  
  23.   
  24.             if (get_user(data_ptr, (void * __user *)ptr))  
  25.                 return -EFAULT;  
  26.             ptr += sizeof(void *);  
  27.   
  28.             buffer = binder_buffer_lookup(proc, data_ptr);  
  29.             if (buffer == NULL) {  
  30.                 binder_user_error("binder: %d:%d "  
  31.                     "BC_FREE_BUFFER u%p no match\n",  
  32.                     proc->pid, thread->pid, data_ptr);  
  33.                 break;  
  34.             }  
  35.             if (!buffer->allow_user_free) {  
  36.                 binder_user_error("binder: %d:%d "  
  37.                     "BC_FREE_BUFFER u%p matched "  
  38.                     "unreturned buffer\n",  
  39.                     proc->pid, thread->pid, data_ptr);  
  40.                 break;  
  41.             }  
  42.             if (binder_debug_mask & BINDER_DEBUG_FREE_BUFFER)  
  43.                 printk(KERN_INFO "binder: %d:%d BC_FREE_BUFFER u%p found buffer %d for %s transaction\n",  
  44.                 proc->pid, thread->pid, data_ptr, buffer->debug_id,  
  45.                 buffer->transaction ? "active" : "finished");  
  46.   
  47.             if (buffer->transaction) {  
  48.                 buffer->transaction->buffer = NULL;  
  49.                 buffer->transaction = NULL;  
  50.             }  
  51.             if (buffer->async_transaction && buffer->target_node) {  
  52.                 BUG_ON(!buffer->target_node->has_async_transaction);  
  53.                 if (list_empty(&buffer->target_node->async_todo))  
  54.                     buffer->target_node->has_async_transaction = 0;  
  55.                 else  
  56.                     list_move_tail(buffer->target_node->async_todo.next, &thread->todo);  
  57.             }  
  58.             binder_transaction_buffer_release(proc, buffer, NULL);  
  59.             binder_free_buf(proc, buffer);  
  60.             break;  
  61.                              }  
  62.   
  63.         ......  
  64.         *consumed = ptr - buffer;  
  65.     }  
  66.     return 0;  
  67. }  
       首先通過看這個語句:
  1. get_user(data_ptr, (void * __user *)ptr)  
       這個是獲得要刪除的Buffer的用戶空間地址,接着通過下面這個語句來找到這個地址對應的struct binder_buffer信息:
  1. buffer = binder_buffer_lookup(proc, data_ptr);  
       因爲這個空間是前面在binder_transaction裏面分配的,所以這裏一定能找到。

       最後,就可以釋放這塊內存了:

  1. binder_transaction_buffer_release(proc, buffer, NULL);  
  2. binder_free_buf(proc, buffer);  
       再來看另外一個命令BC_REPLY:
  1. int  
  2. binder_thread_write(struct binder_proc *proc, struct binder_thread *thread,  
  3.                     void __user *buffer, int size, signed long *consumed)  
  4. {  
  5.     uint32_t cmd;  
  6.     void __user *ptr = buffer + *consumed;  
  7.     void __user *end = buffer + size;  
  8.   
  9.     while (ptr < end && thread->return_error == BR_OK) {  
  10.         if (get_user(cmd, (uint32_t __user *)ptr))  
  11.             return -EFAULT;  
  12.         ptr += sizeof(uint32_t);  
  13.         if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.bc)) {  
  14.             binder_stats.bc[_IOC_NR(cmd)]++;  
  15.             proc->stats.bc[_IOC_NR(cmd)]++;  
  16.             thread->stats.bc[_IOC_NR(cmd)]++;  
  17.         }  
  18.         switch (cmd) {  
  19.         ......  
  20.         case BC_TRANSACTION:  
  21.         case BC_REPLY: {  
  22.             struct binder_transaction_data tr;  
  23.   
  24.             if (copy_from_user(&tr, ptr, sizeof(tr)))  
  25.                 return -EFAULT;  
  26.             ptr += sizeof(tr);  
  27.             binder_transaction(proc, thread, &tr, cmd == BC_REPLY);  
  28.             break;  
  29.                        }  
  30.   
  31.         ......  
  32.         *consumed = ptr - buffer;  
  33.     }  
  34.     return 0;  
  35. }  
       又再次進入到binder_transaction函數:
  1. static void  
  2. binder_transaction(struct binder_proc *proc, struct binder_thread *thread,  
  3. struct binder_transaction_data *tr, int reply)  
  4. {  
  5.     struct binder_transaction *t;  
  6.     struct binder_work *tcomplete;  
  7.     size_t *offp, *off_end;  
  8.     struct binder_proc *target_proc;  
  9.     struct binder_thread *target_thread = NULL;  
  10.     struct binder_node *target_node = NULL;  
  11.     struct list_head *target_list;  
  12.     wait_queue_head_t *target_wait;  
  13.     struct binder_transaction *in_reply_to = NULL;  
  14.     struct binder_transaction_log_entry *e;  
  15.     uint32_t return_error;  
  16.   
  17.     ......  
  18.   
  19.     if (reply) {  
  20.         in_reply_to = thread->transaction_stack;  
  21.         if (in_reply_to == NULL) {  
  22.             ......  
  23.             return_error = BR_FAILED_REPLY;  
  24.             goto err_empty_call_stack;  
  25.         }  
  26.         binder_set_nice(in_reply_to->saved_priority);  
  27.         if (in_reply_to->to_thread != thread) {  
  28.             .......  
  29.             goto err_bad_call_stack;  
  30.         }  
  31.         thread->transaction_stack = in_reply_to->to_parent;  
  32.         target_thread = in_reply_to->from;  
  33.         if (target_thread == NULL) {  
  34.             return_error = BR_DEAD_REPLY;  
  35.             goto err_dead_binder;  
  36.         }  
  37.         if (target_thread->transaction_stack != in_reply_to) {  
  38.             ......  
  39.             return_error = BR_FAILED_REPLY;  
  40.             in_reply_to = NULL;  
  41.             target_thread = NULL;  
  42.             goto err_dead_binder;  
  43.         }  
  44.         target_proc = target_thread->proc;  
  45.     } else {  
  46.         ......  
  47.     }  
  48.     if (target_thread) {  
  49.         e->to_thread = target_thread->pid;  
  50.         target_list = &target_thread->todo;  
  51.         target_wait = &target_thread->wait;  
  52.     } else {  
  53.         ......  
  54.     }  
  55.   
  56.   
  57.     /* TODO: reuse incoming transaction for reply */  
  58.     t = kzalloc(sizeof(*t), GFP_KERNEL);  
  59.     if (t == NULL) {  
  60.         return_error = BR_FAILED_REPLY;  
  61.         goto err_alloc_t_failed;  
  62.     }  
  63.       
  64.   
  65.     tcomplete = kzalloc(sizeof(*tcomplete), GFP_KERNEL);  
  66.     if (tcomplete == NULL) {  
  67.         return_error = BR_FAILED_REPLY;  
  68.         goto err_alloc_tcomplete_failed;  
  69.     }  
  70.   
  71.     if (!reply && !(tr->flags & TF_ONE_WAY))  
  72.         t->from = thread;  
  73.     else  
  74.         t->from = NULL;  
  75.     t->sender_euid = proc->tsk->cred->euid;  
  76.     t->to_proc = target_proc;  
  77.     t->to_thread = target_thread;  
  78.     t->code = tr->code;  
  79.     t->flags = tr->flags;  
  80.     t->priority = task_nice(current);  
  81.     t->buffer = binder_alloc_buf(target_proc, tr->data_size,  
  82.         tr->offsets_size, !reply && (t->flags & TF_ONE_WAY));  
  83.     if (t->buffer == NULL) {  
  84.         return_error = BR_FAILED_REPLY;  
  85.         goto err_binder_alloc_buf_failed;  
  86.     }  
  87.     t->buffer->allow_user_free = 0;  
  88.     t->buffer->debug_id = t->debug_id;  
  89.     t->buffer->transaction = t;  
  90.     t->buffer->target_node = target_node;  
  91.     if (target_node)  
  92.         binder_inc_node(target_node, 1, 0, NULL);  
  93.   
  94.     offp = (size_t *)(t->buffer->data + ALIGN(tr->data_size, sizeof(void *)));  
  95.   
  96.     if (copy_from_user(t->buffer->data, tr->data.ptr.buffer, tr->data_size)) {  
  97.         binder_user_error("binder: %d:%d got transaction with invalid "  
  98.             "data ptr\n", proc->pid, thread->pid);  
  99.         return_error = BR_FAILED_REPLY;  
  100.         goto err_copy_data_failed;  
  101.     }  
  102.     if (copy_from_user(offp, tr->data.ptr.offsets, tr->offsets_size)) {  
  103.         binder_user_error("binder: %d:%d got transaction with invalid "  
  104.             "offsets ptr\n", proc->pid, thread->pid);  
  105.         return_error = BR_FAILED_REPLY;  
  106.         goto err_copy_data_failed;  
  107.     }  
  108.       
  109.     ......  
  110.   
  111.     if (reply) {  
  112.         BUG_ON(t->buffer->async_transaction != 0);  
  113.         binder_pop_transaction(target_thread, in_reply_to);  
  114.     } else if (!(t->flags & TF_ONE_WAY)) {  
  115.         ......  
  116.     } else {  
  117.         ......  
  118.     }  
  119.     t->work.type = BINDER_WORK_TRANSACTION;  
  120.     list_add_tail(&t->work.entry, target_list);  
  121.     tcomplete->type = BINDER_WORK_TRANSACTION_COMPLETE;  
  122.     list_add_tail(&tcomplete->entry, &thread->todo);  
  123.     if (target_wait)  
  124.         wake_up_interruptible(target_wait);  
  125.     return;  
  126.     ......  
  127. }  
       注意,這裏的reply爲1,我們忽略掉其它無關代碼。

       前面Service Manager正在binder_thread_read函數中被MediaPlayerService啓動後進程喚醒後,在最後會把當前處理完的事務放在thread->transaction_stack中:

  1. if (cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)) {  
  2.     t->to_parent = thread->transaction_stack;  
  3.     t->to_thread = thread;  
  4.     thread->transaction_stack = t;  
  5. }   
       所以,這裏,首先是把它這個binder_transaction取回來,並且放在本地變量in_reply_to中:
  1. in_reply_to = thread->transaction_stack;  
       接着就可以通過in_reply_to得到最終發出這個事務請求的線程和進程:
  1. target_thread = in_reply_to->from;  
  2. target_proc = target_thread->proc;  
        然後得到target_list和target_wait:
  1. target_list = &target_thread->todo;  
  2. target_wait = &target_thread->wait;  
       下面這一段代碼:
  1. /* TODO: reuse incoming transaction for reply */  
  2. t = kzalloc(sizeof(*t), GFP_KERNEL);  
  3. if (t == NULL) {  
  4.     return_error = BR_FAILED_REPLY;  
  5.     goto err_alloc_t_failed;  
  6. }  
  7.   
  8.   
  9. tcomplete = kzalloc(sizeof(*tcomplete), GFP_KERNEL);  
  10. if (tcomplete == NULL) {  
  11.     return_error = BR_FAILED_REPLY;  
  12.     goto err_alloc_tcomplete_failed;  
  13. }  
  14.   
  15. if (!reply && !(tr->flags & TF_ONE_WAY))  
  16.     t->from = thread;  
  17. else  
  18.     t->from = NULL;  
  19. t->sender_euid = proc->tsk->cred->euid;  
  20. t->to_proc = target_proc;  
  21. t->to_thread = target_thread;  
  22. t->code = tr->code;  
  23. t->flags = tr->flags;  
  24. t->priority = task_nice(current);  
  25. t->buffer = binder_alloc_buf(target_proc, tr->data_size,  
  26.     tr->offsets_size, !reply && (t->flags & TF_ONE_WAY));  
  27. if (t->buffer == NULL) {  
  28.     return_error = BR_FAILED_REPLY;  
  29.     goto err_binder_alloc_buf_failed;  
  30. }  
  31. t->buffer->allow_user_free = 0;  
  32. t->buffer->debug_id = t->debug_id;  
  33. t->buffer->transaction = t;  
  34. t->buffer->target_node = target_node;  
  35. if (target_node)  
  36.     binder_inc_node(target_node, 1, 0, NULL);  
  37.   
  38. offp = (size_t *)(t->buffer->data + ALIGN(tr->data_size, sizeof(void *)));  
  39.   
  40. if (copy_from_user(t->buffer->data, tr->data.ptr.buffer, tr->data_size)) {  
  41.     binder_user_error("binder: %d:%d got transaction with invalid "  
  42.         "data ptr\n", proc->pid, thread->pid);  
  43.     return_error = BR_FAILED_REPLY;  
  44.     goto err_copy_data_failed;  
  45. }  
  46. if (copy_from_user(offp, tr->data.ptr.offsets, tr->offsets_size)) {  
  47.     binder_user_error("binder: %d:%d got transaction with invalid "  
  48.         "offsets ptr\n", proc->pid, thread->pid);  
  49.     return_error = BR_FAILED_REPLY;  
  50.     goto err_copy_data_failed;  
  51. }  
          我們在前面已經分析過了,這裏不再重複。但是有一點要注意的是,這裏target_node爲NULL,因此,t->buffer->target_node也爲NULL。

          函數本來有一個for循環,用來處理數據中的Binder對象,這裏由於沒有Binder對象,所以就略過了。到了下面這句代碼:

  1. binder_pop_transaction(target_thread, in_reply_to);  
          我們看看做了什麼事情:
  1. static void  
  2. binder_pop_transaction(  
  3.     struct binder_thread *target_thread, struct binder_transaction *t)  
  4. {  
  5.     if (target_thread) {  
  6.         BUG_ON(target_thread->transaction_stack != t);  
  7.         BUG_ON(target_thread->transaction_stack->from != target_thread);  
  8.         target_thread->transaction_stack =  
  9.             target_thread->transaction_stack->from_parent;  
  10.         t->from = NULL;  
  11.     }  
  12.     t->need_reply = 0;  
  13.     if (t->buffer)  
  14.         t->buffer->transaction = NULL;  
  15.     kfree(t);  
  16.     binder_stats.obj_deleted[BINDER_STAT_TRANSACTION]++;  
  17. }  
        由於到了這裏,已經不需要in_reply_to這個transaction了,就把它刪掉。

        回到binder_transaction函數:

  1. t->work.type = BINDER_WORK_TRANSACTION;  
  2. list_add_tail(&t->work.entry, target_list);  
  3. tcomplete->type = BINDER_WORK_TRANSACTION_COMPLETE;  
  4. list_add_tail(&tcomplete->entry, &thread->todo);  
         和前面一樣,分別把t和tcomplete分別放在target_list和thread->todo隊列中,這裏的target_list指的就是最初調用IServiceManager::addService的MediaPlayerService的Server主線程的的thread->todo隊列了,而thread->todo指的是Service Manager中用來回復IServiceManager::addService請求的線程。

        最後,喚醒等待在target_wait隊列上的線程了,就是最初調用IServiceManager::addService的MediaPlayerService的Server主線程了,它最後在binder_thread_read函數中睡眠在thread->wait上,就是這裏的target_wait了:

  1. if (target_wait)  
  2.     wake_up_interruptible(target_wait);  
        這樣,Service Manger回覆調用IServiceManager::addService請求就算完成了,重新回到frameworks/base/cmds/servicemanager/binder.c文件中的binder_loop函數等待下一個Client請求的到來。事實上,Service Manger回到binder_loop函數再次執行ioctl函數時候,又會再次進入到binder_thread_read函數。這時個會發現thread->todo不爲空,這是因爲剛纔我們調用了:
  1. list_add_tail(&tcomplete->entry, &thread->todo);  
          把一個工作項tcompelete放在了在thread->todo中,這個tcompelete的type爲BINDER_WORK_TRANSACTION_COMPLETE,因此,Binder驅動程序會執行下面操作:
  1. switch (w->type) {  
  2. case BINDER_WORK_TRANSACTION_COMPLETE: {  
  3.     cmd = BR_TRANSACTION_COMPLETE;  
  4.     if (put_user(cmd, (uint32_t __user *)ptr))  
  5.         return -EFAULT;  
  6.     ptr += sizeof(uint32_t);  
  7.   
  8.     list_del(&w->entry);  
  9.     kfree(w);  
  10.       
  11.     } break;  
  12.     ......  
  13. }  
        binder_loop函數執行完這個ioctl調用後,纔會在下一次調用ioctl進入到Binder驅動程序進入休眠狀態,等待下一次Client的請求。

        上面講到調用IServiceManager::addService的MediaPlayerService的Server主線程被喚醒了,於是,重新執行binder_thread_read函數:

  1. static int  
  2. binder_thread_read(struct binder_proc *proc, struct binder_thread *thread,  
  3.                    void  __user *buffer, int size, signed long *consumed, int non_block)  
  4. {  
  5.     void __user *ptr = buffer + *consumed;  
  6.     void __user *end = buffer + size;  
  7.   
  8.     int ret = 0;  
  9.     int wait_for_proc_work;  
  10.   
  11.     if (*consumed == 0) {  
  12.         if (put_user(BR_NOOP, (uint32_t __user *)ptr))  
  13.             return -EFAULT;  
  14.         ptr += sizeof(uint32_t);  
  15.     }  
  16.   
  17. retry:  
  18.     wait_for_proc_work = thread->transaction_stack == NULL && list_empty(&thread->todo);  
  19.   
  20.     ......  
  21.   
  22.     if (wait_for_proc_work) {  
  23.         ......  
  24.     } else {  
  25.         if (non_block) {  
  26.             if (!binder_has_thread_work(thread))  
  27.                 ret = -EAGAIN;  
  28.         } else  
  29.             ret = wait_event_interruptible(thread->wait, binder_has_thread_work(thread));  
  30.     }  
  31.       
  32.     ......  
  33.   
  34.     while (1) {  
  35.         uint32_t cmd;  
  36.         struct binder_transaction_data tr;  
  37.         struct binder_work *w;  
  38.         struct binder_transaction *t = NULL;  
  39.   
  40.         if (!list_empty(&thread->todo))  
  41.             w = list_first_entry(&thread->todo, struct binder_work, entry);  
  42.         else if (!list_empty(&proc->todo) && wait_for_proc_work)  
  43.             w = list_first_entry(&proc->todo, struct binder_work, entry);  
  44.         else {  
  45.             if (ptr - buffer == 4 && !(thread->looper & BINDER_LOOPER_STATE_NEED_RETURN)) /* no data added */  
  46.                 goto retry;  
  47.             break;  
  48.         }  
  49.   
  50.         ......  
  51.   
  52.         switch (w->type) {  
  53.         case BINDER_WORK_TRANSACTION: {  
  54.             t = container_of(w, struct binder_transaction, work);  
  55.                                       } break;  
  56.         ......  
  57.         }  
  58.   
  59.         if (!t)  
  60.             continue;  
  61.   
  62.         BUG_ON(t->buffer == NULL);  
  63.         if (t->buffer->target_node) {  
  64.             ......  
  65.         } else {  
  66.             tr.target.ptr = NULL;  
  67.             tr.cookie = NULL;  
  68.             cmd = BR_REPLY;  
  69.         }  
  70.         tr.code = t->code;  
  71.         tr.flags = t->flags;  
  72.         tr.sender_euid = t->sender_euid;  
  73.   
  74.         if (t->from) {  
  75.             ......  
  76.         } else {  
  77.             tr.sender_pid = 0;  
  78.         }  
  79.   
  80.         tr.data_size = t->buffer->data_size;  
  81.         tr.offsets_size = t->buffer->offsets_size;  
  82.         tr.data.ptr.buffer = (void *)t->buffer->data + proc->user_buffer_offset;  
  83.         tr.data.ptr.offsets = tr.data.ptr.buffer + ALIGN(t->buffer->data_size, sizeof(void *));  
  84.   
  85.         if (put_user(cmd, (uint32_t __user *)ptr))  
  86.             return -EFAULT;  
  87.         ptr += sizeof(uint32_t);  
  88.         if (copy_to_user(ptr, &tr, sizeof(tr)))  
  89.             return -EFAULT;  
  90.         ptr += sizeof(tr);  
  91.   
  92.         ......  
  93.   
  94.         list_del(&t->work.entry);  
  95.         t->buffer->allow_user_free = 1;  
  96.         if (cmd == BR_TRANSACTION && !(t->flags & TF_ONE_WAY)) {  
  97.             ......  
  98.         } else {  
  99.             t->buffer->transaction = NULL;  
  100.             kfree(t);  
  101.             binder_stats.obj_deleted[BINDER_STAT_TRANSACTION]++;  
  102.         }  
  103.         break;  
  104.     }  
  105.   
  106. done:  
  107.     ......  
  108.     return 0;  
  109. }  
         在while循環中,從thread->todo得到w,w->type爲BINDER_WORK_TRANSACTION,於是,得到t。從上面可以知道,Service Manager反回了一個0回來,寫在t->buffer->data裏面,現在把t->buffer->data加上proc->user_buffer_offset,得到用戶空間地址,保存在tr.data.ptr.buffer裏面,這樣用戶空間就可以訪問這個返回碼了。由於cmd不等於BR_TRANSACTION,這時就可以把t刪除掉了,因爲以後都不需要用了。

         執行完這個函數後,就返回到binder_ioctl函數,執行下面語句,把數據返回給用戶空間:

  1. if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {  
  2.     ret = -EFAULT;  
  3.     goto err;  
  4. }  
         接着返回到用戶空間IPCThreadState::talkWithDriver函數,最後返回到IPCThreadState::waitForResponse函數,最終執行到下面語句:
  1. status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)  
  2. {  
  3.     int32_t cmd;  
  4.     int32_t err;  
  5.   
  6.     while (1) {  
  7.         if ((err=talkWithDriver()) < NO_ERROR) break;  
  8.           
  9.         ......  
  10.   
  11.         cmd = mIn.readInt32();  
  12.   
  13.         ......  
  14.   
  15.         switch (cmd) {  
  16.         ......  
  17.         case BR_REPLY:  
  18.             {  
  19.                 binder_transaction_data tr;  
  20.                 err = mIn.read(&tr, sizeof(tr));  
  21.                 LOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");  
  22.                 if (err != NO_ERROR) goto finish;  
  23.   
  24.                 if (reply) {  
  25.                     if ((tr.flags & TF_STATUS_CODE) == 0) {  
  26.                         reply->ipcSetDataReference(  
  27.                             reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),  
  28.                             tr.data_size,  
  29.                             reinterpret_cast<const size_t*>(tr.data.ptr.offsets),  
  30.                             tr.offsets_size/sizeof(size_t),  
  31.                             freeBuffer, this);  
  32.                     } else {  
  33.                         ......  
  34.                     }  
  35.                 } else {  
  36.                     ......  
  37.                 }  
  38.             }  
  39.             goto finish;  
  40.   
  41.         ......  
  42.         }  
  43.     }  
  44.   
  45. finish:  
  46.     ......  
  47.     return err;  
  48. }  

        注意,這裏的tr.flags等於0,這個是在上面的binder_send_reply函數裏設置的。最終把結果保存在reply了:

  1. reply->ipcSetDataReference(  
  2.        reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),  
  3.        tr.data_size,  
  4.        reinterpret_cast<const size_t*>(tr.data.ptr.offsets),  
  5.        tr.offsets_size/sizeof(size_t),  
  6.        freeBuffer, this);  
       這個函數我們就不看了,有興趣的讀者可以研究一下。

       從這裏層層返回,最後回到MediaPlayerService::instantiate函數中。

       至此,IServiceManager::addService終於執行完畢了。這個過程非常複雜,但是如果我們能夠深刻地理解這一過程,將能很好地理解Binder機制的設計思想和實現過程。這裏,對IServiceManager::addService過程中MediaPlayerService、ServiceManager和BinderDriver之間的交互作一個小結:


        回到frameworks/base/media/mediaserver/main_mediaserver.cpp文件中的main函數,接下去還要執行下面兩個函數:

  1. ProcessState::self()->startThreadPool();  
  2. IPCThreadState::self()->joinThreadPool();  
        首先看ProcessState::startThreadPool函數的實現:
  1. void ProcessState::startThreadPool()  
  2. {  
  3.     AutoMutex _l(mLock);  
  4.     if (!mThreadPoolStarted) {  
  5.         mThreadPoolStarted = true;  
  6.         spawnPooledThread(true);  
  7.     }  
  8. }  
       這裏調用spwanPooledThread:
  1. void ProcessState::spawnPooledThread(bool isMain)  
  2. {  
  3.     if (mThreadPoolStarted) {  
  4.         int32_t s = android_atomic_add(1, &mThreadPoolSeq);  
  5.         char buf[32];  
  6.         sprintf(buf, "Binder Thread #%d", s);  
  7.         LOGV("Spawning new pooled thread, name=%s\n", buf);  
  8.         sp<Thread> t = new PoolThread(isMain);  
  9.         t->run(buf);  
  10.     }  
  11. }  
       這裏主要是創建一個線程,PoolThread繼續Thread類,Thread類定義在frameworks/base/libs/utils/Threads.cpp文件中,其run函數最終調用子類的threadLoop函數,這裏即爲PoolThread::threadLoop函數:
  1. virtual bool threadLoop()  
  2. {  
  3.     IPCThreadState::self()->joinThreadPool(mIsMain);  
  4.     return false;  
  5. }  
       這裏和frameworks/base/media/mediaserver/main_mediaserver.cpp文件中的main函數一樣,最終都是調用了IPCThreadState::joinThreadPool函數,它們的區別是,一個參數是true,一個是默認值false。我們來看一下這個函數的實現:
  1. void IPCThreadState::joinThreadPool(bool isMain)  
  2. {  
  3.     LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());  
  4.   
  5.     mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);  
  6.   
  7.     ......  
  8.   
  9.     status_t result;  
  10.     do {  
  11.         int32_t cmd;  
  12.   
  13.         .......  
  14.   
  15.         // now get the next command to be processed, waiting if necessary  
  16.         result = talkWithDriver();  
  17.         if (result >= NO_ERROR) {  
  18.             size_t IN = mIn.dataAvail();  
  19.             if (IN < sizeof(int32_t)) continue;  
  20.             cmd = mIn.readInt32();  
  21.             ......  
  22.             }  
  23.   
  24.             result = executeCommand(cmd);  
  25.         }  
  26.   
  27.         ......  
  28.     } while (result != -ECONNREFUSED && result != -EBADF);  
  29.   
  30.     .......  
  31.   
  32.     mOut.writeInt32(BC_EXIT_LOOPER);  
  33.     talkWithDriver(false);  
  34. }  
        這個函數最終是在一個無窮循環中,通過調用talkWithDriver函數來和Binder驅動程序進行交互,實際上就是調用talkWithDriver來等待Client的請求,然後再調用executeCommand來處理請求,而在executeCommand函數中,最終會調用BBinder::transact來真正處理Client的請求:
  1. status_t IPCThreadState::executeCommand(int32_t cmd)  
  2. {  
  3.     BBinder* obj;  
  4.     RefBase::weakref_type* refs;  
  5.     status_t result = NO_ERROR;  
  6.   
  7.     switch (cmd) {  
  8.     ......  
  9.   
  10.     case BR_TRANSACTION:  
  11.         {  
  12.             binder_transaction_data tr;  
  13.             result = mIn.read(&tr, sizeof(tr));  
  14.               
  15.             ......  
  16.   
  17.             Parcel reply;  
  18.               
  19.             ......  
  20.   
  21.             if (tr.target.ptr) {  
  22.                 sp<BBinder> b((BBinder*)tr.cookie);  
  23.                 const status_t error = b->transact(tr.code, buffer, &reply, tr.flags);  
  24.                 if (error < NO_ERROR) reply.setError(error);  
  25.   
  26.             } else {  
  27.                 const status_t error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);  
  28.                 if (error < NO_ERROR) reply.setError(error);  
  29.             }  
  30.   
  31.             ......  
  32.         }  
  33.         break;  
  34.   
  35.     .......  
  36.     }  
  37.   
  38.     if (result != NO_ERROR) {  
  39.         mLastError = result;  
  40.     }  
  41.   
  42.     return result;  
  43. }  
        接下來再看一下BBinder::transact的實現:
  1. status_t BBinder::transact(  
  2.     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)  
  3. {  
  4.     data.setDataPosition(0);  
  5.   
  6.     status_t err = NO_ERROR;  
  7.     switch (code) {  
  8.         case PING_TRANSACTION:  
  9.             reply->writeInt32(pingBinder());  
  10.             break;  
  11.         default:  
  12.             err = onTransact(code, data, reply, flags);  
  13.             break;  
  14.     }  
  15.   
  16.     if (reply != NULL) {  
  17.         reply->setDataPosition(0);  
  18.     }  
  19.   
  20.     return err;  
  21. }  
       最終會調用onTransact函數來處理。在這個場景中,BnMediaPlayerService繼承了BBinder類,並且重載了onTransact函數,因此,這裏實際上是調用了BnMediaPlayerService::onTransact函數,這個函數定義在frameworks/base/libs/media/libmedia/IMediaPlayerService.cpp文件中:
  1. status_t BnMediaPlayerService::onTransact(  
  2.     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)  
  3. {  
  4.     switch(code) {  
  5.         case CREATE_URL: {  
  6.             ......  
  7.                          } break;  
  8.         case CREATE_FD: {  
  9.             ......  
  10.                         } break;  
  11.         case DECODE_URL: {  
  12.             ......  
  13.                          } break;  
  14.         case DECODE_FD: {  
  15.             ......  
  16.                         } break;  
  17.         case CREATE_MEDIA_RECORDER: {  
  18.             ......  
  19.                                     } break;  
  20.         case CREATE_METADATA_RETRIEVER: {  
  21.             ......  
  22.                                         } break;  
  23.         case GET_OMX: {  
  24.             ......  
  25.                       } break;  
  26.         default:  
  27.             return BBinder::onTransact(code, data, reply, flags);  
  28.     }  
  29. }  

       至此,我們就以MediaPlayerService爲例,完整地介紹了Android系統進程間通信Binder機制中的Server啓動過程。Server啓動起來之後,就會在一個無窮循環中等待Client的請求了。在下一篇文章中,我們將介紹Client如何通過Service Manager遠程接口來獲得Server遠程接口,進而調用Server遠程接口來使用Server提供的服務,敬請關注。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章