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