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