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