• 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 <binder/TextOutput.h>
24 
25 #include <android-base/macros.h>
26 #include <cutils/sched_policy.h>
27 #include <utils/CallStack.h>
28 #include <utils/Log.h>
29 #include <utils/SystemClock.h>
30 
31 #include <atomic>
32 #include <errno.h>
33 #include <inttypes.h>
34 #include <pthread.h>
35 #include <sched.h>
36 #include <signal.h>
37 #include <stdio.h>
38 #include <sys/ioctl.h>
39 #include <sys/resource.h>
40 #include <unistd.h>
41 
42 #include "binder_module.h"
43 
44 #if LOG_NDEBUG
45 
46 #define IF_LOG_TRANSACTIONS() if (false)
47 #define IF_LOG_COMMANDS() if (false)
48 #define LOG_REMOTEREFS(...)
49 #define IF_LOG_REMOTEREFS() if (false)
50 
51 #define LOG_THREADPOOL(...)
52 #define LOG_ONEWAY(...)
53 
54 #else
55 
56 #define IF_LOG_TRANSACTIONS() IF_ALOG(LOG_VERBOSE, "transact")
57 #define IF_LOG_COMMANDS() IF_ALOG(LOG_VERBOSE, "ipc")
58 #define LOG_REMOTEREFS(...) ALOG(LOG_DEBUG, "remoterefs", __VA_ARGS__)
59 #define IF_LOG_REMOTEREFS() IF_ALOG(LOG_DEBUG, "remoterefs")
60 #define LOG_THREADPOOL(...) ALOG(LOG_DEBUG, "threadpool", __VA_ARGS__)
61 #define LOG_ONEWAY(...) ALOG(LOG_DEBUG, "ipc", __VA_ARGS__)
62 
63 #endif
64 
65 // ---------------------------------------------------------------------------
66 
67 namespace android {
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     "BR_FROZEN_REPLY",
91     "BR_ONEWAY_SPAM_SUSPECT",
92     "BR_TRANSACTION_SEC_CTX",
93 };
94 
95 static const char *kCommandStrings[] = {
96     "BC_TRANSACTION",
97     "BC_REPLY",
98     "BC_ACQUIRE_RESULT",
99     "BC_FREE_BUFFER",
100     "BC_INCREFS",
101     "BC_ACQUIRE",
102     "BC_RELEASE",
103     "BC_DECREFS",
104     "BC_INCREFS_DONE",
105     "BC_ACQUIRE_DONE",
106     "BC_ATTEMPT_ACQUIRE",
107     "BC_REGISTER_LOOPER",
108     "BC_ENTER_LOOPER",
109     "BC_EXIT_LOOPER",
110     "BC_REQUEST_DEATH_NOTIFICATION",
111     "BC_CLEAR_DEATH_NOTIFICATION",
112     "BC_DEAD_BINDER_DONE"
113 };
114 
115 static const int64_t kWorkSourcePropagatedBitIndex = 32;
116 
getReturnString(uint32_t cmd)117 static const char* getReturnString(uint32_t cmd)
118 {
119     size_t idx = cmd & _IOC_NRMASK;
120     if (idx < sizeof(kReturnStrings) / sizeof(kReturnStrings[0]))
121         return kReturnStrings[idx];
122     else
123         return "unknown";
124 }
125 
printBinderTransactionData(std::ostream & out,const void * data)126 static const void* printBinderTransactionData(std::ostream& out, const void* data) {
127     const binder_transaction_data* btd =
128         (const binder_transaction_data*)data;
129     if (btd->target.handle < 1024) {
130         /* want to print descriptors in decimal; guess based on value */
131         out << "\ttarget.desc=" << btd->target.handle;
132     } else {
133         out << "\ttarget.ptr=" << btd->target.ptr;
134     }
135     out << "\t (cookie " << btd->cookie << ")\n"
136         << "\tcode=" << TypeCode(btd->code) << ", flags=" << (void*)(uint64_t)btd->flags << "\n"
137         << "\tdata=" << btd->data.ptr.buffer << " (" << (void*)btd->data_size << " bytes)\n"
138         << "\toffsets=" << btd->data.ptr.offsets << " (" << (void*)btd->offsets_size << " bytes)\n";
139     return btd + 1;
140 }
141 
printBinderTransactionDataSecCtx(std::ostream & out,const void * data)142 static const void* printBinderTransactionDataSecCtx(std::ostream& out, const void* data) {
143     const binder_transaction_data_secctx* btd = (const binder_transaction_data_secctx*)data;
144 
145     printBinderTransactionData(out, &btd->transaction_data);
146 
147     char* secctx = (char*)btd->secctx;
148     out << "\tsecctx=" << secctx << "\n";
149 
150     return btd+1;
151 }
152 
printReturnCommand(std::ostream & out,const void * _cmd)153 static const void* printReturnCommand(std::ostream& out, const void* _cmd) {
154     static const size_t N = sizeof(kReturnStrings)/sizeof(kReturnStrings[0]);
155     const int32_t* cmd = (const int32_t*)_cmd;
156     uint32_t code = (uint32_t)*cmd++;
157     size_t cmdIndex = code & 0xff;
158     if (code == BR_ERROR) {
159         out << "\tBR_ERROR: " << (void*)(uint64_t)(*cmd++) << "\n";
160         return cmd;
161     } else if (cmdIndex >= N) {
162         out << "\tUnknown reply: " << code << "\n";
163         return cmd;
164     }
165     out << "\t" << kReturnStrings[cmdIndex];
166 
167     switch (code) {
168         case BR_TRANSACTION_SEC_CTX: {
169             out << ": ";
170             cmd = (const int32_t*)printBinderTransactionDataSecCtx(out, cmd);
171         } break;
172 
173         case BR_TRANSACTION:
174         case BR_REPLY: {
175             out << ": ";
176             cmd = (const int32_t*)printBinderTransactionData(out, cmd);
177         } break;
178 
179         case BR_ACQUIRE_RESULT: {
180             const int32_t res = *cmd++;
181             out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
182         } break;
183 
184         case BR_INCREFS:
185         case BR_ACQUIRE:
186         case BR_RELEASE:
187         case BR_DECREFS: {
188             const int32_t b = *cmd++;
189             const int32_t c = *cmd++;
190             out << ": target=" << (void*)(uint64_t)b << " (cookie " << (void*)(uint64_t)c << ")";
191         } break;
192 
193         case BR_ATTEMPT_ACQUIRE: {
194             const int32_t p = *cmd++;
195             const int32_t b = *cmd++;
196             const int32_t c = *cmd++;
197             out << ": target=" << (void*)(uint64_t)b << " (cookie " << (void*)(uint64_t)c
198                 << "), pri=" << p;
199         } break;
200 
201         case BR_DEAD_BINDER:
202         case BR_CLEAR_DEATH_NOTIFICATION_DONE: {
203             const int32_t c = *cmd++;
204             out << ": death cookie " << (void*)(uint64_t)c;
205         } break;
206 
207         default:
208             // no details to show for: BR_OK, BR_DEAD_REPLY,
209             // BR_TRANSACTION_COMPLETE, BR_FINISHED
210             break;
211     }
212 
213     out << "\n";
214     return cmd;
215 }
216 
printCommand(std::ostream & out,const void * _cmd)217 static const void* printCommand(std::ostream& out, const void* _cmd) {
218     static const size_t N = sizeof(kCommandStrings)/sizeof(kCommandStrings[0]);
219     const int32_t* cmd = (const int32_t*)_cmd;
220     uint32_t code = (uint32_t)*cmd++;
221     size_t cmdIndex = code & 0xff;
222 
223     if (cmdIndex >= N) {
224         out << "Unknown command: " << code << "\n";
225         return cmd;
226     }
227     out << kCommandStrings[cmdIndex];
228 
229     switch (code) {
230         case BC_TRANSACTION:
231         case BC_REPLY: {
232             out << ": ";
233             cmd = (const int32_t*)printBinderTransactionData(out, cmd);
234         } break;
235 
236         case BC_ACQUIRE_RESULT: {
237             const int32_t res = *cmd++;
238             out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
239         } break;
240 
241         case BC_FREE_BUFFER: {
242             const int32_t buf = *cmd++;
243             out << ": buffer=" << (void*)(uint64_t)buf;
244         } break;
245 
246         case BC_INCREFS:
247         case BC_ACQUIRE:
248         case BC_RELEASE:
249         case BC_DECREFS: {
250             const int32_t d = *cmd++;
251             out << ": desc=" << d;
252         } break;
253 
254         case BC_INCREFS_DONE:
255         case BC_ACQUIRE_DONE: {
256             const int32_t b = *cmd++;
257             const int32_t c = *cmd++;
258             out << ": target=" << (void*)(uint64_t)b << " (cookie " << (void*)(uint64_t)c << ")";
259         } break;
260 
261         case BC_ATTEMPT_ACQUIRE: {
262             const int32_t p = *cmd++;
263             const int32_t d = *cmd++;
264             out << ": desc=" << d << ", pri=" << p;
265         } break;
266 
267         case BC_REQUEST_DEATH_NOTIFICATION:
268         case BC_CLEAR_DEATH_NOTIFICATION: {
269             const int32_t h = *cmd++;
270             const int32_t c = *cmd++;
271             out << ": handle=" << h << " (death cookie " << (void*)(uint64_t)c << ")";
272         } break;
273 
274         case BC_DEAD_BINDER_DONE: {
275             const int32_t c = *cmd++;
276             out << ": death cookie " << (void*)(uint64_t)c;
277         } break;
278 
279         default:
280             // no details to show for: BC_REGISTER_LOOPER, BC_ENTER_LOOPER,
281             // BC_EXIT_LOOPER
282             break;
283     }
284 
285     out << "\n";
286     return cmd;
287 }
288 
289 static pthread_mutex_t gTLSMutex = PTHREAD_MUTEX_INITIALIZER;
290 static std::atomic<bool> gHaveTLS(false);
291 static pthread_key_t gTLS = 0;
292 static std::atomic<bool> gShutdown = false;
293 static std::atomic<bool> gDisableBackgroundScheduling = false;
294 
self()295 IPCThreadState* IPCThreadState::self()
296 {
297     if (gHaveTLS.load(std::memory_order_acquire)) {
298 restart:
299         const pthread_key_t k = gTLS;
300         IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
301         if (st) return st;
302         return new IPCThreadState;
303     }
304 
305     // Racey, heuristic test for simultaneous shutdown.
306     if (gShutdown.load(std::memory_order_relaxed)) {
307         ALOGW("Calling IPCThreadState::self() during shutdown is dangerous, expect a crash.\n");
308         return nullptr;
309     }
310 
311     pthread_mutex_lock(&gTLSMutex);
312     if (!gHaveTLS.load(std::memory_order_relaxed)) {
313         int key_create_value = pthread_key_create(&gTLS, threadDestructor);
314         if (key_create_value != 0) {
315             pthread_mutex_unlock(&gTLSMutex);
316             ALOGW("IPCThreadState::self() unable to create TLS key, expect a crash: %s\n",
317                     strerror(key_create_value));
318             return nullptr;
319         }
320         gHaveTLS.store(true, std::memory_order_release);
321     }
322     pthread_mutex_unlock(&gTLSMutex);
323     goto restart;
324 }
325 
selfOrNull()326 IPCThreadState* IPCThreadState::selfOrNull()
327 {
328     if (gHaveTLS.load(std::memory_order_acquire)) {
329         const pthread_key_t k = gTLS;
330         IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
331         return st;
332     }
333     return nullptr;
334 }
335 
shutdown()336 void IPCThreadState::shutdown()
337 {
338     gShutdown.store(true, std::memory_order_relaxed);
339 
340     if (gHaveTLS.load(std::memory_order_acquire)) {
341         // XXX Need to wait for all thread pool threads to exit!
342         IPCThreadState* st = (IPCThreadState*)pthread_getspecific(gTLS);
343         if (st) {
344             delete st;
345             pthread_setspecific(gTLS, nullptr);
346         }
347         pthread_key_delete(gTLS);
348         gHaveTLS.store(false, std::memory_order_release);
349     }
350 }
351 
disableBackgroundScheduling(bool disable)352 void IPCThreadState::disableBackgroundScheduling(bool disable)
353 {
354     gDisableBackgroundScheduling.store(disable, std::memory_order_relaxed);
355 }
356 
backgroundSchedulingDisabled()357 bool IPCThreadState::backgroundSchedulingDisabled()
358 {
359     return gDisableBackgroundScheduling.load(std::memory_order_relaxed);
360 }
361 
clearLastError()362 status_t IPCThreadState::clearLastError()
363 {
364     const status_t err = mLastError;
365     mLastError = NO_ERROR;
366     return err;
367 }
368 
getCallingPid() const369 pid_t IPCThreadState::getCallingPid() const
370 {
371     checkContextIsBinderForUse(__func__);
372     return mCallingPid;
373 }
374 
getCallingSid() const375 const char* IPCThreadState::getCallingSid() const
376 {
377     checkContextIsBinderForUse(__func__);
378     return mCallingSid;
379 }
380 
getCallingUid() const381 uid_t IPCThreadState::getCallingUid() const
382 {
383     checkContextIsBinderForUse(__func__);
384     return mCallingUid;
385 }
386 
pushGetCallingSpGuard(const SpGuard * guard)387 const IPCThreadState::SpGuard* IPCThreadState::pushGetCallingSpGuard(const SpGuard* guard) {
388     const SpGuard* orig = mServingStackPointerGuard;
389     mServingStackPointerGuard = guard;
390     return orig;
391 }
392 
restoreGetCallingSpGuard(const SpGuard * guard)393 void IPCThreadState::restoreGetCallingSpGuard(const SpGuard* guard) {
394     mServingStackPointerGuard = guard;
395 }
396 
checkContextIsBinderForUse(const char * use) const397 void IPCThreadState::checkContextIsBinderForUse(const char* use) const {
398     if (LIKELY(mServingStackPointerGuard == nullptr)) return;
399 
400     if (!mServingStackPointer || mServingStackPointerGuard->address < mServingStackPointer) {
401         LOG_ALWAYS_FATAL("In context %s, %s does not make sense (binder sp: %p, guard: %p).",
402                          mServingStackPointerGuard->context, use, mServingStackPointer,
403                          mServingStackPointerGuard->address);
404     }
405 
406     // in the case mServingStackPointer is deeper in the stack than the guard,
407     // we must be serving a binder transaction (maybe nested). This is a binder
408     // context, so we don't abort
409 }
410 
encodeExplicitIdentity(bool hasExplicitIdentity,pid_t callingPid)411 constexpr uint32_t encodeExplicitIdentity(bool hasExplicitIdentity, pid_t callingPid) {
412     uint32_t as_unsigned = static_cast<uint32_t>(callingPid);
413     if (hasExplicitIdentity) {
414         return as_unsigned | (1 << 30);
415     } else {
416         return as_unsigned & ~(1 << 30);
417     }
418 }
419 
packCallingIdentity(bool hasExplicitIdentity,uid_t callingUid,pid_t callingPid)420 constexpr int64_t packCallingIdentity(bool hasExplicitIdentity, uid_t callingUid,
421                                       pid_t callingPid) {
422     // Calling PID is a 32-bit signed integer, but doesn't consume the entire 32 bit space.
423     // To future-proof this and because we have extra capacity, we decided to also support -1,
424     // since this constant is used to represent invalid UID in other places of the system.
425     // Thus, we pack hasExplicitIdentity into the 2nd bit from the left.  This allows us to
426     // preserve the (left-most) bit for the sign while also encoding the value of
427     // hasExplicitIdentity.
428     //               32b     |        1b         |         1b            |        30b
429     // token = [ calling uid | calling pid(sign) | has explicit identity | calling pid(rest) ]
430     uint64_t token = (static_cast<uint64_t>(callingUid) << 32) |
431             encodeExplicitIdentity(hasExplicitIdentity, callingPid);
432     return static_cast<int64_t>(token);
433 }
434 
unpackHasExplicitIdentity(int64_t token)435 constexpr bool unpackHasExplicitIdentity(int64_t token) {
436     return static_cast<int32_t>(token) & (1 << 30);
437 }
438 
unpackCallingUid(int64_t token)439 constexpr uid_t unpackCallingUid(int64_t token) {
440     return static_cast<uid_t>(token >> 32);
441 }
442 
unpackCallingPid(int64_t token)443 constexpr pid_t unpackCallingPid(int64_t token) {
444     int32_t encodedPid = static_cast<int32_t>(token);
445     if (encodedPid & (1 << 31)) {
446         return encodedPid | (1 << 30);
447     } else {
448         return encodedPid & ~(1 << 30);
449     }
450 }
451 
452 static_assert(unpackHasExplicitIdentity(packCallingIdentity(true, 1000, 9999)) == true,
453               "pack true hasExplicit");
454 
455 static_assert(unpackCallingUid(packCallingIdentity(true, 1000, 9999)) == 1000, "pack true uid");
456 
457 static_assert(unpackCallingPid(packCallingIdentity(true, 1000, 9999)) == 9999, "pack true pid");
458 
459 static_assert(unpackHasExplicitIdentity(packCallingIdentity(false, 1000, 9999)) == false,
460               "pack false hasExplicit");
461 
462 static_assert(unpackCallingUid(packCallingIdentity(false, 1000, 9999)) == 1000, "pack false uid");
463 
464 static_assert(unpackCallingPid(packCallingIdentity(false, 1000, 9999)) == 9999, "pack false pid");
465 
466 static_assert(unpackHasExplicitIdentity(packCallingIdentity(true, 1000, -1)) == true,
467               "pack true (negative) hasExplicit");
468 
469 static_assert(unpackCallingUid(packCallingIdentity(true, 1000, -1)) == 1000,
470               "pack true (negative) uid");
471 
472 static_assert(unpackCallingPid(packCallingIdentity(true, 1000, -1)) == -1,
473               "pack true (negative) pid");
474 
475 static_assert(unpackHasExplicitIdentity(packCallingIdentity(false, 1000, -1)) == false,
476               "pack false (negative) hasExplicit");
477 
478 static_assert(unpackCallingUid(packCallingIdentity(false, 1000, -1)) == 1000,
479               "pack false (negative) uid");
480 
481 static_assert(unpackCallingPid(packCallingIdentity(false, 1000, -1)) == -1,
482               "pack false (negative) pid");
483 
clearCallingIdentity()484 int64_t IPCThreadState::clearCallingIdentity()
485 {
486     // ignore mCallingSid for legacy reasons
487     int64_t token = packCallingIdentity(mHasExplicitIdentity, mCallingUid, mCallingPid);
488     clearCaller();
489     mHasExplicitIdentity = true;
490     return token;
491 }
492 
hasExplicitIdentity()493 bool IPCThreadState::hasExplicitIdentity() {
494     return mHasExplicitIdentity;
495 }
496 
setStrictModePolicy(int32_t policy)497 void IPCThreadState::setStrictModePolicy(int32_t policy)
498 {
499     mStrictModePolicy = policy;
500 }
501 
getStrictModePolicy() const502 int32_t IPCThreadState::getStrictModePolicy() const
503 {
504     return mStrictModePolicy;
505 }
506 
setCallingWorkSourceUid(uid_t uid)507 int64_t IPCThreadState::setCallingWorkSourceUid(uid_t uid)
508 {
509     int64_t token = setCallingWorkSourceUidWithoutPropagation(uid);
510     mPropagateWorkSource = true;
511     return token;
512 }
513 
setCallingWorkSourceUidWithoutPropagation(uid_t uid)514 int64_t IPCThreadState::setCallingWorkSourceUidWithoutPropagation(uid_t uid)
515 {
516     const int64_t propagatedBit = ((int64_t)mPropagateWorkSource) << kWorkSourcePropagatedBitIndex;
517     int64_t token = propagatedBit | mWorkSource;
518     mWorkSource = uid;
519     return token;
520 }
521 
clearPropagateWorkSource()522 void IPCThreadState::clearPropagateWorkSource()
523 {
524     mPropagateWorkSource = false;
525 }
526 
shouldPropagateWorkSource() const527 bool IPCThreadState::shouldPropagateWorkSource() const
528 {
529     return mPropagateWorkSource;
530 }
531 
getCallingWorkSourceUid() const532 uid_t IPCThreadState::getCallingWorkSourceUid() const
533 {
534     return mWorkSource;
535 }
536 
clearCallingWorkSource()537 int64_t IPCThreadState::clearCallingWorkSource()
538 {
539     return setCallingWorkSourceUid(kUnsetWorkSource);
540 }
541 
restoreCallingWorkSource(int64_t token)542 void IPCThreadState::restoreCallingWorkSource(int64_t token)
543 {
544     uid_t uid = (int)token;
545     setCallingWorkSourceUidWithoutPropagation(uid);
546     mPropagateWorkSource = ((token >> kWorkSourcePropagatedBitIndex) & 1) == 1;
547 }
548 
setLastTransactionBinderFlags(int32_t flags)549 void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
550 {
551     mLastTransactionBinderFlags = flags;
552 }
553 
getLastTransactionBinderFlags() const554 int32_t IPCThreadState::getLastTransactionBinderFlags() const
555 {
556     return mLastTransactionBinderFlags;
557 }
558 
setCallRestriction(ProcessState::CallRestriction restriction)559 void IPCThreadState::setCallRestriction(ProcessState::CallRestriction restriction) {
560     mCallRestriction = restriction;
561 }
562 
getCallRestriction() const563 ProcessState::CallRestriction IPCThreadState::getCallRestriction() const {
564     return mCallRestriction;
565 }
566 
restoreCallingIdentity(int64_t token)567 void IPCThreadState::restoreCallingIdentity(int64_t token)
568 {
569     mCallingUid = unpackCallingUid(token);
570     mCallingSid = nullptr;  // not enough data to restore
571     mCallingPid = unpackCallingPid(token);
572     mHasExplicitIdentity = unpackHasExplicitIdentity(token);
573 }
574 
clearCaller()575 void IPCThreadState::clearCaller()
576 {
577     mCallingPid = getpid();
578     mCallingSid = nullptr;  // expensive to lookup
579     mCallingUid = getuid();
580 }
581 
flushCommands()582 void IPCThreadState::flushCommands()
583 {
584     if (mProcess->mDriverFD < 0)
585         return;
586     talkWithDriver(false);
587     // The flush could have caused post-write refcount decrements to have
588     // been executed, which in turn could result in BC_RELEASE/BC_DECREFS
589     // being queued in mOut. So flush again, if we need to.
590     if (mOut.dataSize() > 0) {
591         talkWithDriver(false);
592     }
593     if (mOut.dataSize() > 0) {
594         ALOGW("mOut.dataSize() > 0 after flushCommands()");
595     }
596 }
597 
flushIfNeeded()598 bool IPCThreadState::flushIfNeeded()
599 {
600     if (mIsLooper || mServingStackPointer != nullptr || mIsFlushing) {
601         return false;
602     }
603     mIsFlushing = true;
604     // In case this thread is not a looper and is not currently serving a binder transaction,
605     // there's no guarantee that this thread will call back into the kernel driver any time
606     // soon. Therefore, flush pending commands such as BC_FREE_BUFFER, to prevent them from getting
607     // stuck in this thread's out buffer.
608     flushCommands();
609     mIsFlushing = false;
610     return true;
611 }
612 
blockUntilThreadAvailable()613 void IPCThreadState::blockUntilThreadAvailable()
614 {
615     pthread_mutex_lock(&mProcess->mThreadCountLock);
616     mProcess->mWaitingForThreads++;
617     while (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads) {
618         ALOGW("Waiting for thread to be free. mExecutingThreadsCount=%lu mMaxThreads=%lu\n",
619                 static_cast<unsigned long>(mProcess->mExecutingThreadsCount),
620                 static_cast<unsigned long>(mProcess->mMaxThreads));
621         pthread_cond_wait(&mProcess->mThreadCountDecrement, &mProcess->mThreadCountLock);
622     }
623     mProcess->mWaitingForThreads--;
624     pthread_mutex_unlock(&mProcess->mThreadCountLock);
625 }
626 
getAndExecuteCommand()627 status_t IPCThreadState::getAndExecuteCommand()
628 {
629     status_t result;
630     int32_t cmd;
631 
632     result = talkWithDriver();
633     if (result >= NO_ERROR) {
634         size_t IN = mIn.dataAvail();
635         if (IN < sizeof(int32_t)) return result;
636         cmd = mIn.readInt32();
637         IF_LOG_COMMANDS() {
638             std::ostringstream logStream;
639             logStream << "Processing top-level Command: " << getReturnString(cmd) << "\n";
640             std::string message = logStream.str();
641             ALOGI("%s", message.c_str());
642         }
643 
644         pthread_mutex_lock(&mProcess->mThreadCountLock);
645         mProcess->mExecutingThreadsCount++;
646         if (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads &&
647                 mProcess->mStarvationStartTimeMs == 0) {
648             mProcess->mStarvationStartTimeMs = uptimeMillis();
649         }
650         pthread_mutex_unlock(&mProcess->mThreadCountLock);
651 
652         result = executeCommand(cmd);
653 
654         pthread_mutex_lock(&mProcess->mThreadCountLock);
655         mProcess->mExecutingThreadsCount--;
656         if (mProcess->mExecutingThreadsCount < mProcess->mMaxThreads &&
657                 mProcess->mStarvationStartTimeMs != 0) {
658             int64_t starvationTimeMs = uptimeMillis() - mProcess->mStarvationStartTimeMs;
659             if (starvationTimeMs > 100) {
660                 ALOGE("binder thread pool (%zu threads) starved for %" PRId64 " ms",
661                       mProcess->mMaxThreads, starvationTimeMs);
662             }
663             mProcess->mStarvationStartTimeMs = 0;
664         }
665 
666         // Cond broadcast can be expensive, so don't send it every time a binder
667         // call is processed. b/168806193
668         if (mProcess->mWaitingForThreads > 0) {
669             pthread_cond_broadcast(&mProcess->mThreadCountDecrement);
670         }
671         pthread_mutex_unlock(&mProcess->mThreadCountLock);
672     }
673 
674     return result;
675 }
676 
677 // When we've cleared the incoming command queue, process any pending derefs
processPendingDerefs()678 void IPCThreadState::processPendingDerefs()
679 {
680     if (mIn.dataPosition() >= mIn.dataSize()) {
681         /*
682          * The decWeak()/decStrong() calls may cause a destructor to run,
683          * which in turn could have initiated an outgoing transaction,
684          * which in turn could cause us to add to the pending refs
685          * vectors; so instead of simply iterating, loop until they're empty.
686          *
687          * We do this in an outer loop, because calling decStrong()
688          * may result in something being added to mPendingWeakDerefs,
689          * which could be delayed until the next incoming command
690          * from the driver if we don't process it now.
691          */
692         while (mPendingWeakDerefs.size() > 0 || mPendingStrongDerefs.size() > 0) {
693             while (mPendingWeakDerefs.size() > 0) {
694                 RefBase::weakref_type* refs = mPendingWeakDerefs[0];
695                 mPendingWeakDerefs.removeAt(0);
696                 refs->decWeak(mProcess.get());
697             }
698 
699             if (mPendingStrongDerefs.size() > 0) {
700                 // We don't use while() here because we don't want to re-order
701                 // strong and weak decs at all; if this decStrong() causes both a
702                 // decWeak() and a decStrong() to be queued, we want to process
703                 // the decWeak() first.
704                 BBinder* obj = mPendingStrongDerefs[0];
705                 mPendingStrongDerefs.removeAt(0);
706                 obj->decStrong(mProcess.get());
707             }
708         }
709     }
710 }
711 
processPostWriteDerefs()712 void IPCThreadState::processPostWriteDerefs()
713 {
714     for (size_t i = 0; i < mPostWriteWeakDerefs.size(); i++) {
715         RefBase::weakref_type* refs = mPostWriteWeakDerefs[i];
716         refs->decWeak(mProcess.get());
717     }
718     mPostWriteWeakDerefs.clear();
719 
720     for (size_t i = 0; i < mPostWriteStrongDerefs.size(); i++) {
721         RefBase* obj = mPostWriteStrongDerefs[i];
722         obj->decStrong(mProcess.get());
723     }
724     mPostWriteStrongDerefs.clear();
725 }
726 
joinThreadPool(bool isMain)727 void IPCThreadState::joinThreadPool(bool isMain)
728 {
729     LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
730     pthread_mutex_lock(&mProcess->mThreadCountLock);
731     mProcess->mCurrentThreads++;
732     pthread_mutex_unlock(&mProcess->mThreadCountLock);
733     mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
734 
735     mIsLooper = true;
736     status_t result;
737     do {
738         processPendingDerefs();
739         // now get the next command to be processed, waiting if necessary
740         result = getAndExecuteCommand();
741 
742         if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
743             LOG_ALWAYS_FATAL("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
744                   mProcess->mDriverFD, result);
745         }
746 
747         // Let this thread exit the thread pool if it is no longer
748         // needed and it is not the main process thread.
749         if(result == TIMED_OUT && !isMain) {
750             break;
751         }
752     } while (result != -ECONNREFUSED && result != -EBADF);
753 
754     LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%d\n",
755         (void*)pthread_self(), getpid(), result);
756 
757     mOut.writeInt32(BC_EXIT_LOOPER);
758     mIsLooper = false;
759     talkWithDriver(false);
760     pthread_mutex_lock(&mProcess->mThreadCountLock);
761     LOG_ALWAYS_FATAL_IF(mProcess->mCurrentThreads == 0,
762                         "Threadpool thread count = 0. Thread cannot exist and exit in empty "
763                         "threadpool\n"
764                         "Misconfiguration. Increase threadpool max threads configuration\n");
765     mProcess->mCurrentThreads--;
766     pthread_mutex_unlock(&mProcess->mThreadCountLock);
767 }
768 
setupPolling(int * fd)769 status_t IPCThreadState::setupPolling(int* fd)
770 {
771     if (mProcess->mDriverFD < 0) {
772         return -EBADF;
773     }
774 
775     mOut.writeInt32(BC_ENTER_LOOPER);
776     flushCommands();
777     *fd = mProcess->mDriverFD;
778     pthread_mutex_lock(&mProcess->mThreadCountLock);
779     mProcess->mCurrentThreads++;
780     pthread_mutex_unlock(&mProcess->mThreadCountLock);
781     return 0;
782 }
783 
handlePolledCommands()784 status_t IPCThreadState::handlePolledCommands()
785 {
786     status_t result;
787 
788     do {
789         result = getAndExecuteCommand();
790     } while (mIn.dataPosition() < mIn.dataSize());
791 
792     processPendingDerefs();
793     flushCommands();
794     return result;
795 }
796 
stopProcess(bool)797 void IPCThreadState::stopProcess(bool /*immediate*/)
798 {
799     //ALOGI("**** STOPPING PROCESS");
800     flushCommands();
801     int fd = mProcess->mDriverFD;
802     mProcess->mDriverFD = -1;
803     close(fd);
804     //kill(getpid(), SIGKILL);
805 }
806 
transact(int32_t handle,uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)807 status_t IPCThreadState::transact(int32_t handle,
808                                   uint32_t code, const Parcel& data,
809                                   Parcel* reply, uint32_t flags)
810 {
811     LOG_ALWAYS_FATAL_IF(data.isForRpc(), "Parcel constructed for RPC, but being used with binder.");
812 
813     status_t err;
814 
815     flags |= TF_ACCEPT_FDS;
816 
817     IF_LOG_TRANSACTIONS() {
818         std::ostringstream logStream;
819         logStream << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand " << handle
820                   << " / code " << TypeCode(code) << ": \t" << data << "\n";
821         std::string message = logStream.str();
822         ALOGI("%s", message.c_str());
823     }
824 
825     LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
826         (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
827     err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, nullptr);
828 
829     if (err != NO_ERROR) {
830         if (reply) reply->setError(err);
831         return (mLastError = err);
832     }
833 
834     if ((flags & TF_ONE_WAY) == 0) {
835         if (UNLIKELY(mCallRestriction != ProcessState::CallRestriction::NONE)) {
836             if (mCallRestriction == ProcessState::CallRestriction::ERROR_IF_NOT_ONEWAY) {
837                 ALOGE("Process making non-oneway call (code: %u) but is restricted.", code);
838                 CallStack::logStack("non-oneway call", CallStack::getCurrent(10).get(),
839                     ANDROID_LOG_ERROR);
840             } else /* FATAL_IF_NOT_ONEWAY */ {
841                 LOG_ALWAYS_FATAL("Process may not make non-oneway calls (code: %u).", code);
842             }
843         }
844 
845         #if 0
846         if (code == 4) { // relayout
847             ALOGI(">>>>>> CALLING transaction 4");
848         } else {
849             ALOGI(">>>>>> CALLING transaction %d", code);
850         }
851         #endif
852         if (reply) {
853             err = waitForResponse(reply);
854         } else {
855             Parcel fakeReply;
856             err = waitForResponse(&fakeReply);
857         }
858         #if 0
859         if (code == 4) { // relayout
860             ALOGI("<<<<<< RETURNING transaction 4");
861         } else {
862             ALOGI("<<<<<< RETURNING transaction %d", code);
863         }
864         #endif
865 
866         IF_LOG_TRANSACTIONS() {
867             std::ostringstream logStream;
868             logStream << "BR_REPLY thr " << (void*)pthread_self() << " / hand " << handle << ": ";
869             if (reply)
870                 logStream << "\t" << *reply << "\n";
871             else
872                 logStream << "(none requested)"
873                           << "\n";
874             std::string message = logStream.str();
875             ALOGI("%s", message.c_str());
876         }
877     } else {
878         err = waitForResponse(nullptr, nullptr);
879     }
880 
881     return err;
882 }
883 
incStrongHandle(int32_t handle,BpBinder * proxy)884 void IPCThreadState::incStrongHandle(int32_t handle, BpBinder *proxy)
885 {
886     LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
887     mOut.writeInt32(BC_ACQUIRE);
888     mOut.writeInt32(handle);
889     if (!flushIfNeeded()) {
890         // Create a temp reference until the driver has handled this command.
891         proxy->incStrong(mProcess.get());
892         mPostWriteStrongDerefs.push(proxy);
893     }
894 }
895 
decStrongHandle(int32_t handle)896 void IPCThreadState::decStrongHandle(int32_t handle)
897 {
898     LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
899     mOut.writeInt32(BC_RELEASE);
900     mOut.writeInt32(handle);
901     flushIfNeeded();
902 }
903 
incWeakHandle(int32_t handle,BpBinder * proxy)904 void IPCThreadState::incWeakHandle(int32_t handle, BpBinder *proxy)
905 {
906     LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
907     mOut.writeInt32(BC_INCREFS);
908     mOut.writeInt32(handle);
909     if (!flushIfNeeded()) {
910         // Create a temp reference until the driver has handled this command.
911         proxy->getWeakRefs()->incWeak(mProcess.get());
912         mPostWriteWeakDerefs.push(proxy->getWeakRefs());
913     }
914 }
915 
decWeakHandle(int32_t handle)916 void IPCThreadState::decWeakHandle(int32_t handle)
917 {
918     LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
919     mOut.writeInt32(BC_DECREFS);
920     mOut.writeInt32(handle);
921     flushIfNeeded();
922 }
923 
attemptIncStrongHandle(int32_t handle)924 status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
925 {
926 #if HAS_BC_ATTEMPT_ACQUIRE
927     LOG_REMOTEREFS("IPCThreadState::attemptIncStrongHandle(%d)\n", handle);
928     mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
929     mOut.writeInt32(0); // xxx was thread priority
930     mOut.writeInt32(handle);
931     status_t result = UNKNOWN_ERROR;
932 
933     waitForResponse(NULL, &result);
934 
935 #if LOG_REFCOUNTS
936     ALOGV("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
937         handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
938 #endif
939 
940     return result;
941 #else
942     (void)handle;
943     ALOGE("%s(%d): Not supported\n", __func__, handle);
944     return INVALID_OPERATION;
945 #endif
946 }
947 
expungeHandle(int32_t handle,IBinder * binder)948 void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
949 {
950 #if LOG_REFCOUNTS
951     ALOGV("IPCThreadState::expungeHandle(%ld)\n", handle);
952 #endif
953     self()->mProcess->expungeHandle(handle, binder); // NOLINT
954 }
955 
requestDeathNotification(int32_t handle,BpBinder * proxy)956 status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
957 {
958     mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
959     mOut.writeInt32((int32_t)handle);
960     mOut.writePointer((uintptr_t)proxy);
961     return NO_ERROR;
962 }
963 
clearDeathNotification(int32_t handle,BpBinder * proxy)964 status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
965 {
966     mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
967     mOut.writeInt32((int32_t)handle);
968     mOut.writePointer((uintptr_t)proxy);
969     return NO_ERROR;
970 }
971 
IPCThreadState()972 IPCThreadState::IPCThreadState()
973       : mProcess(ProcessState::self()),
974         mServingStackPointer(nullptr),
975         mServingStackPointerGuard(nullptr),
976         mWorkSource(kUnsetWorkSource),
977         mPropagateWorkSource(false),
978         mIsLooper(false),
979         mIsFlushing(false),
980         mStrictModePolicy(0),
981         mLastTransactionBinderFlags(0),
982         mCallRestriction(mProcess->mCallRestriction) {
983     pthread_setspecific(gTLS, this);
984     clearCaller();
985     mHasExplicitIdentity = false;
986     mIn.setDataCapacity(256);
987     mOut.setDataCapacity(256);
988 }
989 
~IPCThreadState()990 IPCThreadState::~IPCThreadState()
991 {
992 }
993 
sendReply(const Parcel & reply,uint32_t flags)994 status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
995 {
996     status_t err;
997     status_t statusBuffer;
998     err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
999     if (err < NO_ERROR) return err;
1000 
1001     return waitForResponse(nullptr, nullptr);
1002 }
1003 
waitForResponse(Parcel * reply,status_t * acquireResult)1004 status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
1005 {
1006     uint32_t cmd;
1007     int32_t err;
1008 
1009     while (1) {
1010         if ((err=talkWithDriver()) < NO_ERROR) break;
1011         err = mIn.errorCheck();
1012         if (err < NO_ERROR) break;
1013         if (mIn.dataAvail() == 0) continue;
1014 
1015         cmd = (uint32_t)mIn.readInt32();
1016 
1017         IF_LOG_COMMANDS() {
1018             std::ostringstream logStream;
1019             logStream << "Processing waitForResponse Command: " << getReturnString(cmd) << "\n";
1020             std::string message = logStream.str();
1021             ALOGI("%s", message.c_str());
1022         }
1023 
1024         switch (cmd) {
1025         case BR_ONEWAY_SPAM_SUSPECT:
1026             ALOGE("Process seems to be sending too many oneway calls.");
1027             CallStack::logStack("oneway spamming", CallStack::getCurrent().get(),
1028                     ANDROID_LOG_ERROR);
1029             [[fallthrough]];
1030         case BR_TRANSACTION_COMPLETE:
1031             if (!reply && !acquireResult) goto finish;
1032             break;
1033 
1034         case BR_TRANSACTION_PENDING_FROZEN:
1035             ALOGW("Sending oneway calls to frozen process.");
1036             goto finish;
1037 
1038         case BR_DEAD_REPLY:
1039             err = DEAD_OBJECT;
1040             goto finish;
1041 
1042         case BR_FAILED_REPLY:
1043             err = FAILED_TRANSACTION;
1044             goto finish;
1045 
1046         case BR_FROZEN_REPLY:
1047             err = FAILED_TRANSACTION;
1048             goto finish;
1049 
1050         case BR_ACQUIRE_RESULT:
1051             {
1052                 ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
1053                 const int32_t result = mIn.readInt32();
1054                 if (!acquireResult) continue;
1055                 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
1056             }
1057             goto finish;
1058 
1059         case BR_REPLY:
1060             {
1061                 binder_transaction_data tr;
1062                 err = mIn.read(&tr, sizeof(tr));
1063                 ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
1064                 if (err != NO_ERROR) goto finish;
1065 
1066                 if (reply) {
1067                     if ((tr.flags & TF_STATUS_CODE) == 0) {
1068                         reply->ipcSetDataReference(
1069                             reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1070                             tr.data_size,
1071                             reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1072                             tr.offsets_size/sizeof(binder_size_t),
1073                             freeBuffer);
1074                     } else {
1075                         err = *reinterpret_cast<const status_t*>(tr.data.ptr.buffer);
1076                         freeBuffer(reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1077                                    tr.data_size,
1078                                    reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1079                                    tr.offsets_size / sizeof(binder_size_t));
1080                     }
1081                 } else {
1082                     freeBuffer(reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer), tr.data_size,
1083                                reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1084                                tr.offsets_size / sizeof(binder_size_t));
1085                     continue;
1086                 }
1087             }
1088             goto finish;
1089 
1090         default:
1091             err = executeCommand(cmd);
1092             if (err != NO_ERROR) goto finish;
1093             break;
1094         }
1095     }
1096 
1097 finish:
1098     if (err != NO_ERROR) {
1099         if (acquireResult) *acquireResult = err;
1100         if (reply) reply->setError(err);
1101         mLastError = err;
1102         logExtendedError();
1103     }
1104 
1105     return err;
1106 }
1107 
talkWithDriver(bool doReceive)1108 status_t IPCThreadState::talkWithDriver(bool doReceive)
1109 {
1110     if (mProcess->mDriverFD < 0) {
1111         return -EBADF;
1112     }
1113 
1114     binder_write_read bwr;
1115 
1116     // Is the read buffer empty?
1117     const bool needRead = mIn.dataPosition() >= mIn.dataSize();
1118 
1119     // We don't want to write anything if we are still reading
1120     // from data left in the input buffer and the caller
1121     // has requested to read the next data.
1122     const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
1123 
1124     bwr.write_size = outAvail;
1125     bwr.write_buffer = (uintptr_t)mOut.data();
1126 
1127     // This is what we'll read.
1128     if (doReceive && needRead) {
1129         bwr.read_size = mIn.dataCapacity();
1130         bwr.read_buffer = (uintptr_t)mIn.data();
1131     } else {
1132         bwr.read_size = 0;
1133         bwr.read_buffer = 0;
1134     }
1135 
1136     IF_LOG_COMMANDS() {
1137         std::ostringstream logStream;
1138         if (outAvail != 0) {
1139             logStream << "Sending commands to driver: ";
1140             const void* cmds = (const void*)bwr.write_buffer;
1141             const void* end = ((const uint8_t*)cmds) + bwr.write_size;
1142             logStream << "\t" << HexDump(cmds, bwr.write_size) << "\n";
1143             while (cmds < end) cmds = printCommand(logStream, cmds);
1144         }
1145         logStream << "Size of receive buffer: " << bwr.read_size << ", needRead: " << needRead
1146                   << ", doReceive: " << doReceive << "\n";
1147 
1148         std::string message = logStream.str();
1149         ALOGI("%s", message.c_str());
1150     }
1151 
1152     // Return immediately if there is nothing to do.
1153     if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
1154 
1155     bwr.write_consumed = 0;
1156     bwr.read_consumed = 0;
1157     status_t err;
1158     do {
1159         IF_LOG_COMMANDS() {
1160             std::ostringstream logStream;
1161             logStream << "About to read/write, write size = " << mOut.dataSize() << "\n";
1162             std::string message = logStream.str();
1163             ALOGI("%s", message.c_str());
1164         }
1165 #if defined(__ANDROID__)
1166         if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
1167             err = NO_ERROR;
1168         else
1169             err = -errno;
1170 #else
1171         err = INVALID_OPERATION;
1172 #endif
1173         if (mProcess->mDriverFD < 0) {
1174             err = -EBADF;
1175         }
1176         IF_LOG_COMMANDS() {
1177             std::ostringstream logStream;
1178             logStream << "Finished read/write, write size = " << mOut.dataSize() << "\n";
1179             std::string message = logStream.str();
1180             ALOGI("%s", message.c_str());
1181         }
1182     } while (err == -EINTR);
1183 
1184     IF_LOG_COMMANDS() {
1185         std::ostringstream logStream;
1186         logStream << "Our err: " << (void*)(intptr_t)err
1187                   << ", write consumed: " << bwr.write_consumed << " (of " << mOut.dataSize()
1188                   << "), read consumed: " << bwr.read_consumed << "\n";
1189         std::string message = logStream.str();
1190         ALOGI("%s", message.c_str());
1191     }
1192 
1193     if (err >= NO_ERROR) {
1194         if (bwr.write_consumed > 0) {
1195             if (bwr.write_consumed < mOut.dataSize())
1196                 LOG_ALWAYS_FATAL("Driver did not consume write buffer. "
1197                                  "err: %s consumed: %zu of %zu",
1198                                  statusToString(err).c_str(),
1199                                  (size_t)bwr.write_consumed,
1200                                  mOut.dataSize());
1201             else {
1202                 mOut.setDataSize(0);
1203                 processPostWriteDerefs();
1204             }
1205         }
1206         if (bwr.read_consumed > 0) {
1207             mIn.setDataSize(bwr.read_consumed);
1208             mIn.setDataPosition(0);
1209         }
1210         IF_LOG_COMMANDS() {
1211             std::ostringstream logStream;
1212             logStream << "Remaining data size: " << mOut.dataSize() << "\n";
1213             logStream << "Received commands from driver: ";
1214             const void* cmds = mIn.data();
1215             const void* end = mIn.data() + mIn.dataSize();
1216             logStream << "\t" << HexDump(cmds, mIn.dataSize()) << "\n";
1217             while (cmds < end) cmds = printReturnCommand(logStream, cmds);
1218             std::string message = logStream.str();
1219             ALOGI("%s", message.c_str());
1220         }
1221         return NO_ERROR;
1222     }
1223 
1224     ALOGE_IF(mProcess->mDriverFD >= 0,
1225              "Driver returned error (%s). This is a bug in either libbinder or the driver. This "
1226              "thread's connection to %s will no longer work.",
1227              statusToString(err).c_str(), mProcess->mDriverName.c_str());
1228     return err;
1229 }
1230 
writeTransactionData(int32_t cmd,uint32_t binderFlags,int32_t handle,uint32_t code,const Parcel & data,status_t * statusBuffer)1231 status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
1232     int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
1233 {
1234     binder_transaction_data tr;
1235 
1236     tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
1237     tr.target.handle = handle;
1238     tr.code = code;
1239     tr.flags = binderFlags;
1240     tr.cookie = 0;
1241     tr.sender_pid = 0;
1242     tr.sender_euid = 0;
1243 
1244     const status_t err = data.errorCheck();
1245     if (err == NO_ERROR) {
1246         tr.data_size = data.ipcDataSize();
1247         tr.data.ptr.buffer = data.ipcData();
1248         tr.offsets_size = data.ipcObjectsCount()*sizeof(binder_size_t);
1249         tr.data.ptr.offsets = data.ipcObjects();
1250     } else if (statusBuffer) {
1251         tr.flags |= TF_STATUS_CODE;
1252         *statusBuffer = err;
1253         tr.data_size = sizeof(status_t);
1254         tr.data.ptr.buffer = reinterpret_cast<uintptr_t>(statusBuffer);
1255         tr.offsets_size = 0;
1256         tr.data.ptr.offsets = 0;
1257     } else {
1258         return (mLastError = err);
1259     }
1260 
1261     mOut.writeInt32(cmd);
1262     mOut.write(&tr, sizeof(tr));
1263 
1264     return NO_ERROR;
1265 }
1266 
1267 sp<BBinder> the_context_object;
1268 
setTheContextObject(const sp<BBinder> & obj)1269 void IPCThreadState::setTheContextObject(const sp<BBinder>& obj)
1270 {
1271     the_context_object = obj;
1272 }
1273 
executeCommand(int32_t cmd)1274 status_t IPCThreadState::executeCommand(int32_t cmd)
1275 {
1276     BBinder* obj;
1277     RefBase::weakref_type* refs;
1278     status_t result = NO_ERROR;
1279 
1280     switch ((uint32_t)cmd) {
1281     case BR_ERROR:
1282         result = mIn.readInt32();
1283         break;
1284 
1285     case BR_OK:
1286         break;
1287 
1288     case BR_ACQUIRE:
1289         refs = (RefBase::weakref_type*)mIn.readPointer();
1290         obj = (BBinder*)mIn.readPointer();
1291         ALOG_ASSERT(refs->refBase() == obj,
1292                    "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
1293                    refs, obj, refs->refBase());
1294         obj->incStrong(mProcess.get());
1295         IF_LOG_REMOTEREFS() {
1296             LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
1297             obj->printRefs();
1298         }
1299         mOut.writeInt32(BC_ACQUIRE_DONE);
1300         mOut.writePointer((uintptr_t)refs);
1301         mOut.writePointer((uintptr_t)obj);
1302         break;
1303 
1304     case BR_RELEASE:
1305         refs = (RefBase::weakref_type*)mIn.readPointer();
1306         obj = (BBinder*)mIn.readPointer();
1307         ALOG_ASSERT(refs->refBase() == obj,
1308                    "BR_RELEASE: object %p does not match cookie %p (expected %p)",
1309                    refs, obj, refs->refBase());
1310         IF_LOG_REMOTEREFS() {
1311             LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
1312             obj->printRefs();
1313         }
1314         mPendingStrongDerefs.push(obj);
1315         break;
1316 
1317     case BR_INCREFS:
1318         refs = (RefBase::weakref_type*)mIn.readPointer();
1319         obj = (BBinder*)mIn.readPointer();
1320         refs->incWeak(mProcess.get());
1321         mOut.writeInt32(BC_INCREFS_DONE);
1322         mOut.writePointer((uintptr_t)refs);
1323         mOut.writePointer((uintptr_t)obj);
1324         break;
1325 
1326     case BR_DECREFS:
1327         refs = (RefBase::weakref_type*)mIn.readPointer();
1328         // NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores)
1329         obj = (BBinder*)mIn.readPointer(); // consume
1330         // NOTE: This assertion is not valid, because the object may no
1331         // longer exist (thus the (BBinder*)cast above resulting in a different
1332         // memory address).
1333         //ALOG_ASSERT(refs->refBase() == obj,
1334         //           "BR_DECREFS: object %p does not match cookie %p (expected %p)",
1335         //           refs, obj, refs->refBase());
1336         mPendingWeakDerefs.push(refs);
1337         break;
1338 
1339     case BR_ATTEMPT_ACQUIRE:
1340         refs = (RefBase::weakref_type*)mIn.readPointer();
1341         obj = (BBinder*)mIn.readPointer();
1342 
1343         {
1344             const bool success = refs->attemptIncStrong(mProcess.get());
1345             ALOG_ASSERT(success && refs->refBase() == obj,
1346                        "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
1347                        refs, obj, refs->refBase());
1348 
1349             mOut.writeInt32(BC_ACQUIRE_RESULT);
1350             mOut.writeInt32((int32_t)success);
1351         }
1352         break;
1353 
1354     case BR_TRANSACTION_SEC_CTX:
1355     case BR_TRANSACTION:
1356         {
1357             binder_transaction_data_secctx tr_secctx;
1358             binder_transaction_data& tr = tr_secctx.transaction_data;
1359 
1360             if (cmd == (int) BR_TRANSACTION_SEC_CTX) {
1361                 result = mIn.read(&tr_secctx, sizeof(tr_secctx));
1362             } else {
1363                 result = mIn.read(&tr, sizeof(tr));
1364                 tr_secctx.secctx = 0;
1365             }
1366 
1367             ALOG_ASSERT(result == NO_ERROR,
1368                 "Not enough command data for brTRANSACTION");
1369             if (result != NO_ERROR) break;
1370 
1371             Parcel buffer;
1372             buffer.ipcSetDataReference(
1373                 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1374                 tr.data_size,
1375                 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1376                 tr.offsets_size/sizeof(binder_size_t), freeBuffer);
1377 
1378             const void* origServingStackPointer = mServingStackPointer;
1379             mServingStackPointer = __builtin_frame_address(0);
1380 
1381             const pid_t origPid = mCallingPid;
1382             const char* origSid = mCallingSid;
1383             const uid_t origUid = mCallingUid;
1384             const bool origHasExplicitIdentity = mHasExplicitIdentity;
1385             const int32_t origStrictModePolicy = mStrictModePolicy;
1386             const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
1387             const int32_t origWorkSource = mWorkSource;
1388             const bool origPropagateWorkSet = mPropagateWorkSource;
1389             // Calling work source will be set by Parcel#enforceInterface. Parcel#enforceInterface
1390             // is only guaranteed to be called for AIDL-generated stubs so we reset the work source
1391             // here to never propagate it.
1392             clearCallingWorkSource();
1393             clearPropagateWorkSource();
1394 
1395             mCallingPid = tr.sender_pid;
1396             mCallingSid = reinterpret_cast<const char*>(tr_secctx.secctx);
1397             mCallingUid = tr.sender_euid;
1398             mHasExplicitIdentity = false;
1399             mLastTransactionBinderFlags = tr.flags;
1400 
1401             // ALOGI(">>>> TRANSACT from pid %d sid %s uid %d\n", mCallingPid,
1402             //    (mCallingSid ? mCallingSid : "<N/A>"), mCallingUid);
1403 
1404             Parcel reply;
1405             status_t error;
1406             IF_LOG_TRANSACTIONS() {
1407                 std::ostringstream logStream;
1408                 logStream << "BR_TRANSACTION thr " << (void*)pthread_self() << " / obj "
1409                           << tr.target.ptr << " / code " << TypeCode(tr.code) << ": \t" << buffer
1410                           << "\n"
1411                           << "Data addr = " << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1412                           << ", offsets addr="
1413                           << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << "\n";
1414                 std::string message = logStream.str();
1415                 ALOGI("%s", message.c_str());
1416             }
1417             if (tr.target.ptr) {
1418                 // We only have a weak reference on the target object, so we must first try to
1419                 // safely acquire a strong reference before doing anything else with it.
1420                 if (reinterpret_cast<RefBase::weakref_type*>(
1421                         tr.target.ptr)->attemptIncStrong(this)) {
1422                     error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,
1423                             &reply, tr.flags);
1424                     reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);
1425                 } else {
1426                     error = UNKNOWN_TRANSACTION;
1427                 }
1428 
1429             } else {
1430                 error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
1431             }
1432 
1433             //ALOGI("<<<< TRANSACT from pid %d restore pid %d sid %s uid %d\n",
1434             //     mCallingPid, origPid, (origSid ? origSid : "<N/A>"), origUid);
1435 
1436             if ((tr.flags & TF_ONE_WAY) == 0) {
1437                 LOG_ONEWAY("Sending reply to %d!", mCallingPid);
1438                 if (error < NO_ERROR) reply.setError(error);
1439 
1440                 // b/238777741: clear buffer before we send the reply.
1441                 // Otherwise, there is a race where the client may
1442                 // receive the reply and send another transaction
1443                 // here and the space used by this transaction won't
1444                 // be freed for the client.
1445                 buffer.setDataSize(0);
1446 
1447                 constexpr uint32_t kForwardReplyFlags = TF_CLEAR_BUF;
1448                 sendReply(reply, (tr.flags & kForwardReplyFlags));
1449             } else {
1450                 if (error != OK) {
1451                     std::ostringstream logStream;
1452                     logStream << "oneway function results for code " << tr.code << " on binder at "
1453                               << reinterpret_cast<void*>(tr.target.ptr)
1454                               << " will be dropped but finished with status "
1455                               << statusToString(error);
1456 
1457                     // ideally we could log this even when error == OK, but it
1458                     // causes too much logspam because some manually-written
1459                     // interfaces have clients that call methods which always
1460                     // write results, sometimes as oneway methods.
1461                     if (reply.dataSize() != 0) {
1462                         logStream << " and reply parcel size " << reply.dataSize();
1463                     }
1464                     std::string message = logStream.str();
1465                     ALOGI("%s", message.c_str());
1466                 }
1467                 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1468             }
1469 
1470             mServingStackPointer = origServingStackPointer;
1471             mCallingPid = origPid;
1472             mCallingSid = origSid;
1473             mCallingUid = origUid;
1474             mHasExplicitIdentity = origHasExplicitIdentity;
1475             mStrictModePolicy = origStrictModePolicy;
1476             mLastTransactionBinderFlags = origTransactionBinderFlags;
1477             mWorkSource = origWorkSource;
1478             mPropagateWorkSource = origPropagateWorkSet;
1479 
1480             IF_LOG_TRANSACTIONS() {
1481                 std::ostringstream logStream;
1482                 logStream << "BC_REPLY thr " << (void*)pthread_self() << " / obj " << tr.target.ptr
1483                           << ": \t" << reply << "\n";
1484                 std::string message = logStream.str();
1485                 ALOGI("%s", message.c_str());
1486             }
1487 
1488         }
1489         break;
1490 
1491     case BR_DEAD_BINDER:
1492         {
1493             BpBinder *proxy = (BpBinder*)mIn.readPointer();
1494             proxy->sendObituary();
1495             mOut.writeInt32(BC_DEAD_BINDER_DONE);
1496             mOut.writePointer((uintptr_t)proxy);
1497         } break;
1498 
1499     case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1500         {
1501             BpBinder *proxy = (BpBinder*)mIn.readPointer();
1502             proxy->getWeakRefs()->decWeak(proxy);
1503         } break;
1504 
1505     case BR_FINISHED:
1506         result = TIMED_OUT;
1507         break;
1508 
1509     case BR_NOOP:
1510         break;
1511 
1512     case BR_SPAWN_LOOPER:
1513         mProcess->spawnPooledThread(false);
1514         break;
1515 
1516     default:
1517         ALOGE("*** BAD COMMAND %d received from Binder driver\n", cmd);
1518         result = UNKNOWN_ERROR;
1519         break;
1520     }
1521 
1522     if (result != NO_ERROR) {
1523         mLastError = result;
1524     }
1525 
1526     return result;
1527 }
1528 
getServingStackPointer() const1529 const void* IPCThreadState::getServingStackPointer() const {
1530      return mServingStackPointer;
1531 }
1532 
threadDestructor(void * st)1533 void IPCThreadState::threadDestructor(void *st)
1534 {
1535         IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1536         if (self) {
1537                 self->flushCommands();
1538 #if defined(__ANDROID__)
1539         if (self->mProcess->mDriverFD >= 0) {
1540             ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1541         }
1542 #endif
1543                 delete self;
1544         }
1545 }
1546 
getProcessFreezeInfo(pid_t pid,uint32_t * sync_received,uint32_t * async_received)1547 status_t IPCThreadState::getProcessFreezeInfo(pid_t pid, uint32_t *sync_received,
1548                                               uint32_t *async_received)
1549 {
1550     int ret = 0;
1551     binder_frozen_status_info info = {};
1552     info.pid = pid;
1553 
1554 #if defined(__ANDROID__)
1555     if (ioctl(self()->mProcess->mDriverFD, BINDER_GET_FROZEN_INFO, &info) < 0)
1556         ret = -errno;
1557 #endif
1558     *sync_received = info.sync_recv;
1559     *async_received = info.async_recv;
1560 
1561     return ret;
1562 }
1563 
freeze(pid_t pid,bool enable,uint32_t timeout_ms)1564 status_t IPCThreadState::freeze(pid_t pid, bool enable, uint32_t timeout_ms) {
1565     struct binder_freeze_info info;
1566     int ret = 0;
1567 
1568     info.pid = pid;
1569     info.enable = enable;
1570     info.timeout_ms = timeout_ms;
1571 
1572 
1573 #if defined(__ANDROID__)
1574     if (ioctl(self()->mProcess->mDriverFD, BINDER_FREEZE, &info) < 0)
1575         ret = -errno;
1576 #endif
1577 
1578     //
1579     // ret==-EAGAIN indicates that transactions have not drained.
1580     // Call again to poll for completion.
1581     //
1582     return ret;
1583 }
1584 
logExtendedError()1585 void IPCThreadState::logExtendedError() {
1586     struct binder_extended_error ee = {.command = BR_OK};
1587 
1588     if (!ProcessState::isDriverFeatureEnabled(ProcessState::DriverFeature::EXTENDED_ERROR))
1589         return;
1590 
1591 #if defined(__ANDROID__)
1592     if (ioctl(self()->mProcess->mDriverFD, BINDER_GET_EXTENDED_ERROR, &ee) < 0) {
1593         ALOGE("Failed to get extended error: %s", strerror(errno));
1594         return;
1595     }
1596 #endif
1597 
1598     ALOGE_IF(ee.command != BR_OK, "Binder transaction failure: %d/%d/%d",
1599              ee.id, ee.command, ee.param);
1600 }
1601 
freeBuffer(const uint8_t * data,size_t,const binder_size_t *,size_t)1602 void IPCThreadState::freeBuffer(const uint8_t* data, size_t /*dataSize*/,
1603                                 const binder_size_t* /*objects*/, size_t /*objectsSize*/) {
1604     //ALOGI("Freeing parcel %p", &parcel);
1605     IF_LOG_COMMANDS() {
1606         std::ostringstream logStream;
1607         logStream << "Writing BC_FREE_BUFFER for " << data << "\n";
1608         std::string message = logStream.str();
1609         ALOGI("%s", message.c_str());
1610     }
1611     ALOG_ASSERT(data != NULL, "Called with NULL data");
1612     IPCThreadState* state = self();
1613     state->mOut.writeInt32(BC_FREE_BUFFER);
1614     state->mOut.writePointer((uintptr_t)data);
1615     state->flushIfNeeded();
1616 }
1617 
1618 } // namespace android
1619