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