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