• 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 "hw-IPCThreadState"
18 
19 #include <hwbinder/IPCThreadState.h>
20 
21 #include <hwbinder/Binder.h>
22 #include <hwbinder/BpHwBinder.h>
23 #include <hwbinder/TextOutput.h>
24 #include <hwbinder/binder_kernel.h>
25 
26 #include <utils/Log.h>
27 #include <utils/SystemClock.h>
28 #include <utils/threads.h>
29 
30 #include <private/binder/binder_module.h>
31 #include <hwbinder/Static.h>
32 
33 #include <errno.h>
34 #include <inttypes.h>
35 #include <pthread.h>
36 #include <sched.h>
37 #include <signal.h>
38 #include <stdio.h>
39 #include <sys/ioctl.h>
40 #include <sys/resource.h>
41 #include <unistd.h>
42 
43 #if LOG_NDEBUG
44 
45 #define IF_LOG_TRANSACTIONS() if (false)
46 #define IF_LOG_COMMANDS() if (false)
47 #define LOG_REMOTEREFS(...)
48 #define IF_LOG_REMOTEREFS() if (false)
49 #define LOG_THREADPOOL(...)
50 #define LOG_ONEWAY(...)
51 
52 #else
53 
54 #define IF_LOG_TRANSACTIONS() IF_ALOG(LOG_VERBOSE, "transact")
55 #define IF_LOG_COMMANDS() IF_ALOG(LOG_VERBOSE, "ipc")
56 #define LOG_REMOTEREFS(...) ALOG(LOG_DEBUG, "remoterefs", __VA_ARGS__)
57 #define IF_LOG_REMOTEREFS() IF_ALOG(LOG_DEBUG, "remoterefs")
58 #define LOG_THREADPOOL(...) ALOG(LOG_DEBUG, "threadpool", __VA_ARGS__)
59 #define LOG_ONEWAY(...) ALOG(LOG_DEBUG, "ipc", __VA_ARGS__)
60 
61 #endif
62 
63 // ---------------------------------------------------------------------------
64 
65 namespace android {
66 namespace hardware {
67 
68 // Static const and functions will be optimized out if not used,
69 // when LOG_NDEBUG and references in IF_LOG_COMMANDS() are optimized out.
70 static const char *kReturnStrings[] = {
71     "BR_ERROR",
72     "BR_OK",
73     "BR_TRANSACTION",
74     "BR_REPLY",
75     "BR_ACQUIRE_RESULT",
76     "BR_DEAD_REPLY",
77     "BR_TRANSACTION_COMPLETE",
78     "BR_INCREFS",
79     "BR_ACQUIRE",
80     "BR_RELEASE",
81     "BR_DECREFS",
82     "BR_ATTEMPT_ACQUIRE",
83     "BR_NOOP",
84     "BR_SPAWN_LOOPER",
85     "BR_FINISHED",
86     "BR_DEAD_BINDER",
87     "BR_CLEAR_DEATH_NOTIFICATION_DONE",
88     "BR_FAILED_REPLY",
89     "BR_TRANSACTION_SEC_CTX",
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) {
291         ALOGW("Calling IPCThreadState::self() during shutdown is dangerous, expect a crash.\n");
292         return NULL;
293     }
294 
295     pthread_mutex_lock(&gTLSMutex);
296     if (!gHaveTLS) {
297         int key_create_value = pthread_key_create(&gTLS, threadDestructor);
298         if (key_create_value != 0) {
299             pthread_mutex_unlock(&gTLSMutex);
300             ALOGW("IPCThreadState::self() unable to create TLS key, expect a crash: %s\n",
301                     strerror(key_create_value));
302             return NULL;
303         }
304         gHaveTLS = true;
305     }
306     pthread_mutex_unlock(&gTLSMutex);
307     goto restart;
308 }
309 
selfOrNull()310 IPCThreadState* IPCThreadState::selfOrNull()
311 {
312     if (gHaveTLS) {
313         const pthread_key_t k = gTLS;
314         IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
315         return st;
316     }
317     return NULL;
318 }
319 
shutdown()320 void IPCThreadState::shutdown()
321 {
322     gShutdown = true;
323 
324     if (gHaveTLS) {
325         // XXX Need to wait for all thread pool threads to exit!
326         IPCThreadState* st = (IPCThreadState*)pthread_getspecific(gTLS);
327         if (st) {
328             delete st;
329             pthread_setspecific(gTLS, NULL);
330         }
331         pthread_key_delete(gTLS);
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() const353 pid_t IPCThreadState::getCallingPid() const
354 {
355     return mCallingPid;
356 }
357 
getCallingSid() const358 const char* IPCThreadState::getCallingSid() const
359 {
360     return mCallingSid;
361 }
362 
getCallingUid() const363 uid_t IPCThreadState::getCallingUid() const
364 {
365     return mCallingUid;
366 }
367 
clearCallingIdentity()368 int64_t IPCThreadState::clearCallingIdentity()
369 {
370     // ignore mCallingSid for legacy reasons
371     int64_t token = ((int64_t)mCallingUid<<32) | mCallingPid;
372     clearCaller();
373     return token;
374 }
375 
setStrictModePolicy(int32_t policy)376 void IPCThreadState::setStrictModePolicy(int32_t policy)
377 {
378     mStrictModePolicy = policy;
379 }
380 
getStrictModePolicy() const381 int32_t IPCThreadState::getStrictModePolicy() const
382 {
383     return mStrictModePolicy;
384 }
385 
setLastTransactionBinderFlags(int32_t flags)386 void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
387 {
388     mLastTransactionBinderFlags = flags;
389 }
390 
getLastTransactionBinderFlags() const391 int32_t IPCThreadState::getLastTransactionBinderFlags() const
392 {
393     return mLastTransactionBinderFlags;
394 }
395 
restoreCallingIdentity(int64_t token)396 void IPCThreadState::restoreCallingIdentity(int64_t token)
397 {
398     mCallingUid = (int)(token>>32);
399     mCallingSid = nullptr;  // not enough data to restore
400     mCallingPid = (int)token;
401 }
402 
clearCaller()403 void IPCThreadState::clearCaller()
404 {
405     mCallingPid = getpid();
406     mCallingSid = nullptr;  // expensive to lookup
407     mCallingUid = getuid();
408 }
409 
flushCommands()410 void IPCThreadState::flushCommands()
411 {
412     if (mProcess->mDriverFD <= 0)
413         return;
414     talkWithDriver(false);
415 }
416 
blockUntilThreadAvailable()417 void IPCThreadState::blockUntilThreadAvailable()
418 {
419     pthread_mutex_lock(&mProcess->mThreadCountLock);
420     while (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads) {
421         ALOGW("Waiting for thread to be free. mExecutingThreadsCount=%lu mMaxThreads=%lu\n",
422                 static_cast<unsigned long>(mProcess->mExecutingThreadsCount),
423                 static_cast<unsigned long>(mProcess->mMaxThreads));
424         pthread_cond_wait(&mProcess->mThreadCountDecrement, &mProcess->mThreadCountLock);
425     }
426     pthread_mutex_unlock(&mProcess->mThreadCountLock);
427 }
428 
getAndExecuteCommand()429 status_t IPCThreadState::getAndExecuteCommand()
430 {
431     status_t result;
432     int32_t cmd;
433 
434     result = talkWithDriver();
435     if (result >= NO_ERROR) {
436         size_t IN = mIn.dataAvail();
437         if (IN < sizeof(int32_t)) return result;
438         cmd = mIn.readInt32();
439         IF_LOG_COMMANDS() {
440             alog << "Processing top-level Command: "
441                  << getReturnString(cmd) << endl;
442         }
443 
444         pthread_mutex_lock(&mProcess->mThreadCountLock);
445         mProcess->mExecutingThreadsCount++;
446         if (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads &&
447             mProcess->mMaxThreads > 1 && mProcess->mStarvationStartTimeMs == 0) {
448             mProcess->mStarvationStartTimeMs = uptimeMillis();
449         }
450         pthread_mutex_unlock(&mProcess->mThreadCountLock);
451 
452         result = executeCommand(cmd);
453 
454         pthread_mutex_lock(&mProcess->mThreadCountLock);
455         mProcess->mExecutingThreadsCount--;
456         if (mProcess->mExecutingThreadsCount < mProcess->mMaxThreads && mProcess->mMaxThreads > 1 &&
457             mProcess->mStarvationStartTimeMs != 0) {
458             int64_t starvationTimeMs = uptimeMillis() - mProcess->mStarvationStartTimeMs;
459             if (starvationTimeMs > 100) {
460                 ALOGW("All binder threads in pool (%zu threads) busy for %" PRId64 " ms",
461                       mProcess->mMaxThreads, starvationTimeMs);
462             }
463             mProcess->mStarvationStartTimeMs = 0;
464         }
465         pthread_cond_broadcast(&mProcess->mThreadCountDecrement);
466         pthread_mutex_unlock(&mProcess->mThreadCountLock);
467     }
468 
469     return result;
470 }
471 
472 // When we've cleared the incoming command queue, process any pending derefs
processPendingDerefs()473 void IPCThreadState::processPendingDerefs()
474 {
475     if (mIn.dataPosition() >= mIn.dataSize()) {
476         size_t numPending = mPendingWeakDerefs.size();
477         if (numPending > 0) {
478             for (size_t i = 0; i < numPending; i++) {
479                 RefBase::weakref_type* refs = mPendingWeakDerefs[i];
480                 refs->decWeak(mProcess.get());
481             }
482             mPendingWeakDerefs.clear();
483         }
484 
485         numPending = mPendingStrongDerefs.size();
486         if (numPending > 0) {
487             for (size_t i = 0; i < numPending; i++) {
488                 BHwBinder* obj = mPendingStrongDerefs[i];
489                 obj->decStrong(mProcess.get());
490             }
491             mPendingStrongDerefs.clear();
492         }
493     }
494 }
495 
joinThreadPool(bool isMain)496 void IPCThreadState::joinThreadPool(bool isMain)
497 {
498     LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
499 
500     mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
501 
502     status_t result;
503     do {
504         processPendingDerefs();
505         // now get the next command to be processed, waiting if necessary
506         result = getAndExecuteCommand();
507 
508         if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
509             ALOGE("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
510                   mProcess->mDriverFD, result);
511             abort();
512         }
513 
514         // Let this thread exit the thread pool if it is no longer
515         // needed and it is not the main process thread.
516         if(result == TIMED_OUT && !isMain) {
517             break;
518         }
519     } while (result != -ECONNREFUSED && result != -EBADF);
520 
521     LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%d\n",
522         (void*)pthread_self(), getpid(), result);
523 
524     mOut.writeInt32(BC_EXIT_LOOPER);
525     talkWithDriver(false);
526 }
527 
setupPolling(int * fd)528 int IPCThreadState::setupPolling(int* fd)
529 {
530     if (mProcess->mDriverFD <= 0) {
531         return -EBADF;
532     }
533 
534     mOut.writeInt32(BC_ENTER_LOOPER);
535     *fd = mProcess->mDriverFD;
536     return 0;
537 }
538 
handlePolledCommands()539 status_t IPCThreadState::handlePolledCommands()
540 {
541     status_t result;
542 
543     do {
544         result = getAndExecuteCommand();
545     } while (mIn.dataPosition() < mIn.dataSize());
546 
547     processPendingDerefs();
548     flushCommands();
549     return result;
550 }
551 
stopProcess(bool)552 void IPCThreadState::stopProcess(bool /*immediate*/)
553 {
554     //ALOGI("**** STOPPING PROCESS");
555     flushCommands();
556     int fd = mProcess->mDriverFD;
557     mProcess->mDriverFD = -1;
558     close(fd);
559     //kill(getpid(), SIGKILL);
560 }
561 
transact(int32_t handle,uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)562 status_t IPCThreadState::transact(int32_t handle,
563                                   uint32_t code, const Parcel& data,
564                                   Parcel* reply, uint32_t flags)
565 {
566     status_t err = data.errorCheck();
567 
568     flags |= TF_ACCEPT_FDS;
569 
570     IF_LOG_TRANSACTIONS() {
571         alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
572             << handle << " / code " << TypeCode(code) << ": "
573             << indent << data << dedent << endl;
574     }
575 
576     if (err == NO_ERROR) {
577         LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
578             (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
579         err = writeTransactionData(BC_TRANSACTION_SG, flags, handle, code, data, NULL);
580     }
581 
582     if (err != NO_ERROR) {
583         if (reply) reply->setError(err);
584         return (mLastError = err);
585     }
586 
587     if ((flags & TF_ONE_WAY) == 0) {
588         #if 0
589         if (code == 4) { // relayout
590             ALOGI(">>>>>> CALLING transaction 4");
591         } else {
592             ALOGI(">>>>>> CALLING transaction %d", code);
593         }
594         #endif
595         if (reply) {
596             err = waitForResponse(reply);
597         } else {
598             Parcel fakeReply;
599             err = waitForResponse(&fakeReply);
600         }
601         #if 0
602         if (code == 4) { // relayout
603             ALOGI("<<<<<< RETURNING transaction 4");
604         } else {
605             ALOGI("<<<<<< RETURNING transaction %d", code);
606         }
607         #endif
608 
609         IF_LOG_TRANSACTIONS() {
610             alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
611                 << handle << ": ";
612             if (reply) alog << indent << *reply << dedent << endl;
613             else alog << "(none requested)" << endl;
614         }
615     } else {
616         err = waitForResponse(NULL, NULL);
617     }
618 
619     return err;
620 }
621 
incStrongHandle(int32_t handle)622 void IPCThreadState::incStrongHandle(int32_t handle)
623 {
624     LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
625     mOut.writeInt32(BC_ACQUIRE);
626     mOut.writeInt32(handle);
627 }
628 
decStrongHandle(int32_t handle)629 void IPCThreadState::decStrongHandle(int32_t handle)
630 {
631     LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
632     mOut.writeInt32(BC_RELEASE);
633     mOut.writeInt32(handle);
634 }
635 
incWeakHandle(int32_t handle)636 void IPCThreadState::incWeakHandle(int32_t handle)
637 {
638     LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
639     mOut.writeInt32(BC_INCREFS);
640     mOut.writeInt32(handle);
641 }
642 
decWeakHandle(int32_t handle)643 void IPCThreadState::decWeakHandle(int32_t handle)
644 {
645     LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
646     mOut.writeInt32(BC_DECREFS);
647     mOut.writeInt32(handle);
648 }
649 
attemptIncStrongHandle(int32_t handle)650 status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
651 {
652 #if HAS_BC_ATTEMPT_ACQUIRE
653     LOG_REMOTEREFS("IPCThreadState::attemptIncStrongHandle(%d)\n", handle);
654     mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
655     mOut.writeInt32(0); // xxx was thread priority
656     mOut.writeInt32(handle);
657     status_t result = UNKNOWN_ERROR;
658 
659     waitForResponse(NULL, &result);
660 
661 #if LOG_REFCOUNTS
662     printf("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
663         handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
664 #endif
665 
666     return result;
667 #else
668     (void)handle;
669     ALOGE("%s(%d): Not supported\n", __func__, handle);
670     return INVALID_OPERATION;
671 #endif
672 }
673 
expungeHandle(int32_t handle,IBinder * binder)674 void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
675 {
676 #if LOG_REFCOUNTS
677     printf("IPCThreadState::expungeHandle(%ld)\n", handle);
678 #endif
679     self()->mProcess->expungeHandle(handle, binder);
680 }
681 
requestDeathNotification(int32_t handle,BpHwBinder * proxy)682 status_t IPCThreadState::requestDeathNotification(int32_t handle, BpHwBinder* proxy)
683 {
684     mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
685     mOut.writeInt32((int32_t)handle);
686     mOut.writePointer((uintptr_t)proxy);
687     return NO_ERROR;
688 }
689 
clearDeathNotification(int32_t handle,BpHwBinder * proxy)690 status_t IPCThreadState::clearDeathNotification(int32_t handle, BpHwBinder* proxy)
691 {
692     mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
693     mOut.writeInt32((int32_t)handle);
694     mOut.writePointer((uintptr_t)proxy);
695     return NO_ERROR;
696 }
697 
IPCThreadState()698 IPCThreadState::IPCThreadState()
699     : mProcess(ProcessState::self()),
700       mMyThreadId(gettid()),
701       mStrictModePolicy(0),
702       mLastTransactionBinderFlags(0)
703 {
704     pthread_setspecific(gTLS, this);
705     clearCaller();
706     mIn.setDataCapacity(256);
707     mOut.setDataCapacity(256);
708 }
709 
~IPCThreadState()710 IPCThreadState::~IPCThreadState()
711 {
712 }
713 
sendReply(const Parcel & reply,uint32_t flags)714 status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
715 {
716     status_t err;
717     status_t statusBuffer;
718     err = writeTransactionData(BC_REPLY_SG, flags, -1, 0, reply, &statusBuffer);
719     if (err < NO_ERROR) return err;
720 
721     return waitForResponse(NULL, NULL);
722 }
723 
waitForResponse(Parcel * reply,status_t * acquireResult)724 status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
725 {
726     uint32_t cmd;
727     int32_t err;
728 
729     while (1) {
730         if ((err=talkWithDriver()) < NO_ERROR) break;
731         err = mIn.errorCheck();
732         if (err < NO_ERROR) break;
733         if (mIn.dataAvail() == 0) continue;
734 
735         cmd = (uint32_t)mIn.readInt32();
736 
737         IF_LOG_COMMANDS() {
738             alog << "Processing waitForResponse Command: "
739                 << getReturnString(cmd) << endl;
740         }
741 
742         switch (cmd) {
743         case BR_TRANSACTION_COMPLETE:
744             if (!reply && !acquireResult) goto finish;
745             break;
746 
747         case BR_DEAD_REPLY:
748             err = DEAD_OBJECT;
749             goto finish;
750 
751         case BR_FAILED_REPLY:
752             err = FAILED_TRANSACTION;
753             goto finish;
754 
755         case BR_ACQUIRE_RESULT:
756             {
757                 ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
758                 const int32_t result = mIn.readInt32();
759                 if (!acquireResult) continue;
760                 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
761             }
762             goto finish;
763 
764         case BR_REPLY:
765             {
766                 binder_transaction_data tr;
767                 err = mIn.read(&tr, sizeof(tr));
768                 ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
769                 if (err != NO_ERROR) goto finish;
770 
771                 if (reply) {
772                     if ((tr.flags & TF_STATUS_CODE) == 0) {
773                         reply->ipcSetDataReference(
774                             reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
775                             tr.data_size,
776                             reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
777                             tr.offsets_size/sizeof(binder_size_t),
778                             freeBuffer, this);
779                     } else {
780                         err = *reinterpret_cast<const status_t*>(tr.data.ptr.buffer);
781                         freeBuffer(NULL,
782                             reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
783                             tr.data_size,
784                             reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
785                             tr.offsets_size/sizeof(binder_size_t), this);
786                     }
787                 } else {
788                     freeBuffer(NULL,
789                         reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
790                         tr.data_size,
791                         reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
792                         tr.offsets_size/sizeof(binder_size_t), this);
793                     continue;
794                 }
795             }
796             goto finish;
797 
798         default:
799             err = executeCommand(cmd);
800             if (err != NO_ERROR) goto finish;
801             break;
802         }
803     }
804 
805 finish:
806     if (err != NO_ERROR) {
807         if (acquireResult) *acquireResult = err;
808         if (reply) reply->setError(err);
809         mLastError = err;
810     }
811 
812     return err;
813 }
814 
talkWithDriver(bool doReceive)815 status_t IPCThreadState::talkWithDriver(bool doReceive)
816 {
817     if (mProcess->mDriverFD <= 0) {
818         return -EBADF;
819     }
820 
821     binder_write_read bwr;
822 
823     // Is the read buffer empty?
824     const bool needRead = mIn.dataPosition() >= mIn.dataSize();
825 
826     // We don't want to write anything if we are still reading
827     // from data left in the input buffer and the caller
828     // has requested to read the next data.
829     const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
830 
831     bwr.write_size = outAvail;
832     bwr.write_buffer = (uintptr_t)mOut.data();
833 
834     // This is what we'll read.
835     if (doReceive && needRead) {
836         bwr.read_size = mIn.dataCapacity();
837         bwr.read_buffer = (uintptr_t)mIn.data();
838     } else {
839         bwr.read_size = 0;
840         bwr.read_buffer = 0;
841     }
842 
843     IF_LOG_COMMANDS() {
844         if (outAvail != 0) {
845             alog << "Sending commands to driver: " << indent;
846             const void* cmds = (const void*)bwr.write_buffer;
847             const void* end = ((const uint8_t*)cmds)+bwr.write_size;
848             alog << HexDump(cmds, bwr.write_size) << endl;
849             while (cmds < end) cmds = printCommand(alog, cmds);
850             alog << dedent;
851         }
852         alog << "Size of receive buffer: " << bwr.read_size
853             << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
854     }
855 
856     // Return immediately if there is nothing to do.
857     if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
858 
859     bwr.write_consumed = 0;
860     bwr.read_consumed = 0;
861     status_t err;
862     do {
863         IF_LOG_COMMANDS() {
864             alog << "About to read/write, write size = " << mOut.dataSize() << endl;
865         }
866 #if defined(__ANDROID__)
867         if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
868             err = NO_ERROR;
869         else
870             err = -errno;
871 #else
872         err = INVALID_OPERATION;
873 #endif
874         if (mProcess->mDriverFD <= 0) {
875             err = -EBADF;
876         }
877         IF_LOG_COMMANDS() {
878             alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
879         }
880     } while (err == -EINTR);
881 
882     IF_LOG_COMMANDS() {
883         alog << "Our err: " << (void*)(intptr_t)err << ", write consumed: "
884             << bwr.write_consumed << " (of " << mOut.dataSize()
885                         << "), read consumed: " << bwr.read_consumed << endl;
886     }
887 
888     if (err >= NO_ERROR) {
889         if (bwr.write_consumed > 0) {
890             if (bwr.write_consumed < mOut.dataSize())
891                 mOut.remove(0, bwr.write_consumed);
892             else
893                 mOut.setDataSize(0);
894         }
895         if (bwr.read_consumed > 0) {
896             mIn.setDataSize(bwr.read_consumed);
897             mIn.setDataPosition(0);
898         }
899         IF_LOG_COMMANDS() {
900             alog << "Remaining data size: " << mOut.dataSize() << endl;
901             alog << "Received commands from driver: " << indent;
902             const void* cmds = mIn.data();
903             const void* end = mIn.data() + mIn.dataSize();
904             alog << HexDump(cmds, mIn.dataSize()) << endl;
905             while (cmds < end) cmds = printReturnCommand(alog, cmds);
906             alog << dedent;
907         }
908         return NO_ERROR;
909     }
910 
911     return err;
912 }
913 
writeTransactionData(int32_t cmd,uint32_t binderFlags,int32_t handle,uint32_t code,const Parcel & data,status_t * statusBuffer)914 status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
915     int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
916 {
917     binder_transaction_data_sg tr_sg;
918     tr_sg.tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
919     tr_sg.tr.target.handle = handle;
920     tr_sg.tr.code = code;
921     tr_sg.tr.flags = binderFlags;
922     tr_sg.tr.cookie = 0;
923     tr_sg.tr.sender_pid = 0;
924     tr_sg.tr.sender_euid = 0;
925 
926     const status_t err = data.errorCheck();
927     if (err == NO_ERROR) {
928         tr_sg.tr.data_size = data.ipcDataSize();
929         tr_sg.tr.data.ptr.buffer = data.ipcData();
930         tr_sg.tr.offsets_size = data.ipcObjectsCount()*sizeof(binder_size_t);
931         tr_sg.tr.data.ptr.offsets = data.ipcObjects();
932         tr_sg.buffers_size = data.ipcBufferSize();
933     } else if (statusBuffer) {
934         tr_sg.tr.flags |= TF_STATUS_CODE;
935         *statusBuffer = err;
936         tr_sg.tr.data_size = sizeof(status_t);
937         tr_sg.tr.data.ptr.buffer = reinterpret_cast<uintptr_t>(statusBuffer);
938         tr_sg.tr.offsets_size = 0;
939         tr_sg.tr.data.ptr.offsets = 0;
940         tr_sg.buffers_size = 0;
941     } else {
942         return (mLastError = err);
943     }
944 
945     mOut.writeInt32(cmd);
946     mOut.write(&tr_sg, sizeof(tr_sg));
947 
948     return NO_ERROR;
949 }
950 
setTheContextObject(sp<BHwBinder> obj)951 void IPCThreadState::setTheContextObject(sp<BHwBinder> obj)
952 {
953     mContextObject = obj;
954 }
955 
executeCommand(int32_t cmd)956 status_t IPCThreadState::executeCommand(int32_t cmd)
957 {
958     BHwBinder* obj;
959     RefBase::weakref_type* refs;
960     status_t result = NO_ERROR;
961     switch ((uint32_t)cmd) {
962     case BR_ERROR:
963         result = mIn.readInt32();
964         break;
965 
966     case BR_OK:
967         break;
968 
969     case BR_ACQUIRE:
970         refs = (RefBase::weakref_type*)mIn.readPointer();
971         obj = (BHwBinder*)mIn.readPointer();
972         ALOG_ASSERT(refs->refBase() == obj,
973                    "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
974                    refs, obj, refs->refBase());
975         obj->incStrong(mProcess.get());
976         IF_LOG_REMOTEREFS() {
977             LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
978             obj->printRefs();
979         }
980         mOut.writeInt32(BC_ACQUIRE_DONE);
981         mOut.writePointer((uintptr_t)refs);
982         mOut.writePointer((uintptr_t)obj);
983         break;
984 
985     case BR_RELEASE:
986         refs = (RefBase::weakref_type*)mIn.readPointer();
987         obj = (BHwBinder*)mIn.readPointer();
988         ALOG_ASSERT(refs->refBase() == obj,
989                    "BR_RELEASE: object %p does not match cookie %p (expected %p)",
990                    refs, obj, refs->refBase());
991         IF_LOG_REMOTEREFS() {
992             LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
993             obj->printRefs();
994         }
995         mPendingStrongDerefs.push(obj);
996         break;
997 
998     case BR_INCREFS:
999         refs = (RefBase::weakref_type*)mIn.readPointer();
1000         obj = (BHwBinder*)mIn.readPointer();
1001         refs->incWeak(mProcess.get());
1002         mOut.writeInt32(BC_INCREFS_DONE);
1003         mOut.writePointer((uintptr_t)refs);
1004         mOut.writePointer((uintptr_t)obj);
1005         break;
1006 
1007     case BR_DECREFS:
1008         refs = (RefBase::weakref_type*)mIn.readPointer();
1009         obj = (BHwBinder*)mIn.readPointer();
1010         // NOTE: This assertion is not valid, because the object may no
1011         // longer exist (thus the (BHwBinder*)cast above resulting in a different
1012         // memory address).
1013         //ALOG_ASSERT(refs->refBase() == obj,
1014         //           "BR_DECREFS: object %p does not match cookie %p (expected %p)",
1015         //           refs, obj, refs->refBase());
1016         mPendingWeakDerefs.push(refs);
1017         break;
1018 
1019     case BR_ATTEMPT_ACQUIRE:
1020         refs = (RefBase::weakref_type*)mIn.readPointer();
1021         obj = (BHwBinder*)mIn.readPointer();
1022 
1023         {
1024             const bool success = refs->attemptIncStrong(mProcess.get());
1025             ALOG_ASSERT(success && refs->refBase() == obj,
1026                        "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
1027                        refs, obj, refs->refBase());
1028 
1029             mOut.writeInt32(BC_ACQUIRE_RESULT);
1030             mOut.writeInt32((int32_t)success);
1031         }
1032         break;
1033 
1034     case BR_TRANSACTION_SEC_CTX:
1035     case BR_TRANSACTION:
1036         {
1037             binder_transaction_data_secctx tr_secctx;
1038             binder_transaction_data& tr = tr_secctx.transaction_data;
1039 
1040             if (cmd == (int) BR_TRANSACTION_SEC_CTX) {
1041                 result = mIn.read(&tr_secctx, sizeof(tr_secctx));
1042             } else {
1043                 result = mIn.read(&tr, sizeof(tr));
1044                 tr_secctx.secctx = 0;
1045             }
1046 
1047             ALOG_ASSERT(result == NO_ERROR,
1048                 "Not enough command data for brTRANSACTION");
1049             if (result != NO_ERROR) break;
1050 
1051             Parcel buffer;
1052             buffer.ipcSetDataReference(
1053                 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1054                 tr.data_size,
1055                 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1056                 tr.offsets_size/sizeof(binder_size_t), freeBuffer, this);
1057 
1058             const pid_t origPid = mCallingPid;
1059             const char* origSid = mCallingSid;
1060             const uid_t origUid = mCallingUid;
1061             const int32_t origStrictModePolicy = mStrictModePolicy;
1062             const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
1063 
1064             mCallingPid = tr.sender_pid;
1065             mCallingSid = reinterpret_cast<const char*>(tr_secctx.secctx);
1066             mCallingUid = tr.sender_euid;
1067             mLastTransactionBinderFlags = tr.flags;
1068 
1069             // ALOGI(">>>> TRANSACT from pid %d sid %s uid %d\n", mCallingPid,
1070             //    (mCallingSid ? mCallingSid : "<N/A>"), mCallingUid);
1071 
1072             Parcel reply;
1073             status_t error;
1074             bool reply_sent = false;
1075             IF_LOG_TRANSACTIONS() {
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 
1086             auto reply_callback = [&] (auto &replyParcel) {
1087                 if (reply_sent) {
1088                     // Reply was sent earlier, ignore it.
1089                     ALOGE("Dropping binder reply, it was sent already.");
1090                     return;
1091                 }
1092                 reply_sent = true;
1093                 if ((tr.flags & TF_ONE_WAY) == 0) {
1094                     replyParcel.setError(NO_ERROR);
1095                     sendReply(replyParcel, 0);
1096                 } else {
1097                     ALOGE("Not sending reply in one-way transaction");
1098                 }
1099             };
1100 
1101             if (tr.target.ptr) {
1102                 // We only have a weak reference on the target object, so we must first try to
1103                 // safely acquire a strong reference before doing anything else with it.
1104                 if (reinterpret_cast<RefBase::weakref_type*>(
1105                         tr.target.ptr)->attemptIncStrong(this)) {
1106                     error = reinterpret_cast<BHwBinder*>(tr.cookie)->transact(tr.code, buffer,
1107                             &reply, tr.flags, reply_callback);
1108                     reinterpret_cast<BHwBinder*>(tr.cookie)->decStrong(this);
1109                 } else {
1110                     error = UNKNOWN_TRANSACTION;
1111                 }
1112 
1113             } else {
1114                 error = mContextObject->transact(tr.code, buffer, &reply, tr.flags, reply_callback);
1115             }
1116 
1117             if ((tr.flags & TF_ONE_WAY) == 0) {
1118                 if (!reply_sent) {
1119                     // Should have been a reply but there wasn't, so there
1120                     // must have been an error instead.
1121                     reply.setError(error);
1122                     sendReply(reply, 0);
1123                 } else {
1124                     if (error != NO_ERROR) {
1125                         ALOGE("transact() returned error after sending reply.");
1126                     } else {
1127                         // Ok, reply sent and transact didn't return an error.
1128                     }
1129                 }
1130             } else {
1131                 // One-way transaction, don't care about return value or reply.
1132             }
1133 
1134             //ALOGI("<<<< TRANSACT from pid %d restore pid %d sid %s uid %d\n",
1135             //     mCallingPid, origPid, (origSid ? origSid : "<N/A>"), origUid);
1136 
1137             mCallingPid = origPid;
1138             mCallingSid = origSid;
1139             mCallingUid = origUid;
1140             mStrictModePolicy = origStrictModePolicy;
1141             mLastTransactionBinderFlags = origTransactionBinderFlags;
1142 
1143             IF_LOG_TRANSACTIONS() {
1144                 alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
1145                     << tr.target.ptr << ": " << indent << reply << dedent << endl;
1146             }
1147 
1148         }
1149         break;
1150 
1151     case BR_DEAD_BINDER:
1152         {
1153             BpHwBinder *proxy = (BpHwBinder*)mIn.readPointer();
1154             proxy->sendObituary();
1155             mOut.writeInt32(BC_DEAD_BINDER_DONE);
1156             mOut.writePointer((uintptr_t)proxy);
1157         } break;
1158 
1159     case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1160         {
1161             BpHwBinder *proxy = (BpHwBinder*)mIn.readPointer();
1162             proxy->getWeakRefs()->decWeak(proxy);
1163         } break;
1164 
1165     case BR_FINISHED:
1166         result = TIMED_OUT;
1167         break;
1168 
1169     case BR_NOOP:
1170         break;
1171 
1172     case BR_SPAWN_LOOPER:
1173         mProcess->spawnPooledThread(false);
1174         break;
1175 
1176     default:
1177         printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
1178         result = UNKNOWN_ERROR;
1179         break;
1180     }
1181 
1182     if (result != NO_ERROR) {
1183         mLastError = result;
1184     }
1185 
1186     return result;
1187 }
1188 
threadDestructor(void * st)1189 void IPCThreadState::threadDestructor(void *st)
1190 {
1191         IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1192         if (self) {
1193                 self->flushCommands();
1194 #if defined(__ANDROID__)
1195         if (self->mProcess->mDriverFD > 0) {
1196             ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1197         }
1198 #endif
1199                 delete self;
1200         }
1201 }
1202 
1203 
freeBuffer(Parcel * parcel,const uint8_t * data,size_t,const binder_size_t *,size_t,void *)1204 void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data,
1205                                 size_t /*dataSize*/,
1206                                 const binder_size_t* /*objects*/,
1207                                 size_t /*objectsSize*/, void* /*cookie*/)
1208 {
1209     //ALOGI("Freeing parcel %p", &parcel);
1210     IF_LOG_COMMANDS() {
1211         alog << "Writing BC_FREE_BUFFER for " << data << endl;
1212     }
1213     ALOG_ASSERT(data != NULL, "Called with NULL data");
1214     if (parcel != NULL) parcel->closeFileDescriptors();
1215     IPCThreadState* state = self();
1216     state->mOut.writeInt32(BC_FREE_BUFFER);
1217     state->mOut.writePointer((uintptr_t)data);
1218 }
1219 
1220 }; // namespace hardware
1221 }; // namespace android
1222