• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2005 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "IPCThreadState"
18 
19 #include <binder/IPCThreadState.h>
20 
21 #include <binder/Binder.h>
22 #include <binder/BpBinder.h>
23 #include <cutils/sched_policy.h>
24 #include <utils/Debug.h>
25 #include <utils/Log.h>
26 #include <utils/TextOutput.h>
27 #include <utils/threads.h>
28 
29 #include <private/binder/binder_module.h>
30 #include <private/binder/Static.h>
31 
32 #include <sys/ioctl.h>
33 #include <signal.h>
34 #include <errno.h>
35 #include <stdio.h>
36 #include <unistd.h>
37 
38 #ifdef HAVE_PTHREADS
39 #include <pthread.h>
40 #include <sched.h>
41 #include <sys/resource.h>
42 #endif
43 #ifdef HAVE_WIN32_THREADS
44 #include <windows.h>
45 #endif
46 
47 
48 #if LOG_NDEBUG
49 
50 #define IF_LOG_TRANSACTIONS() if (false)
51 #define IF_LOG_COMMANDS() if (false)
52 #define LOG_REMOTEREFS(...)
53 #define IF_LOG_REMOTEREFS() if (false)
54 #define LOG_THREADPOOL(...)
55 #define LOG_ONEWAY(...)
56 
57 #else
58 
59 #define IF_LOG_TRANSACTIONS() IF_LOG(LOG_VERBOSE, "transact")
60 #define IF_LOG_COMMANDS() IF_LOG(LOG_VERBOSE, "ipc")
61 #define LOG_REMOTEREFS(...) LOG(LOG_DEBUG, "remoterefs", __VA_ARGS__)
62 #define IF_LOG_REMOTEREFS() IF_LOG(LOG_DEBUG, "remoterefs")
63 #define LOG_THREADPOOL(...) LOG(LOG_DEBUG, "threadpool", __VA_ARGS__)
64 #define LOG_ONEWAY(...) LOG(LOG_DEBUG, "ipc", __VA_ARGS__)
65 
66 #endif
67 
68 // ---------------------------------------------------------------------------
69 
70 namespace android {
71 
72 static const char* getReturnString(size_t idx);
73 static const char* getCommandString(size_t idx);
74 static const void* printReturnCommand(TextOutput& out, const void* _cmd);
75 static const void* printCommand(TextOutput& out, const void* _cmd);
76 
77 // This will result in a missing symbol failure if the IF_LOG_COMMANDS()
78 // conditionals don't get stripped...  but that is probably what we want.
79 #if !LOG_NDEBUG
80 static const char *kReturnStrings[] = {
81 #if 1 /* TODO: error update strings */
82     "unknown",
83 #else
84     "BR_OK",
85     "BR_TIMEOUT",
86     "BR_WAKEUP",
87     "BR_TRANSACTION",
88     "BR_REPLY",
89     "BR_ACQUIRE_RESULT",
90     "BR_DEAD_REPLY",
91     "BR_TRANSACTION_COMPLETE",
92     "BR_INCREFS",
93     "BR_ACQUIRE",
94     "BR_RELEASE",
95     "BR_DECREFS",
96     "BR_ATTEMPT_ACQUIRE",
97     "BR_EVENT_OCCURRED",
98     "BR_NOOP",
99     "BR_SPAWN_LOOPER",
100     "BR_FINISHED",
101     "BR_DEAD_BINDER",
102     "BR_CLEAR_DEATH_NOTIFICATION_DONE"
103 #endif
104 };
105 
106 static const char *kCommandStrings[] = {
107 #if 1 /* TODO: error update strings */
108     "unknown",
109 #else
110     "BC_NOOP",
111     "BC_TRANSACTION",
112     "BC_REPLY",
113     "BC_ACQUIRE_RESULT",
114     "BC_FREE_BUFFER",
115     "BC_TRANSACTION_COMPLETE",
116     "BC_INCREFS",
117     "BC_ACQUIRE",
118     "BC_RELEASE",
119     "BC_DECREFS",
120     "BC_INCREFS_DONE",
121     "BC_ACQUIRE_DONE",
122     "BC_ATTEMPT_ACQUIRE",
123     "BC_RETRIEVE_ROOT_OBJECT",
124     "BC_SET_THREAD_ENTRY",
125     "BC_REGISTER_LOOPER",
126     "BC_ENTER_LOOPER",
127     "BC_EXIT_LOOPER",
128     "BC_SYNC",
129     "BC_STOP_PROCESS",
130     "BC_STOP_SELF",
131     "BC_REQUEST_DEATH_NOTIFICATION",
132     "BC_CLEAR_DEATH_NOTIFICATION",
133     "BC_DEAD_BINDER_DONE"
134 #endif
135 };
136 
getReturnString(size_t idx)137 static const char* getReturnString(size_t idx)
138 {
139     if (idx < sizeof(kReturnStrings) / sizeof(kReturnStrings[0]))
140         return kReturnStrings[idx];
141     else
142         return "unknown";
143 }
144 
getCommandString(size_t idx)145 static const char* getCommandString(size_t idx)
146 {
147     if (idx < sizeof(kCommandStrings) / sizeof(kCommandStrings[0]))
148         return kCommandStrings[idx];
149     else
150         return "unknown";
151 }
152 
printBinderTransactionData(TextOutput & out,const void * data)153 static const void* printBinderTransactionData(TextOutput& out, const void* data)
154 {
155     const binder_transaction_data* btd =
156         (const binder_transaction_data*)data;
157     out << "target=" << btd->target.ptr << " (cookie " << btd->cookie << ")" << endl
158         << "code=" << TypeCode(btd->code) << ", flags=" << (void*)btd->flags << endl
159         << "data=" << btd->data.ptr.buffer << " (" << (void*)btd->data_size
160         << " bytes)" << endl
161         << "offsets=" << btd->data.ptr.offsets << " (" << (void*)btd->offsets_size
162         << " bytes)" << endl;
163     return btd+1;
164 }
165 
printReturnCommand(TextOutput & out,const void * _cmd)166 static const void* printReturnCommand(TextOutput& out, const void* _cmd)
167 {
168     static const int32_t N = sizeof(kReturnStrings)/sizeof(kReturnStrings[0]);
169 
170     const int32_t* cmd = (const int32_t*)_cmd;
171     int32_t code = *cmd++;
172     if (code == BR_ERROR) {
173         out << "BR_ERROR: " << (void*)(*cmd++) << endl;
174         return cmd;
175     } else if (code < 0 || code >= N) {
176         out << "Unknown reply: " << code << endl;
177         return cmd;
178     }
179 
180     out << kReturnStrings[code];
181     switch (code) {
182         case BR_TRANSACTION:
183         case BR_REPLY: {
184             out << ": " << indent;
185             cmd = (const int32_t *)printBinderTransactionData(out, cmd);
186             out << dedent;
187         } break;
188 
189         case BR_ACQUIRE_RESULT: {
190             const int32_t res = *cmd++;
191             out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
192         } break;
193 
194         case BR_INCREFS:
195         case BR_ACQUIRE:
196         case BR_RELEASE:
197         case BR_DECREFS: {
198             const int32_t b = *cmd++;
199             const int32_t c = *cmd++;
200             out << ": target=" << (void*)b << " (cookie " << (void*)c << ")";
201         } break;
202 
203         case BR_ATTEMPT_ACQUIRE: {
204             const int32_t p = *cmd++;
205             const int32_t b = *cmd++;
206             const int32_t c = *cmd++;
207             out << ": target=" << (void*)b << " (cookie " << (void*)c
208                 << "), pri=" << p;
209         } break;
210 
211         case BR_DEAD_BINDER:
212         case BR_CLEAR_DEATH_NOTIFICATION_DONE: {
213             const int32_t c = *cmd++;
214             out << ": death cookie " << (void*)c;
215         } break;
216     }
217 
218     out << endl;
219     return cmd;
220 }
221 
printCommand(TextOutput & out,const void * _cmd)222 static const void* printCommand(TextOutput& out, const void* _cmd)
223 {
224     static const int32_t N = sizeof(kCommandStrings)/sizeof(kCommandStrings[0]);
225 
226     const int32_t* cmd = (const int32_t*)_cmd;
227     int32_t code = *cmd++;
228     if (code < 0 || code >= N) {
229         out << "Unknown command: " << code << endl;
230         return cmd;
231     }
232 
233     out << kCommandStrings[code];
234     switch (code) {
235         case BC_TRANSACTION:
236         case BC_REPLY: {
237             out << ": " << indent;
238             cmd = (const int32_t *)printBinderTransactionData(out, cmd);
239             out << dedent;
240         } break;
241 
242         case BC_ACQUIRE_RESULT: {
243             const int32_t res = *cmd++;
244             out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
245         } break;
246 
247         case BC_FREE_BUFFER: {
248             const int32_t buf = *cmd++;
249             out << ": buffer=" << (void*)buf;
250         } break;
251 
252         case BC_INCREFS:
253         case BC_ACQUIRE:
254         case BC_RELEASE:
255         case BC_DECREFS: {
256             const int32_t d = *cmd++;
257             out << ": descriptor=" << (void*)d;
258         } break;
259 
260         case BC_INCREFS_DONE:
261         case BC_ACQUIRE_DONE: {
262             const int32_t b = *cmd++;
263             const int32_t c = *cmd++;
264             out << ": target=" << (void*)b << " (cookie " << (void*)c << ")";
265         } break;
266 
267         case BC_ATTEMPT_ACQUIRE: {
268             const int32_t p = *cmd++;
269             const int32_t d = *cmd++;
270             out << ": decriptor=" << (void*)d << ", pri=" << p;
271         } break;
272 
273         case BC_REQUEST_DEATH_NOTIFICATION:
274         case BC_CLEAR_DEATH_NOTIFICATION: {
275             const int32_t h = *cmd++;
276             const int32_t c = *cmd++;
277             out << ": handle=" << h << " (death cookie " << (void*)c << ")";
278         } break;
279 
280         case BC_DEAD_BINDER_DONE: {
281             const int32_t c = *cmd++;
282             out << ": death cookie " << (void*)c;
283         } break;
284     }
285 
286     out << endl;
287     return cmd;
288 }
289 #endif
290 
291 static pthread_mutex_t gTLSMutex = PTHREAD_MUTEX_INITIALIZER;
292 static bool gHaveTLS = false;
293 static pthread_key_t gTLS = 0;
294 static bool gShutdown = false;
295 static bool gDisableBackgroundScheduling = false;
296 
self()297 IPCThreadState* IPCThreadState::self()
298 {
299     if (gHaveTLS) {
300 restart:
301         const pthread_key_t k = gTLS;
302         IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
303         if (st) return st;
304         return new IPCThreadState;
305     }
306 
307     if (gShutdown) return NULL;
308 
309     pthread_mutex_lock(&gTLSMutex);
310     if (!gHaveTLS) {
311         if (pthread_key_create(&gTLS, threadDestructor) != 0) {
312             pthread_mutex_unlock(&gTLSMutex);
313             return NULL;
314         }
315         gHaveTLS = true;
316     }
317     pthread_mutex_unlock(&gTLSMutex);
318     goto restart;
319 }
320 
shutdown()321 void IPCThreadState::shutdown()
322 {
323     gShutdown = true;
324 
325     if (gHaveTLS) {
326         // XXX Need to wait for all thread pool threads to exit!
327         IPCThreadState* st = (IPCThreadState*)pthread_getspecific(gTLS);
328         if (st) {
329             delete st;
330             pthread_setspecific(gTLS, NULL);
331         }
332         gHaveTLS = false;
333     }
334 }
335 
disableBackgroundScheduling(bool disable)336 void IPCThreadState::disableBackgroundScheduling(bool disable)
337 {
338     gDisableBackgroundScheduling = disable;
339 }
340 
process()341 sp<ProcessState> IPCThreadState::process()
342 {
343     return mProcess;
344 }
345 
clearLastError()346 status_t IPCThreadState::clearLastError()
347 {
348     const status_t err = mLastError;
349     mLastError = NO_ERROR;
350     return err;
351 }
352 
getCallingPid()353 int IPCThreadState::getCallingPid()
354 {
355     return mCallingPid;
356 }
357 
getCallingUid()358 int IPCThreadState::getCallingUid()
359 {
360     return mCallingUid;
361 }
362 
clearCallingIdentity()363 int64_t IPCThreadState::clearCallingIdentity()
364 {
365     int64_t token = ((int64_t)mCallingUid<<32) | mCallingPid;
366     clearCaller();
367     return token;
368 }
369 
setStrictModePolicy(int32_t policy)370 void IPCThreadState::setStrictModePolicy(int32_t policy)
371 {
372     mStrictModePolicy = policy;
373 }
374 
getStrictModePolicy() const375 int32_t IPCThreadState::getStrictModePolicy() const
376 {
377     return mStrictModePolicy;
378 }
379 
setLastTransactionBinderFlags(int32_t flags)380 void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
381 {
382     mLastTransactionBinderFlags = flags;
383 }
384 
getLastTransactionBinderFlags() const385 int32_t IPCThreadState::getLastTransactionBinderFlags() const
386 {
387     return mLastTransactionBinderFlags;
388 }
389 
restoreCallingIdentity(int64_t token)390 void IPCThreadState::restoreCallingIdentity(int64_t token)
391 {
392     mCallingUid = (int)(token>>32);
393     mCallingPid = (int)token;
394 }
395 
clearCaller()396 void IPCThreadState::clearCaller()
397 {
398     mCallingPid = getpid();
399     mCallingUid = getuid();
400 }
401 
flushCommands()402 void IPCThreadState::flushCommands()
403 {
404     if (mProcess->mDriverFD <= 0)
405         return;
406     talkWithDriver(false);
407 }
408 
joinThreadPool(bool isMain)409 void IPCThreadState::joinThreadPool(bool isMain)
410 {
411     LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
412 
413     mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
414 
415     // This thread may have been spawned by a thread that was in the background
416     // scheduling group, so first we will make sure it is in the default/foreground
417     // one to avoid performing an initial transaction in the background.
418     androidSetThreadSchedulingGroup(mMyThreadId, ANDROID_TGROUP_DEFAULT);
419 
420     status_t result;
421     do {
422         int32_t cmd;
423 
424         // When we've cleared the incoming command queue, process any pending derefs
425         if (mIn.dataPosition() >= mIn.dataSize()) {
426             size_t numPending = mPendingWeakDerefs.size();
427             if (numPending > 0) {
428                 for (size_t i = 0; i < numPending; i++) {
429                     RefBase::weakref_type* refs = mPendingWeakDerefs[i];
430                     refs->decWeak(mProcess.get());
431                 }
432                 mPendingWeakDerefs.clear();
433             }
434 
435             numPending = mPendingStrongDerefs.size();
436             if (numPending > 0) {
437                 for (size_t i = 0; i < numPending; i++) {
438                     BBinder* obj = mPendingStrongDerefs[i];
439                     obj->decStrong(mProcess.get());
440                 }
441                 mPendingStrongDerefs.clear();
442             }
443         }
444 
445         // now get the next command to be processed, waiting if necessary
446         result = talkWithDriver();
447         if (result >= NO_ERROR) {
448             size_t IN = mIn.dataAvail();
449             if (IN < sizeof(int32_t)) continue;
450             cmd = mIn.readInt32();
451             IF_LOG_COMMANDS() {
452                 alog << "Processing top-level Command: "
453                     << getReturnString(cmd) << endl;
454             }
455 
456 
457             result = executeCommand(cmd);
458         }
459 
460         // After executing the command, ensure that the thread is returned to the
461         // default cgroup before rejoining the pool.  The driver takes care of
462         // restoring the priority, but doesn't do anything with cgroups so we
463         // need to take care of that here in userspace.  Note that we do make
464         // sure to go in the foreground after executing a transaction, but
465         // there are other callbacks into user code that could have changed
466         // our group so we want to make absolutely sure it is put back.
467         androidSetThreadSchedulingGroup(mMyThreadId, ANDROID_TGROUP_DEFAULT);
468 
469         // Let this thread exit the thread pool if it is no longer
470         // needed and it is not the main process thread.
471         if(result == TIMED_OUT && !isMain) {
472             break;
473         }
474     } while (result != -ECONNREFUSED && result != -EBADF);
475 
476     LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%p\n",
477         (void*)pthread_self(), getpid(), (void*)result);
478 
479     mOut.writeInt32(BC_EXIT_LOOPER);
480     talkWithDriver(false);
481 }
482 
stopProcess(bool immediate)483 void IPCThreadState::stopProcess(bool immediate)
484 {
485     //LOGI("**** STOPPING PROCESS");
486     flushCommands();
487     int fd = mProcess->mDriverFD;
488     mProcess->mDriverFD = -1;
489     close(fd);
490     //kill(getpid(), SIGKILL);
491 }
492 
transact(int32_t handle,uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)493 status_t IPCThreadState::transact(int32_t handle,
494                                   uint32_t code, const Parcel& data,
495                                   Parcel* reply, uint32_t flags)
496 {
497     status_t err = data.errorCheck();
498 
499     flags |= TF_ACCEPT_FDS;
500 
501     IF_LOG_TRANSACTIONS() {
502         TextOutput::Bundle _b(alog);
503         alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
504             << handle << " / code " << TypeCode(code) << ": "
505             << indent << data << dedent << endl;
506     }
507 
508     if (err == NO_ERROR) {
509         LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
510             (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
511         err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);
512     }
513 
514     if (err != NO_ERROR) {
515         if (reply) reply->setError(err);
516         return (mLastError = err);
517     }
518 
519     if ((flags & TF_ONE_WAY) == 0) {
520         #if 0
521         if (code == 4) { // relayout
522             LOGI(">>>>>> CALLING transaction 4");
523         } else {
524             LOGI(">>>>>> CALLING transaction %d", code);
525         }
526         #endif
527         if (reply) {
528             err = waitForResponse(reply);
529         } else {
530             Parcel fakeReply;
531             err = waitForResponse(&fakeReply);
532         }
533         #if 0
534         if (code == 4) { // relayout
535             LOGI("<<<<<< RETURNING transaction 4");
536         } else {
537             LOGI("<<<<<< RETURNING transaction %d", code);
538         }
539         #endif
540 
541         IF_LOG_TRANSACTIONS() {
542             TextOutput::Bundle _b(alog);
543             alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
544                 << handle << ": ";
545             if (reply) alog << indent << *reply << dedent << endl;
546             else alog << "(none requested)" << endl;
547         }
548     } else {
549         err = waitForResponse(NULL, NULL);
550     }
551 
552     return err;
553 }
554 
incStrongHandle(int32_t handle)555 void IPCThreadState::incStrongHandle(int32_t handle)
556 {
557     LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
558     mOut.writeInt32(BC_ACQUIRE);
559     mOut.writeInt32(handle);
560 }
561 
decStrongHandle(int32_t handle)562 void IPCThreadState::decStrongHandle(int32_t handle)
563 {
564     LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
565     mOut.writeInt32(BC_RELEASE);
566     mOut.writeInt32(handle);
567 }
568 
incWeakHandle(int32_t handle)569 void IPCThreadState::incWeakHandle(int32_t handle)
570 {
571     LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
572     mOut.writeInt32(BC_INCREFS);
573     mOut.writeInt32(handle);
574 }
575 
decWeakHandle(int32_t handle)576 void IPCThreadState::decWeakHandle(int32_t handle)
577 {
578     LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
579     mOut.writeInt32(BC_DECREFS);
580     mOut.writeInt32(handle);
581 }
582 
attemptIncStrongHandle(int32_t handle)583 status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
584 {
585     mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
586     mOut.writeInt32(0); // xxx was thread priority
587     mOut.writeInt32(handle);
588     status_t result = UNKNOWN_ERROR;
589 
590     waitForResponse(NULL, &result);
591 
592 #if LOG_REFCOUNTS
593     printf("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
594         handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
595 #endif
596 
597     return result;
598 }
599 
expungeHandle(int32_t handle,IBinder * binder)600 void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
601 {
602 #if LOG_REFCOUNTS
603     printf("IPCThreadState::expungeHandle(%ld)\n", handle);
604 #endif
605     self()->mProcess->expungeHandle(handle, binder);
606 }
607 
requestDeathNotification(int32_t handle,BpBinder * proxy)608 status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
609 {
610     mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
611     mOut.writeInt32((int32_t)handle);
612     mOut.writeInt32((int32_t)proxy);
613     return NO_ERROR;
614 }
615 
clearDeathNotification(int32_t handle,BpBinder * proxy)616 status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
617 {
618     mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
619     mOut.writeInt32((int32_t)handle);
620     mOut.writeInt32((int32_t)proxy);
621     return NO_ERROR;
622 }
623 
IPCThreadState()624 IPCThreadState::IPCThreadState()
625     : mProcess(ProcessState::self()),
626       mMyThreadId(androidGetTid()),
627       mStrictModePolicy(0),
628       mLastTransactionBinderFlags(0)
629 {
630     pthread_setspecific(gTLS, this);
631     clearCaller();
632     mIn.setDataCapacity(256);
633     mOut.setDataCapacity(256);
634 }
635 
~IPCThreadState()636 IPCThreadState::~IPCThreadState()
637 {
638 }
639 
sendReply(const Parcel & reply,uint32_t flags)640 status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
641 {
642     status_t err;
643     status_t statusBuffer;
644     err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
645     if (err < NO_ERROR) return err;
646 
647     return waitForResponse(NULL, NULL);
648 }
649 
waitForResponse(Parcel * reply,status_t * acquireResult)650 status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
651 {
652     int32_t cmd;
653     int32_t err;
654 
655     while (1) {
656         if ((err=talkWithDriver()) < NO_ERROR) break;
657         err = mIn.errorCheck();
658         if (err < NO_ERROR) break;
659         if (mIn.dataAvail() == 0) continue;
660 
661         cmd = mIn.readInt32();
662 
663         IF_LOG_COMMANDS() {
664             alog << "Processing waitForResponse Command: "
665                 << getReturnString(cmd) << endl;
666         }
667 
668         switch (cmd) {
669         case BR_TRANSACTION_COMPLETE:
670             if (!reply && !acquireResult) goto finish;
671             break;
672 
673         case BR_DEAD_REPLY:
674             err = DEAD_OBJECT;
675             goto finish;
676 
677         case BR_FAILED_REPLY:
678             err = FAILED_TRANSACTION;
679             goto finish;
680 
681         case BR_ACQUIRE_RESULT:
682             {
683                 LOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
684                 const int32_t result = mIn.readInt32();
685                 if (!acquireResult) continue;
686                 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
687             }
688             goto finish;
689 
690         case BR_REPLY:
691             {
692                 binder_transaction_data tr;
693                 err = mIn.read(&tr, sizeof(tr));
694                 LOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
695                 if (err != NO_ERROR) goto finish;
696 
697                 if (reply) {
698                     if ((tr.flags & TF_STATUS_CODE) == 0) {
699                         reply->ipcSetDataReference(
700                             reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
701                             tr.data_size,
702                             reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
703                             tr.offsets_size/sizeof(size_t),
704                             freeBuffer, this);
705                     } else {
706                         err = *static_cast<const status_t*>(tr.data.ptr.buffer);
707                         freeBuffer(NULL,
708                             reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
709                             tr.data_size,
710                             reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
711                             tr.offsets_size/sizeof(size_t), this);
712                     }
713                 } else {
714                     freeBuffer(NULL,
715                         reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
716                         tr.data_size,
717                         reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
718                         tr.offsets_size/sizeof(size_t), this);
719                     continue;
720                 }
721             }
722             goto finish;
723 
724         default:
725             err = executeCommand(cmd);
726             if (err != NO_ERROR) goto finish;
727             break;
728         }
729     }
730 
731 finish:
732     if (err != NO_ERROR) {
733         if (acquireResult) *acquireResult = err;
734         if (reply) reply->setError(err);
735         mLastError = err;
736     }
737 
738     return err;
739 }
740 
talkWithDriver(bool doReceive)741 status_t IPCThreadState::talkWithDriver(bool doReceive)
742 {
743     LOG_ASSERT(mProcess->mDriverFD >= 0, "Binder driver is not opened");
744 
745     binder_write_read bwr;
746 
747     // Is the read buffer empty?
748     const bool needRead = mIn.dataPosition() >= mIn.dataSize();
749 
750     // We don't want to write anything if we are still reading
751     // from data left in the input buffer and the caller
752     // has requested to read the next data.
753     const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
754 
755     bwr.write_size = outAvail;
756     bwr.write_buffer = (long unsigned int)mOut.data();
757 
758     // This is what we'll read.
759     if (doReceive && needRead) {
760         bwr.read_size = mIn.dataCapacity();
761         bwr.read_buffer = (long unsigned int)mIn.data();
762     } else {
763         bwr.read_size = 0;
764     }
765 
766     IF_LOG_COMMANDS() {
767         TextOutput::Bundle _b(alog);
768         if (outAvail != 0) {
769             alog << "Sending commands to driver: " << indent;
770             const void* cmds = (const void*)bwr.write_buffer;
771             const void* end = ((const uint8_t*)cmds)+bwr.write_size;
772             alog << HexDump(cmds, bwr.write_size) << endl;
773             while (cmds < end) cmds = printCommand(alog, cmds);
774             alog << dedent;
775         }
776         alog << "Size of receive buffer: " << bwr.read_size
777             << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
778     }
779 
780     // Return immediately if there is nothing to do.
781     if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
782 
783     bwr.write_consumed = 0;
784     bwr.read_consumed = 0;
785     status_t err;
786     do {
787         IF_LOG_COMMANDS() {
788             alog << "About to read/write, write size = " << mOut.dataSize() << endl;
789         }
790 #if defined(HAVE_ANDROID_OS)
791         if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
792             err = NO_ERROR;
793         else
794             err = -errno;
795 #else
796         err = INVALID_OPERATION;
797 #endif
798         IF_LOG_COMMANDS() {
799             alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
800         }
801     } while (err == -EINTR);
802 
803     IF_LOG_COMMANDS() {
804         alog << "Our err: " << (void*)err << ", write consumed: "
805             << bwr.write_consumed << " (of " << mOut.dataSize()
806 			<< "), read consumed: " << bwr.read_consumed << endl;
807     }
808 
809     if (err >= NO_ERROR) {
810         if (bwr.write_consumed > 0) {
811             if (bwr.write_consumed < (ssize_t)mOut.dataSize())
812                 mOut.remove(0, bwr.write_consumed);
813             else
814                 mOut.setDataSize(0);
815         }
816         if (bwr.read_consumed > 0) {
817             mIn.setDataSize(bwr.read_consumed);
818             mIn.setDataPosition(0);
819         }
820         IF_LOG_COMMANDS() {
821             TextOutput::Bundle _b(alog);
822             alog << "Remaining data size: " << mOut.dataSize() << endl;
823             alog << "Received commands from driver: " << indent;
824             const void* cmds = mIn.data();
825             const void* end = mIn.data() + mIn.dataSize();
826             alog << HexDump(cmds, mIn.dataSize()) << endl;
827             while (cmds < end) cmds = printReturnCommand(alog, cmds);
828             alog << dedent;
829         }
830         return NO_ERROR;
831     }
832 
833     return err;
834 }
835 
writeTransactionData(int32_t cmd,uint32_t binderFlags,int32_t handle,uint32_t code,const Parcel & data,status_t * statusBuffer)836 status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
837     int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
838 {
839     binder_transaction_data tr;
840 
841     tr.target.handle = handle;
842     tr.code = code;
843     tr.flags = binderFlags;
844 
845     const status_t err = data.errorCheck();
846     if (err == NO_ERROR) {
847         tr.data_size = data.ipcDataSize();
848         tr.data.ptr.buffer = data.ipcData();
849         tr.offsets_size = data.ipcObjectsCount()*sizeof(size_t);
850         tr.data.ptr.offsets = data.ipcObjects();
851     } else if (statusBuffer) {
852         tr.flags |= TF_STATUS_CODE;
853         *statusBuffer = err;
854         tr.data_size = sizeof(status_t);
855         tr.data.ptr.buffer = statusBuffer;
856         tr.offsets_size = 0;
857         tr.data.ptr.offsets = NULL;
858     } else {
859         return (mLastError = err);
860     }
861 
862     mOut.writeInt32(cmd);
863     mOut.write(&tr, sizeof(tr));
864 
865     return NO_ERROR;
866 }
867 
868 sp<BBinder> the_context_object;
869 
setTheContextObject(sp<BBinder> obj)870 void setTheContextObject(sp<BBinder> obj)
871 {
872     the_context_object = obj;
873 }
874 
executeCommand(int32_t cmd)875 status_t IPCThreadState::executeCommand(int32_t cmd)
876 {
877     BBinder* obj;
878     RefBase::weakref_type* refs;
879     status_t result = NO_ERROR;
880 
881     switch (cmd) {
882     case BR_ERROR:
883         result = mIn.readInt32();
884         break;
885 
886     case BR_OK:
887         break;
888 
889     case BR_ACQUIRE:
890         refs = (RefBase::weakref_type*)mIn.readInt32();
891         obj = (BBinder*)mIn.readInt32();
892         LOG_ASSERT(refs->refBase() == obj,
893                    "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
894                    refs, obj, refs->refBase());
895         obj->incStrong(mProcess.get());
896         IF_LOG_REMOTEREFS() {
897             LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
898             obj->printRefs();
899         }
900         mOut.writeInt32(BC_ACQUIRE_DONE);
901         mOut.writeInt32((int32_t)refs);
902         mOut.writeInt32((int32_t)obj);
903         break;
904 
905     case BR_RELEASE:
906         refs = (RefBase::weakref_type*)mIn.readInt32();
907         obj = (BBinder*)mIn.readInt32();
908         LOG_ASSERT(refs->refBase() == obj,
909                    "BR_RELEASE: object %p does not match cookie %p (expected %p)",
910                    refs, obj, refs->refBase());
911         IF_LOG_REMOTEREFS() {
912             LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
913             obj->printRefs();
914         }
915         mPendingStrongDerefs.push(obj);
916         break;
917 
918     case BR_INCREFS:
919         refs = (RefBase::weakref_type*)mIn.readInt32();
920         obj = (BBinder*)mIn.readInt32();
921         refs->incWeak(mProcess.get());
922         mOut.writeInt32(BC_INCREFS_DONE);
923         mOut.writeInt32((int32_t)refs);
924         mOut.writeInt32((int32_t)obj);
925         break;
926 
927     case BR_DECREFS:
928         refs = (RefBase::weakref_type*)mIn.readInt32();
929         obj = (BBinder*)mIn.readInt32();
930         // NOTE: This assertion is not valid, because the object may no
931         // longer exist (thus the (BBinder*)cast above resulting in a different
932         // memory address).
933         //LOG_ASSERT(refs->refBase() == obj,
934         //           "BR_DECREFS: object %p does not match cookie %p (expected %p)",
935         //           refs, obj, refs->refBase());
936         mPendingWeakDerefs.push(refs);
937         break;
938 
939     case BR_ATTEMPT_ACQUIRE:
940         refs = (RefBase::weakref_type*)mIn.readInt32();
941         obj = (BBinder*)mIn.readInt32();
942 
943         {
944             const bool success = refs->attemptIncStrong(mProcess.get());
945             LOG_ASSERT(success && refs->refBase() == obj,
946                        "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
947                        refs, obj, refs->refBase());
948 
949             mOut.writeInt32(BC_ACQUIRE_RESULT);
950             mOut.writeInt32((int32_t)success);
951         }
952         break;
953 
954     case BR_TRANSACTION:
955         {
956             binder_transaction_data tr;
957             result = mIn.read(&tr, sizeof(tr));
958             LOG_ASSERT(result == NO_ERROR,
959                 "Not enough command data for brTRANSACTION");
960             if (result != NO_ERROR) break;
961 
962             Parcel buffer;
963             buffer.ipcSetDataReference(
964                 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
965                 tr.data_size,
966                 reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
967                 tr.offsets_size/sizeof(size_t), freeBuffer, this);
968 
969             const pid_t origPid = mCallingPid;
970             const uid_t origUid = mCallingUid;
971 
972             mCallingPid = tr.sender_pid;
973             mCallingUid = tr.sender_euid;
974 
975             int curPrio = getpriority(PRIO_PROCESS, mMyThreadId);
976             if (gDisableBackgroundScheduling) {
977                 if (curPrio > ANDROID_PRIORITY_NORMAL) {
978                     // We have inherited a reduced priority from the caller, but do not
979                     // want to run in that state in this process.  The driver set our
980                     // priority already (though not our scheduling class), so bounce
981                     // it back to the default before invoking the transaction.
982                     setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL);
983                 }
984             } else {
985                 if (curPrio >= ANDROID_PRIORITY_BACKGROUND) {
986                     // We want to use the inherited priority from the caller.
987                     // Ensure this thread is in the background scheduling class,
988                     // since the driver won't modify scheduling classes for us.
989                     // The scheduling group is reset to default by the caller
990                     // once this method returns after the transaction is complete.
991                     androidSetThreadSchedulingGroup(mMyThreadId,
992                                                     ANDROID_TGROUP_BG_NONINTERACT);
993                 }
994             }
995 
996             //LOGI(">>>> TRANSACT from pid %d uid %d\n", mCallingPid, mCallingUid);
997 
998             Parcel reply;
999             IF_LOG_TRANSACTIONS() {
1000                 TextOutput::Bundle _b(alog);
1001                 alog << "BR_TRANSACTION thr " << (void*)pthread_self()
1002                     << " / obj " << tr.target.ptr << " / code "
1003                     << TypeCode(tr.code) << ": " << indent << buffer
1004                     << dedent << endl
1005                     << "Data addr = "
1006                     << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1007                     << ", offsets addr="
1008                     << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
1009             }
1010             if (tr.target.ptr) {
1011                 sp<BBinder> b((BBinder*)tr.cookie);
1012                 const status_t error = b->transact(tr.code, buffer, &reply, tr.flags);
1013                 if (error < NO_ERROR) reply.setError(error);
1014 
1015             } else {
1016                 const status_t error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
1017                 if (error < NO_ERROR) reply.setError(error);
1018             }
1019 
1020             //LOGI("<<<< TRANSACT from pid %d restore pid %d uid %d\n",
1021             //     mCallingPid, origPid, origUid);
1022 
1023             if ((tr.flags & TF_ONE_WAY) == 0) {
1024                 LOG_ONEWAY("Sending reply to %d!", mCallingPid);
1025                 sendReply(reply, 0);
1026             } else {
1027                 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1028             }
1029 
1030             mCallingPid = origPid;
1031             mCallingUid = origUid;
1032 
1033             IF_LOG_TRANSACTIONS() {
1034                 TextOutput::Bundle _b(alog);
1035                 alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
1036                     << tr.target.ptr << ": " << indent << reply << dedent << endl;
1037             }
1038 
1039         }
1040         break;
1041 
1042     case BR_DEAD_BINDER:
1043         {
1044             BpBinder *proxy = (BpBinder*)mIn.readInt32();
1045             proxy->sendObituary();
1046             mOut.writeInt32(BC_DEAD_BINDER_DONE);
1047             mOut.writeInt32((int32_t)proxy);
1048         } break;
1049 
1050     case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1051         {
1052             BpBinder *proxy = (BpBinder*)mIn.readInt32();
1053             proxy->getWeakRefs()->decWeak(proxy);
1054         } break;
1055 
1056     case BR_FINISHED:
1057         result = TIMED_OUT;
1058         break;
1059 
1060     case BR_NOOP:
1061         break;
1062 
1063     case BR_SPAWN_LOOPER:
1064         mProcess->spawnPooledThread(false);
1065         break;
1066 
1067     default:
1068         printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
1069         result = UNKNOWN_ERROR;
1070         break;
1071     }
1072 
1073     if (result != NO_ERROR) {
1074         mLastError = result;
1075     }
1076 
1077     return result;
1078 }
1079 
threadDestructor(void * st)1080 void IPCThreadState::threadDestructor(void *st)
1081 {
1082 	IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1083 	if (self) {
1084 		self->flushCommands();
1085 #if defined(HAVE_ANDROID_OS)
1086         ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1087 #endif
1088 		delete self;
1089 	}
1090 }
1091 
1092 
freeBuffer(Parcel * parcel,const uint8_t * data,size_t dataSize,const size_t * objects,size_t objectsSize,void * cookie)1093 void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data, size_t dataSize,
1094                                 const size_t* objects, size_t objectsSize,
1095                                 void* cookie)
1096 {
1097     //LOGI("Freeing parcel %p", &parcel);
1098     IF_LOG_COMMANDS() {
1099         alog << "Writing BC_FREE_BUFFER for " << data << endl;
1100     }
1101     LOG_ASSERT(data != NULL, "Called with NULL data");
1102     if (parcel != NULL) parcel->closeFileDescriptors();
1103     IPCThreadState* state = self();
1104     state->mOut.writeInt32(BC_FREE_BUFFER);
1105     state->mOut.writeInt32((int32_t)data);
1106 }
1107 
1108 }; // namespace android
1109