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