深入了解mediaserver-2

来源:互联网 发布:飞天怎么样知乎 编辑:程序博客网 时间:2024/06/08 08:29

4.2 BnServiceManager<servicemanager进程>

      上面说了,defaultServiceManager返回的是一个BpServiceManager,通过它可以把命令请求发送到binder设备,而且handle的值为0。那么,系统的另外一端肯定有个接收命令的,那又是谁呢?

      很可惜啊,BnServiceManager不存在,但确实有一个程序完成了BnServiceManager的工作,那就是/system/bin/servicemanager进程.虽然service_manager没有从BnServiceManager中派生,但是它肯定完成了BnServiceManager的功能。

[html] view plaincopy
  1. //service_manager.c  
  2. int main(int argc, char **argv)  
  3. {  
  4.     struct binder_state *bs;  
  5.     void *svcmgr = BINDER_SERVICE_MANAGER;  
  6.   
  7.     bs = binder_open(128*1024);  
  8.   
  9.     if (binder_become_context_manager(bs)) {  
  10.         LOGE("cannot become context manager (%s)\n", strerror(errno));  
  11.         return -1;  
  12.     }  
  13.   
  14.     svcmgr_handle = svcmgr;  
  15.    <span style="color:#ff0000;"> binder_loop(bs, svcmgr_handler);  
  16. </span>    return 0;  
  17. }  
[html] view plaincopy
  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.         <span style="color:#ff0000;">res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);  
  20. </span>  
  21.         if (res < 0) {  
  22.             LOGE("binder_loop: ioctl failed (%s)\n", strerror(errno));  
  23.             break;  
  24.         }  
  25.   
  26.         <span style="color:#ff0000;">res = binder_parse(bs, 0, readbuf, bwr.read_consumed, func);  
  27. </span>        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. }  
[html] view plaincopy
  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.   
  11. //    LOGI("target=%p code=%d pid=%d uid=%d\n",  
  12. //         txn->target, txn->code, txn->sender_pid, txn->sender_euid);  
  13.   
  14.     if (txn->target != svcmgr_handle)  
  15.         return -1;  
  16.   
  17.     s = bio_get_string16(msg, &len);  
  18.   
  19.     if ((len != (sizeof(svcmgr_id) / 2)) ||  
  20.         memcmp(svcmgr_id, s, sizeof(svcmgr_id))) {  
  21.         fprintf(stderr,"invalid id %s\n", str8(s));  
  22.         return -1;  
  23.     }  
  24.   
  25.     switch(txn->code) {  
  26.     case SVC_MGR_GET_SERVICE:  
  27.     case SVC_MGR_CHECK_SERVICE:  
  28.         s = bio_get_string16(msg, &len);  
  29.         ptr = do_find_service(bs, s, len);  
  30.         if (!ptr)  
  31.             break;  
  32.         bio_put_ref(reply, ptr);  
  33.         return 0;  
  34.   
  35.     case SVC_MGR_ADD_SERVICE:  
  36.         s = bio_get_string16(msg, &len);  
  37.         ptr = bio_get_ref(msg);  
  38.         if (do_add_service(bs, s, len, ptr, txn->sender_euid)) <span style="color:#ff0000;">//add a service to svclist  
  39. </span>            return -1;  
  40.         break;  
  41.   
  42.     case SVC_MGR_LIST_SERVICES: {  
  43.         unsigned n = bio_get_uint32(msg);  
  44.   
  45.         si = svclist;  
  46.         while ((n-- > 0) && si)  
  47.             si = si->next;  
  48.         if (si) {  
  49.             bio_put_string16(reply, si->name);  
  50.             return 0;  
  51.         }  
  52.         return -1;  
  53.     }  
  54.     default:  
  55.         LOGE("unknown code %d\n", txn->code);  
  56.         return -1;  
  57.     }  
  58.   
  59.     bio_put_uint32(reply, 0);  
  60.     return 0;  
  61. }  


5. MediaPlayerService等待请求
/system/bin/mediaserver在ProcessState::Self()中打开了binder,其looper又在哪儿呢?

[html] view plaincopy
  1. //main_mediaserver.cpp  
  2. int main(int argc, char** argv)  
  3. {  
  4.     sp<ProcessState> proc(ProcessState::self());  
  5.     sp<IServiceManager> sm = defaultServiceManager();  
  6.     LOGI("ServiceManager: %p", sm.get());  
  7.     AudioFlinger::instantiate();  
  8.     MediaPlayerService::instantiate();  
  9.     CameraService::instantiate();  
  10.     AudioPolicyService::instantiate();  
  11.     ProcessState::self()->startThreadPool();  
  12.     IPCThreadState::self()->joinThreadPool();  
  13. }  

5.1 startThreadPool

[html] view plaincopy
  1. void ProcessState::startThreadPool()  
  2. {  
  3.     AutoMutex _l(mLock);  
  4.     if (!mThreadPoolStarted) {  
  5.         mThreadPoolStarted = true;  
  6.         spawnPooledThread(true);  
  7.     }  
  8. }  
  9. void ProcessState::spawnPooledThread(bool isMain)  
  10. {  
  11.     if (mThreadPoolStarted) {  
  12.         int32_t s = android_atomic_add(1, &mThreadPoolSeq);  
  13.         char buf[32];  
  14.   
  15.         sprintf(buf, "Binder Thread #%d", s);  
  16.         LOGV("Spawning new pooled thread, name=%s\n", buf);  
  17.   
  18.         <span style="color:#ff0000;">//创建线程池,然后run起来,和java的Thread何其像也。  
  19. </span>        sp<Thread> t = new PoolThread(isMain);  
  20.         t->run(buf);  
  21.     }  
  22. }  
  23.   
  24. class PoolThread : public Thread  
  25. {  
  26. public:  
  27.     PoolThread(bool isMain)  
  28.         : mIsMain(isMain)  
  29.     {  
  30.     }  
  31.       
  32. protected:  
  33.     virtual bool threadLoop()  
  34.     {  
  35.         IPCThreadState::self()->joinThreadPool(mIsMain);  
  36.         return false;  
  37.     }  
  38.       
  39.     const bool mIsMain;  
  40. };  
  41.   
  42. <span style="font-size:18px;color:#ff0000;">//还没有创建线程  
  43. </span>status_t Thread::run(const char* name, int32_t priority, size_t stack)  
  44. {  
  45.     Mutex::Autolock _l(mLock);  
  46.   
  47.     if (mRunning) {  
  48.         // thread already started  
  49.         return INVALID_OPERATION;  
  50.     }  
  51.   
  52.     // reset status and exitPending to their default value, so we can  
  53.     // try again after an error happened (either below, or in readyToRun())  
  54.     mStatus = NO_ERROR;  
  55.     mExitPending = false;  
  56.     mThread = thread_id_t(-1);  
  57.       
  58.     // hold a strong reference on ourself  
  59.     mHoldSelf = this;  
  60.   
  61.     mRunning = true;  
  62.   
  63.     bool res;  
  64.     if (mCanCallJava) {  
  65.         <span style="color:#ff0000;">//name为android:unnamed_thread  
  66. </span>        res = createThreadEtc<span style="color:#ff0000;">(_threadLoop</span>,  
  67.                 this, name, priority, stack, &mThread);  
  68.     } else {  
  69.         res = androidCreateRawThreadEtc(_<span style="color:#ff0000;">threadLoop</span>,  
  70.                 this, name, priority, stack, &mThread);  
  71.     }  
  72.       
  73.       
  74.     if (res == false) {  
  75.         mStatus = UNKNOWN_ERROR;   // something happened!  
  76.         mRunning = false;  
  77.         mThread = thread_id_t(-1);  
  78.         mHoldSelf.clear();  // "this" may have gone away after this.  
  79.   
  80.         return UNKNOWN_ERROR;  
  81.     }  
  82.       
  83.     // Do not refer to mStatus here: The thread is already running (may, in fact  
  84.     // already have exited with a valid mStatus result). The NO_ERROR indication  
  85.     // here merely indicates successfully starting the thread and does not  
  86.     // imply successful termination/execution.  
  87.     return NO_ERROR;  
  88. }  
  89.   
  90. int androidCreateRawThreadEtc(android_thread_func_t entryFunction,  
  91.                                void *userData,  
  92.                                const char* threadName,  
  93.                                int32_t threadPriority,  
  94.                                size_t threadStackSize,  
  95.                                android_thread_id_t *threadId)  
  96. {  
  97.     pthread_attr_t attr;   
  98.     pthread_attr_init(&attr);  
  99.     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);  
  100.   
  101. #ifdef HAVE_ANDROID_OS  /* valgrind is rejecting RT-priority create reqs */  
  102.     if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {  
  103.         // We could avoid the trampoline if there was a way to get to the  
  104.         // android_thread_id_t (pid) from pthread_t  
  105.         thread_data_t* t = new thread_data_t;  
  106.         t->priority = threadPriority;  
  107.         t->threadName = threadName ? strdup(threadName) : NULL;  
  108.         t->entryFunction = entryFunction;  
  109.         t->userData = userData;  
  110.         entryFunction = (android_thread_func_t)&thread_data_t::trampoline;  
  111.         userData = t;              
  112.     }  
  113. #endif  
  114.   
  115.     if (threadStackSize) {  
  116.         pthread_attr_setstacksize(&attr, threadStackSize);  
  117.     }  
  118.       
  119.     errno = 0;  
  120.     pthread_t thread;  
  121.     <span style="color:#ff0000;">//终于看到了熟悉的线程创建,入口函数为:_threadLoop  
  122. </span>    int result = pthread_create(&thread, &attr,  
  123.                     (android_pthread_entry)entryFunction, userData);  
  124.     if (result != 0) {  
  125.         LOGE("androidCreateRawThreadEtc failed (entry=%p, res=%d, errno=%d)\n"  
  126.              "(android threadPriority=%d)",  
  127.             entryFunction, result, errno, threadPriority);  
  128.         return 0;  
  129.     }  
  130.   
  131.     if (threadId != NULL) {  
  132.         *threadId = (android_thread_id_t)thread; // XXX: this is not portable  
  133.     }  
  134.     return 1;  
  135. }  

 

新开的线程的入口函数为:_threadLoop
 

[html] view plaincopy
  1. <span style="color:#ff0000;">int Thread::_threadLoop(void* user)  
  2. </span>{  
  3.     Thread* const self = static_cast<Thread*>(user);  
  4.     sp<Thread> strong(self->mHoldSelf);  
  5.     wp<Thread> weak(strong);  
  6.     self->mHoldSelf.clear();  
  7.   
  8. #if HAVE_ANDROID_OS  
  9.     // this is very useful for debugging with gdb  
  10.     self->mTid = gettid();  
  11. #endif  
  12.   
  13.     bool first = true;  
  14.   
  15.     do {  
  16.         bool result;  
  17.         if (first) {  
  18.             first = false;  
  19.             self->mStatus = self->readyToRun();  
  20.             result = (self->mStatus == NO_ERROR);  
  21.   
  22.             if (result && !self->mExitPending) {  
  23.                 // Binder threads (and maybe others) rely on threadLoop  
  24.                 // running at least once after a successful ::readyToRun()  
  25.                 // (unless, of course, the thread has already been asked to exit  
  26.                 // at that point).  
  27.                 // This is because threads are essentially used like this:  
  28.                 //   (new ThreadSubclass())->run();  
  29.                 // The caller therefore does not retain a strong reference to  
  30.                 // the thread and the thread would simply disappear after the  
  31.                 // successful ::readyToRun() call instead of entering the  
  32.                 // threadLoop at least once.  
  33.                 result = self->threadLoop();  <span style="color:#ff0000;">//调用自己的<span lang="EN-US">threadLoop</span>  
  34. </span>            }  
  35.         } else {  
  36.             result = self->threadLoop();  
  37.         }  
  38.   
  39.         if (result == false || self->mExitPending) {  
  40.             self->mExitPending = true;  
  41.             self->mLock.lock();  
  42.             self->mRunning = false;  
  43.             self->mThreadExitedCondition.broadcast();  
  44.             self->mLock.unlock();  
  45.             break;  
  46.         }  
  47.           
  48.         // Release our strong reference, to let a chance to the thread  
  49.         // to die a peaceful death.  
  50.         strong.clear();  
  51.         // And immediately, re-acquire a strong reference for the next loop  
  52.         strong = weak.promote();  
  53.     } while(strong != 0);  
  54.       
  55.     return 0;  
  56. }  

PoolThread::threadLoop

[html] view plaincopy
  1. class PoolThread : public Thread  
  2. {  
  3. public:  
  4.     PoolThread(bool isMain)  
  5.         : mIsMain(isMain)  
  6.     {  
  7.     }  
  8.       
  9. protected:  
  10.     <span style="color:#ff0000;">virtual bool threadLoop()</span>  
  11.     {   ////mIsMain为true。 而且注意,这是一个新的线程,所以必然会创建一个新的IPCThreadState对象(记得线程本地存储吗?TLS)  
  12.         <span style="color:#ff0000;">IPCThreadState::self()->joinThreadPool(mIsMain);  
  13. </span>        return false;  
  14.     }  
  15.       
  16.     const bool mIsMain;  
  17. };  

主线程和工作线程都调用了joinThreadPool

[html] view plaincopy
  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.     <span style="color:#ff0000;">mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);  
  6. </span>      
  7.     // This thread may have been spawned by a thread that was in the background  
  8.     // scheduling group, so first we will make sure it is in the default/foreground  
  9.     // one to avoid performing an initial transaction in the background.  
  10.     androidSetThreadSchedulingGroup(mMyThreadId, ANDROID_TGROUP_DEFAULT);  
  11.           
  12.     status_t result;  
  13.     do {  
  14.         int32_t cmd;  
  15.           
  16.         // When we've cleared the incoming command queue, process any pending derefs  
  17.         if (mIn.dataPosition() >= mIn.dataSize()) {  
  18.             size_t numPending = mPendingWeakDerefs.size();  
  19.             if (numPending > 0) {  
  20.                 for (size_t i = 0; i < numPending; i++) {  
  21.                     RefBase::weakref_type* refs = mPendingWeakDerefs[i];  
  22.                     refs->decWeak(mProcess.get());  
  23.                 }  
  24.                 mPendingWeakDerefs.clear();  
  25.             }  
  26.   
  27.             numPending = mPendingStrongDerefs.size();  
  28.             if (numPending > 0) {  
  29.                 for (size_t i = 0; i < numPending; i++) {  
  30.                     BBinder* obj = mPendingStrongDerefs[i];  
  31.                     obj->decStrong(mProcess.get());  
  32.                 }  
  33.                 mPendingStrongDerefs.clear();  
  34.             }  
  35.         }  
  36.   
  37.         // now get the next command to be processed, waiting if necessary  
  38.         <span style="color:#ff0000;">result = talkWithDriver();  
  39. </span>        if (result >= NO_ERROR) {  
  40.             size_t IN = mIn.dataAvail();  
  41.             if (IN < sizeof(int32_t)) continue;  
  42.             cmd = mIn.readInt32();  
  43.             IF_LOG_COMMANDS() {  
  44.                 alog << "Processing top-level Command: "  
  45.                     << getReturnString(cmd) << endl;  
  46.             }  
  47.   
  48.   
  49.             <span style="color:#ff0000;">result = executeCommand(cmd);  
  50. </span>        }  
  51.           
  52.         // After executing the command, ensure that the thread is returned to the  
  53.         // default cgroup before rejoining the pool.  The driver takes care of  
  54.         // restoring the priority, but doesn't do anything with cgroups so we  
  55.         // need to take care of that here in userspace.  Note that we do make  
  56.         // sure to go in the foreground after executing a transaction, but  
  57.         // there are other callbacks into user code that could have changed  
  58.         // our group so we want to make absolutely sure it is put back.  
  59.         androidSetThreadSchedulingGroup(mMyThreadId, ANDROID_TGROUP_DEFAULT);  
  60.   
  61.         // Let this thread exit the thread pool if it is no longer  
  62.         // needed and it is not the main process thread.  
  63.         if(result == TIMED_OUT && !isMain) {  
  64.             break;  
  65.         }  
  66.     } while (result != -ECONNREFUSED && result != -EBADF);  
  67.   
  68.     LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%p\n",  
  69.         (void*)pthread_self(), getpid(), (void*)result);  
  70.       
  71.     mOut.writeInt32(BC_EXIT_LOOPER);  
  72.     talkWithDriver(false);  
  73. }  

有loop了,但是有两个线程都执行了这个啊!这里有两个消息循环?
看看executeCommand

[html] view plaincopy
  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.     case BR_ERROR:  
  9.         result = mIn.readInt32();  
  10.         break;  
  11.           
  12.     case BR_OK:  
  13.         break;  
  14.           
  15.     case BR_ACQUIRE:  
  16.         refs = (RefBase::weakref_type*)mIn.readInt32();  
  17.         obj = (BBinder*)mIn.readInt32();  
  18.         LOG_ASSERT(refs->refBase() == obj,  
  19.                    "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",  
  20.                    refs, obj, refs->refBase());  
  21.         obj->incStrong(mProcess.get());  
  22.         IF_LOG_REMOTEREFS() {  
  23.             LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);  
  24.             obj->printRefs();  
  25.         }  
  26.         mOut.writeInt32(BC_ACQUIRE_DONE);  
  27.         mOut.writeInt32((int32_t)refs);  
  28.         mOut.writeInt32((int32_t)obj);  
  29.         break;  
  30.           
  31.     case BR_RELEASE:  
  32.         refs = (RefBase::weakref_type*)mIn.readInt32();  
  33.         obj = (BBinder*)mIn.readInt32();  
  34.         LOG_ASSERT(refs->refBase() == obj,  
  35.                    "BR_RELEASE: object %p does not match cookie %p (expected %p)",  
  36.                    refs, obj, refs->refBase());  
  37.         IF_LOG_REMOTEREFS() {  
  38.             LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);  
  39.             obj->printRefs();  
  40.         }  
  41.         mPendingStrongDerefs.push(obj);  
  42.         break;  
  43.           
  44.     case BR_INCREFS:  
  45.         refs = (RefBase::weakref_type*)mIn.readInt32();  
  46.         obj = (BBinder*)mIn.readInt32();  
  47.         refs->incWeak(mProcess.get());  
  48.         mOut.writeInt32(BC_INCREFS_DONE);  
  49.         mOut.writeInt32((int32_t)refs);  
  50.         mOut.writeInt32((int32_t)obj);  
  51.         break;  
  52.           
  53.     case BR_DECREFS:  
  54.         refs = (RefBase::weakref_type*)mIn.readInt32();  
  55.         obj = (BBinder*)mIn.readInt32();  
  56.         // NOTE: This assertion is not valid, because the object may no  
  57.         // longer exist (thus the (BBinder*)cast above resulting in a different  
  58.         // memory address).  
  59.         //LOG_ASSERT(refs->refBase() == obj,  
  60.         //           "BR_DECREFS: object %p does not match cookie %p (expected %p)",  
  61.         //           refs, obj, refs->refBase());  
  62.         mPendingWeakDerefs.push(refs);  
  63.         break;  
  64.           
  65.     case BR_ATTEMPT_ACQUIRE:  
  66.         refs = (RefBase::weakref_type*)mIn.readInt32();  
  67.         obj = (BBinder*)mIn.readInt32();  
  68.            
  69.         {  
  70.             const bool success = refs->attemptIncStrong(mProcess.get());  
  71.             LOG_ASSERT(success && refs->refBase() == obj,  
  72.                        "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",  
  73.                        refs, obj, refs->refBase());  
  74.               
  75.             mOut.writeInt32(BC_ACQUIRE_RESULT);  
  76.             mOut.writeInt32((int32_t)success);  
  77.         }  
  78.         break;  
  79.       
  80.     <span style="color:#ff0000;">case BR_TRANSACTION:  
  81. </span>        {  
  82.             binder_transaction_data tr;  
  83.             result = mIn.read(&tr, sizeof(tr));  
  84.             LOG_ASSERT(result == NO_ERROR,  
  85.                 "Not enough command data for brTRANSACTION");  
  86.             if (result != NO_ERROR) break;  
  87.               
  88.             Parcel buffer;  
  89.             buffer.ipcSetDataReference(  
  90.                 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),  
  91.                 tr.data_size,  
  92.                 reinterpret_cast<const size_t*>(tr.data.ptr.offsets),  
  93.                 tr.offsets_size/sizeof(size_t), freeBuffer, this);  
  94.               
  95.             const pid_t origPid = mCallingPid;  
  96.             const uid_t origUid = mCallingUid;  
  97.               
  98.             mCallingPid = tr.sender_pid;  
  99.             mCallingUid = tr.sender_euid;  
  100.               
  101.             int curPrio = getpriority(PRIO_PROCESS, mMyThreadId);  
  102.             if (gDisableBackgroundScheduling) {  
  103.                 if (curPrio > ANDROID_PRIORITY_NORMAL) {  
  104.                     // We have inherited a reduced priority from the caller, but do not  
  105.                     // want to run in that state in this process.  The driver set our  
  106.                     // priority already (though not our scheduling class), so bounce  
  107.                     // it back to the default before invoking the transaction.  
  108.                     setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL);  
  109.                 }  
  110.             } else {  
  111.                 if (curPrio >= ANDROID_PRIORITY_BACKGROUND) {  
  112.                     // We want to use the inherited priority from the caller.  
  113.                     // Ensure this thread is in the background scheduling class,  
  114.                     // since the driver won't modify scheduling classes for us.  
  115.                     // The scheduling group is reset to default by the caller  
  116.                     // once this method returns after the transaction is complete.  
  117.                     androidSetThreadSchedulingGroup(mMyThreadId,  
  118.                                                     ANDROID_TGROUP_BG_NONINTERACT);  
  119.                 }  
  120.             }  
  121.   
  122.             //LOGI(">>>> TRANSACT from pid %d uid %d\n", mCallingPid, mCallingUid);  
  123.               
  124.             Parcel reply;  
  125.             IF_LOG_TRANSACTIONS() {  
  126.                 TextOutput::Bundle _b(alog);  
  127.                 alog << "BR_TRANSACTION thr " << (void*)pthread_self()  
  128.                     << " / obj " << tr.target.ptr << " / code "  
  129.                     << TypeCode(tr.code) << ": " << indent << buffer  
  130.                     << dedent << endl  
  131.                     << "Data addr = "  
  132.                     << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)  
  133.                     << ", offsets addr="  
  134.                     << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;  
  135.             }  
  136.        <span style="color:#ff0000;">     if (tr.target.ptr) {  
  137.                 sp<BBinder> b((BBinder*)tr.cookie); <span style="color:#3333ff;">//这里用的是<span lang="EN-US">BBinder</span>。  
  138. </span>                const status_t error = b->transact(tr.code, buffer, &reply, 0);  
  139.                 if (error < NO_ERROR) reply.setError(error);  
  140.                   
  141.             } else {  
  142.                 const status_t error = the_context_object->transact(tr.code, buffer, &reply, 0);  
  143.                 if (error < NO_ERROR) reply.setError(error);  
  144.             }  
  145. </span>              
  146.             //LOGI("<<<< TRANSACT from pid %d restore pid %d uid %d\n",  
  147.             //     mCallingPid, origPid, origUid);  
  148.               
  149.             if ((tr.flags & TF_ONE_WAY) == 0) {  
  150.                 LOG_ONEWAY("Sending reply to %d!", mCallingPid);  
  151.                 sendReply(reply, 0);  
  152.             } else {  
  153.                 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);  
  154.             }  
  155.               
  156.             mCallingPid = origPid;  
  157.             mCallingUid = origUid;  
  158.   
  159.             IF_LOG_TRANSACTIONS() {  
  160.                 TextOutput::Bundle _b(alog);  
  161.                 alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "  
  162.                     << tr.target.ptr << ": " << indent << reply << dedent << endl;  
  163.             }  
  164.               
  165.         }  
  166.         break;  
  167.       
  168.     case BR_DEAD_BINDER:  
  169.         {  
  170.             BpBinder *proxy = (BpBinder*)mIn.readInt32();  
  171.             proxy->sendObituary();  
  172.             mOut.writeInt32(BC_DEAD_BINDER_DONE);  
  173.             mOut.writeInt32((int32_t)proxy);  
  174.         } break;  
  175.           
  176.     case BR_CLEAR_DEATH_NOTIFICATION_DONE:  
  177.         {  
  178.             BpBinder *proxy = (BpBinder*)mIn.readInt32();  
  179.             proxy->getWeakRefs()->decWeak(proxy);  
  180.         } break;  
  181.           
  182.     case BR_FINISHED:  
  183.         result = TIMED_OUT;  
  184.         break;  
  185.           
  186.     case BR_NOOP:  
  187.         break;  
  188.           
  189.     case BR_SPAWN_LOOPER:  
  190.         mProcess->spawnPooledThread(false);  
  191.         break;  
  192.           
  193.     default:  
  194.         printf("*** BAD COMMAND %d received from Binder driver\n", cmd);  
  195.         result = UNKNOWN_ERROR;  
  196.         break;  
  197.     }  
  198.   
  199.     if (result != NO_ERROR) {  
  200.         mLastError = result;  
  201.     }  
  202.       
  203.     return result;  
  204. }  

BBinder的transact函数如下:

[html] view plaincopy
  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);  <span style="color:#ff0000;">//调用自己的onTransact,实际调用BnMediaPlayerService::onTransact  
  13. </span>            break;  
  14.     }  
  15.   
  16.     if (reply != NULL) {  
  17.         reply->setDataPosition(0);  
  18.     }  
  19.   
  20.     return err;  
  21. }  

BnMediaPlayerService从BBinder派生,所以会调用到它的onTransact函数,终于水落石出了,让我们看看BnMediaPlayerServcice的onTransact函数。

[html] view plaincopy
  1. status_t BnMediaPlayerService::onTransact(  
  2.     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)  
  3. {  
  4. <span style="color:#ff0000;">    // BnMediaPlayerService从BBinder和IMediaPlayerService派生  
  5.      // 所有IMediaPlayerService提供的函数都通过命令类型来区分  
  6. </span>  
  7.     switch(code) {  
  8.         case CREATE_URL: {  
  9.             CHECK_INTERFACE(IMediaPlayerService, data, reply);  
  10.             pid_t pid = data.readInt32();  
  11.             sp<IMediaPlayerClient> client =  
  12.                 interface_cast<IMediaPlayerClient>(data.readStrongBinder());  
  13.             const char* url = data.readCString();  
  14.   
  15.             KeyedVector<String8, String8> headers;  
  16.             int32_t numHeaders = data.readInt32();  
  17.             for (int i = 0; i < numHeaders; ++i) {  
  18.                 String8 key = data.readString8();  
  19.                 String8 value = data.readString8();  
  20.                 headers.add(key, value);  
  21.             }  
  22.           <span style="color:#ff0000;">//create是一个虚函数,由MediaPlayerService来实现,见MediaPlayerService::create  
  23. </span>          <span style="color:#ff0000;">//MediaPlayerService.cpp  
  24. </span>            sp<IMediaPlayer> player = create(  
  25.                     pid, client, url, numHeaders > 0 ? &headers : NULL);  
  26.   
  27.             reply->writeStrongBinder(player->asBinder());  
  28.             return NO_ERROR;  
  29.         } break;  
  30.         ...  
  31.    }  
  32. }  

其实,到这里,我们就明白了。BnXXX的onTransact函数收取命令,然后派发到派生类XXX的对应函数,由他们完成实际的工作。

说明:
    这里有点特殊,startThreadPool和joinThreadPool完后确实有两个线程,主线程和工作线程,而且都在做消息循环。为什么要这么做呢?他们参数isMain都是true。不知道google搞什么。难道是怕一个线程工作量太多,所以搞两个线程来工作?这种解释应该也是合理的。
    网上有人测试过把最后一句屏蔽掉,也能正常工作。但是难道主线程退出了,程序还能不退出吗?这个...管它的,反正知道有两个线程在那处理就行了。



 

0 0