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 <private/binder/binder_module.h>
33
34 #include <atomic>
35 #include <errno.h>
36 #include <inttypes.h>
37 #include <pthread.h>
38 #include <sched.h>
39 #include <signal.h>
40 #include <stdio.h>
41 #include <sys/ioctl.h>
42 #include <sys/resource.h>
43 #include <unistd.h>
44
45 #include "Static.h"
46
47 #if LOG_NDEBUG
48
49 #define IF_LOG_TRANSACTIONS() if (false)
50 #define IF_LOG_COMMANDS() if (false)
51 #define LOG_REMOTEREFS(...)
52 #define IF_LOG_REMOTEREFS() if (false)
53
54 #define LOG_THREADPOOL(...)
55 #define LOG_ONEWAY(...)
56
57 #else
58
59 #define IF_LOG_TRANSACTIONS() IF_ALOG(LOG_VERBOSE, "transact")
60 #define IF_LOG_COMMANDS() IF_ALOG(LOG_VERBOSE, "ipc")
61 #define LOG_REMOTEREFS(...) ALOG(LOG_DEBUG, "remoterefs", __VA_ARGS__)
62 #define IF_LOG_REMOTEREFS() IF_ALOG(LOG_DEBUG, "remoterefs")
63 #define LOG_THREADPOOL(...) ALOG(LOG_DEBUG, "threadpool", __VA_ARGS__)
64 #define LOG_ONEWAY(...) ALOG(LOG_DEBUG, "ipc", __VA_ARGS__)
65
66 #endif
67
68 // ---------------------------------------------------------------------------
69
70 namespace android {
71
72 // Static const and functions will be optimized out if not used,
73 // when LOG_NDEBUG and references in IF_LOG_COMMANDS() are optimized out.
74 static const char *kReturnStrings[] = {
75 "BR_ERROR",
76 "BR_OK",
77 "BR_TRANSACTION",
78 "BR_REPLY",
79 "BR_ACQUIRE_RESULT",
80 "BR_DEAD_REPLY",
81 "BR_TRANSACTION_COMPLETE",
82 "BR_INCREFS",
83 "BR_ACQUIRE",
84 "BR_RELEASE",
85 "BR_DECREFS",
86 "BR_ATTEMPT_ACQUIRE",
87 "BR_NOOP",
88 "BR_SPAWN_LOOPER",
89 "BR_FINISHED",
90 "BR_DEAD_BINDER",
91 "BR_CLEAR_DEATH_NOTIFICATION_DONE",
92 "BR_FAILED_REPLY",
93 "BR_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*)(long)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*)(long)(*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*)(long)b << " (cookie " << (void*)(long)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*)(long)b << " (cookie " << (void*)(long)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*)(long)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*)(long)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*)(long)b << " (cookie " << (void*)(long)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*)(long)c << ")";
264 } break;
265
266 case BC_DEAD_BINDER_DONE: {
267 const int32_t c = *cmd++;
268 out << ": death cookie " << (void*)(long)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
process()354 sp<ProcessState> IPCThreadState::process()
355 {
356 return mProcess;
357 }
358
clearLastError()359 status_t IPCThreadState::clearLastError()
360 {
361 const status_t err = mLastError;
362 mLastError = NO_ERROR;
363 return err;
364 }
365
getCallingPid() const366 pid_t IPCThreadState::getCallingPid() const
367 {
368 return mCallingPid;
369 }
370
getCallingSid() const371 const char* IPCThreadState::getCallingSid() const
372 {
373 return mCallingSid;
374 }
375
getCallingUid() const376 uid_t IPCThreadState::getCallingUid() const
377 {
378 return mCallingUid;
379 }
380
clearCallingIdentity()381 int64_t IPCThreadState::clearCallingIdentity()
382 {
383 // ignore mCallingSid for legacy reasons
384 int64_t token = ((int64_t)mCallingUid<<32) | mCallingPid;
385 clearCaller();
386 return token;
387 }
388
setStrictModePolicy(int32_t policy)389 void IPCThreadState::setStrictModePolicy(int32_t policy)
390 {
391 mStrictModePolicy = policy;
392 }
393
getStrictModePolicy() const394 int32_t IPCThreadState::getStrictModePolicy() const
395 {
396 return mStrictModePolicy;
397 }
398
setCallingWorkSourceUid(uid_t uid)399 int64_t IPCThreadState::setCallingWorkSourceUid(uid_t uid)
400 {
401 int64_t token = setCallingWorkSourceUidWithoutPropagation(uid);
402 mPropagateWorkSource = true;
403 return token;
404 }
405
setCallingWorkSourceUidWithoutPropagation(uid_t uid)406 int64_t IPCThreadState::setCallingWorkSourceUidWithoutPropagation(uid_t uid)
407 {
408 const int64_t propagatedBit = ((int64_t)mPropagateWorkSource) << kWorkSourcePropagatedBitIndex;
409 int64_t token = propagatedBit | mWorkSource;
410 mWorkSource = uid;
411 return token;
412 }
413
clearPropagateWorkSource()414 void IPCThreadState::clearPropagateWorkSource()
415 {
416 mPropagateWorkSource = false;
417 }
418
shouldPropagateWorkSource() const419 bool IPCThreadState::shouldPropagateWorkSource() const
420 {
421 return mPropagateWorkSource;
422 }
423
getCallingWorkSourceUid() const424 uid_t IPCThreadState::getCallingWorkSourceUid() const
425 {
426 return mWorkSource;
427 }
428
clearCallingWorkSource()429 int64_t IPCThreadState::clearCallingWorkSource()
430 {
431 return setCallingWorkSourceUid(kUnsetWorkSource);
432 }
433
restoreCallingWorkSource(int64_t token)434 void IPCThreadState::restoreCallingWorkSource(int64_t token)
435 {
436 uid_t uid = (int)token;
437 setCallingWorkSourceUidWithoutPropagation(uid);
438 mPropagateWorkSource = ((token >> kWorkSourcePropagatedBitIndex) & 1) == 1;
439 }
440
setLastTransactionBinderFlags(int32_t flags)441 void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
442 {
443 mLastTransactionBinderFlags = flags;
444 }
445
getLastTransactionBinderFlags() const446 int32_t IPCThreadState::getLastTransactionBinderFlags() const
447 {
448 return mLastTransactionBinderFlags;
449 }
450
restoreCallingIdentity(int64_t token)451 void IPCThreadState::restoreCallingIdentity(int64_t token)
452 {
453 mCallingUid = (int)(token>>32);
454 mCallingSid = nullptr; // not enough data to restore
455 mCallingPid = (int)token;
456 }
457
clearCaller()458 void IPCThreadState::clearCaller()
459 {
460 mCallingPid = getpid();
461 mCallingSid = nullptr; // expensive to lookup
462 mCallingUid = getuid();
463 }
464
flushCommands()465 void IPCThreadState::flushCommands()
466 {
467 if (mProcess->mDriverFD < 0)
468 return;
469 talkWithDriver(false);
470 // The flush could have caused post-write refcount decrements to have
471 // been executed, which in turn could result in BC_RELEASE/BC_DECREFS
472 // being queued in mOut. So flush again, if we need to.
473 if (mOut.dataSize() > 0) {
474 talkWithDriver(false);
475 }
476 if (mOut.dataSize() > 0) {
477 ALOGW("mOut.dataSize() > 0 after flushCommands()");
478 }
479 }
480
blockUntilThreadAvailable()481 void IPCThreadState::blockUntilThreadAvailable()
482 {
483 pthread_mutex_lock(&mProcess->mThreadCountLock);
484 while (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads) {
485 ALOGW("Waiting for thread to be free. mExecutingThreadsCount=%lu mMaxThreads=%lu\n",
486 static_cast<unsigned long>(mProcess->mExecutingThreadsCount),
487 static_cast<unsigned long>(mProcess->mMaxThreads));
488 pthread_cond_wait(&mProcess->mThreadCountDecrement, &mProcess->mThreadCountLock);
489 }
490 pthread_mutex_unlock(&mProcess->mThreadCountLock);
491 }
492
getAndExecuteCommand()493 status_t IPCThreadState::getAndExecuteCommand()
494 {
495 status_t result;
496 int32_t cmd;
497
498 result = talkWithDriver();
499 if (result >= NO_ERROR) {
500 size_t IN = mIn.dataAvail();
501 if (IN < sizeof(int32_t)) return result;
502 cmd = mIn.readInt32();
503 IF_LOG_COMMANDS() {
504 alog << "Processing top-level Command: "
505 << getReturnString(cmd) << endl;
506 }
507
508 pthread_mutex_lock(&mProcess->mThreadCountLock);
509 mProcess->mExecutingThreadsCount++;
510 if (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads &&
511 mProcess->mStarvationStartTimeMs == 0) {
512 mProcess->mStarvationStartTimeMs = uptimeMillis();
513 }
514 pthread_mutex_unlock(&mProcess->mThreadCountLock);
515
516 result = executeCommand(cmd);
517
518 pthread_mutex_lock(&mProcess->mThreadCountLock);
519 mProcess->mExecutingThreadsCount--;
520 if (mProcess->mExecutingThreadsCount < mProcess->mMaxThreads &&
521 mProcess->mStarvationStartTimeMs != 0) {
522 int64_t starvationTimeMs = uptimeMillis() - mProcess->mStarvationStartTimeMs;
523 if (starvationTimeMs > 100) {
524 ALOGE("binder thread pool (%zu threads) starved for %" PRId64 " ms",
525 mProcess->mMaxThreads, starvationTimeMs);
526 }
527 mProcess->mStarvationStartTimeMs = 0;
528 }
529 pthread_cond_broadcast(&mProcess->mThreadCountDecrement);
530 pthread_mutex_unlock(&mProcess->mThreadCountLock);
531 }
532
533 return result;
534 }
535
536 // When we've cleared the incoming command queue, process any pending derefs
processPendingDerefs()537 void IPCThreadState::processPendingDerefs()
538 {
539 if (mIn.dataPosition() >= mIn.dataSize()) {
540 /*
541 * The decWeak()/decStrong() calls may cause a destructor to run,
542 * which in turn could have initiated an outgoing transaction,
543 * which in turn could cause us to add to the pending refs
544 * vectors; so instead of simply iterating, loop until they're empty.
545 *
546 * We do this in an outer loop, because calling decStrong()
547 * may result in something being added to mPendingWeakDerefs,
548 * which could be delayed until the next incoming command
549 * from the driver if we don't process it now.
550 */
551 while (mPendingWeakDerefs.size() > 0 || mPendingStrongDerefs.size() > 0) {
552 while (mPendingWeakDerefs.size() > 0) {
553 RefBase::weakref_type* refs = mPendingWeakDerefs[0];
554 mPendingWeakDerefs.removeAt(0);
555 refs->decWeak(mProcess.get());
556 }
557
558 if (mPendingStrongDerefs.size() > 0) {
559 // We don't use while() here because we don't want to re-order
560 // strong and weak decs at all; if this decStrong() causes both a
561 // decWeak() and a decStrong() to be queued, we want to process
562 // the decWeak() first.
563 BBinder* obj = mPendingStrongDerefs[0];
564 mPendingStrongDerefs.removeAt(0);
565 obj->decStrong(mProcess.get());
566 }
567 }
568 }
569 }
570
processPostWriteDerefs()571 void IPCThreadState::processPostWriteDerefs()
572 {
573 for (size_t i = 0; i < mPostWriteWeakDerefs.size(); i++) {
574 RefBase::weakref_type* refs = mPostWriteWeakDerefs[i];
575 refs->decWeak(mProcess.get());
576 }
577 mPostWriteWeakDerefs.clear();
578
579 for (size_t i = 0; i < mPostWriteStrongDerefs.size(); i++) {
580 RefBase* obj = mPostWriteStrongDerefs[i];
581 obj->decStrong(mProcess.get());
582 }
583 mPostWriteStrongDerefs.clear();
584 }
585
joinThreadPool(bool isMain)586 void IPCThreadState::joinThreadPool(bool isMain)
587 {
588 LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
589
590 mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
591
592 status_t result;
593 do {
594 processPendingDerefs();
595 // now get the next command to be processed, waiting if necessary
596 result = getAndExecuteCommand();
597
598 if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
599 LOG_ALWAYS_FATAL("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
600 mProcess->mDriverFD, result);
601 }
602
603 // Let this thread exit the thread pool if it is no longer
604 // needed and it is not the main process thread.
605 if(result == TIMED_OUT && !isMain) {
606 break;
607 }
608 } while (result != -ECONNREFUSED && result != -EBADF);
609
610 LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%d\n",
611 (void*)pthread_self(), getpid(), result);
612
613 mOut.writeInt32(BC_EXIT_LOOPER);
614 talkWithDriver(false);
615 }
616
setupPolling(int * fd)617 int IPCThreadState::setupPolling(int* fd)
618 {
619 if (mProcess->mDriverFD < 0) {
620 return -EBADF;
621 }
622
623 mOut.writeInt32(BC_ENTER_LOOPER);
624 *fd = mProcess->mDriverFD;
625 return 0;
626 }
627
handlePolledCommands()628 status_t IPCThreadState::handlePolledCommands()
629 {
630 status_t result;
631
632 do {
633 result = getAndExecuteCommand();
634 } while (mIn.dataPosition() < mIn.dataSize());
635
636 processPendingDerefs();
637 flushCommands();
638 return result;
639 }
640
stopProcess(bool)641 void IPCThreadState::stopProcess(bool /*immediate*/)
642 {
643 //ALOGI("**** STOPPING PROCESS");
644 flushCommands();
645 int fd = mProcess->mDriverFD;
646 mProcess->mDriverFD = -1;
647 close(fd);
648 //kill(getpid(), SIGKILL);
649 }
650
transact(int32_t handle,uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)651 status_t IPCThreadState::transact(int32_t handle,
652 uint32_t code, const Parcel& data,
653 Parcel* reply, uint32_t flags)
654 {
655 status_t err;
656
657 flags |= TF_ACCEPT_FDS;
658
659 IF_LOG_TRANSACTIONS() {
660 TextOutput::Bundle _b(alog);
661 alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
662 << handle << " / code " << TypeCode(code) << ": "
663 << indent << data << dedent << endl;
664 }
665
666 LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
667 (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
668 err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, nullptr);
669
670 if (err != NO_ERROR) {
671 if (reply) reply->setError(err);
672 return (mLastError = err);
673 }
674
675 if ((flags & TF_ONE_WAY) == 0) {
676 if (UNLIKELY(mCallRestriction != ProcessState::CallRestriction::NONE)) {
677 if (mCallRestriction == ProcessState::CallRestriction::ERROR_IF_NOT_ONEWAY) {
678 ALOGE("Process making non-oneway call (code: %u) but is restricted.", code);
679 CallStack::logStack("non-oneway call", CallStack::getCurrent(10).get(),
680 ANDROID_LOG_ERROR);
681 } else /* FATAL_IF_NOT_ONEWAY */ {
682 LOG_ALWAYS_FATAL("Process may not make oneway calls (code: %u).", code);
683 }
684 }
685
686 #if 0
687 if (code == 4) { // relayout
688 ALOGI(">>>>>> CALLING transaction 4");
689 } else {
690 ALOGI(">>>>>> CALLING transaction %d", code);
691 }
692 #endif
693 if (reply) {
694 err = waitForResponse(reply);
695 } else {
696 Parcel fakeReply;
697 err = waitForResponse(&fakeReply);
698 }
699 #if 0
700 if (code == 4) { // relayout
701 ALOGI("<<<<<< RETURNING transaction 4");
702 } else {
703 ALOGI("<<<<<< RETURNING transaction %d", code);
704 }
705 #endif
706
707 IF_LOG_TRANSACTIONS() {
708 TextOutput::Bundle _b(alog);
709 alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
710 << handle << ": ";
711 if (reply) alog << indent << *reply << dedent << endl;
712 else alog << "(none requested)" << endl;
713 }
714 } else {
715 err = waitForResponse(nullptr, nullptr);
716 }
717
718 return err;
719 }
720
incStrongHandle(int32_t handle,BpBinder * proxy)721 void IPCThreadState::incStrongHandle(int32_t handle, BpBinder *proxy)
722 {
723 LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
724 mOut.writeInt32(BC_ACQUIRE);
725 mOut.writeInt32(handle);
726 // Create a temp reference until the driver has handled this command.
727 proxy->incStrong(mProcess.get());
728 mPostWriteStrongDerefs.push(proxy);
729 }
730
decStrongHandle(int32_t handle)731 void IPCThreadState::decStrongHandle(int32_t handle)
732 {
733 LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
734 mOut.writeInt32(BC_RELEASE);
735 mOut.writeInt32(handle);
736 }
737
incWeakHandle(int32_t handle,BpBinder * proxy)738 void IPCThreadState::incWeakHandle(int32_t handle, BpBinder *proxy)
739 {
740 LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
741 mOut.writeInt32(BC_INCREFS);
742 mOut.writeInt32(handle);
743 // Create a temp reference until the driver has handled this command.
744 proxy->getWeakRefs()->incWeak(mProcess.get());
745 mPostWriteWeakDerefs.push(proxy->getWeakRefs());
746 }
747
decWeakHandle(int32_t handle)748 void IPCThreadState::decWeakHandle(int32_t handle)
749 {
750 LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
751 mOut.writeInt32(BC_DECREFS);
752 mOut.writeInt32(handle);
753 }
754
attemptIncStrongHandle(int32_t handle)755 status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
756 {
757 #if HAS_BC_ATTEMPT_ACQUIRE
758 LOG_REMOTEREFS("IPCThreadState::attemptIncStrongHandle(%d)\n", handle);
759 mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
760 mOut.writeInt32(0); // xxx was thread priority
761 mOut.writeInt32(handle);
762 status_t result = UNKNOWN_ERROR;
763
764 waitForResponse(NULL, &result);
765
766 #if LOG_REFCOUNTS
767 ALOGV("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
768 handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
769 #endif
770
771 return result;
772 #else
773 (void)handle;
774 ALOGE("%s(%d): Not supported\n", __func__, handle);
775 return INVALID_OPERATION;
776 #endif
777 }
778
expungeHandle(int32_t handle,IBinder * binder)779 void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
780 {
781 #if LOG_REFCOUNTS
782 ALOGV("IPCThreadState::expungeHandle(%ld)\n", handle);
783 #endif
784 self()->mProcess->expungeHandle(handle, binder); // NOLINT
785 }
786
requestDeathNotification(int32_t handle,BpBinder * proxy)787 status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
788 {
789 mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
790 mOut.writeInt32((int32_t)handle);
791 mOut.writePointer((uintptr_t)proxy);
792 return NO_ERROR;
793 }
794
clearDeathNotification(int32_t handle,BpBinder * proxy)795 status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
796 {
797 mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
798 mOut.writeInt32((int32_t)handle);
799 mOut.writePointer((uintptr_t)proxy);
800 return NO_ERROR;
801 }
802
IPCThreadState()803 IPCThreadState::IPCThreadState()
804 : mProcess(ProcessState::self()),
805 mServingStackPointer(nullptr),
806 mWorkSource(kUnsetWorkSource),
807 mPropagateWorkSource(false),
808 mStrictModePolicy(0),
809 mLastTransactionBinderFlags(0),
810 mCallRestriction(mProcess->mCallRestriction)
811 {
812 pthread_setspecific(gTLS, this);
813 clearCaller();
814 mIn.setDataCapacity(256);
815 mOut.setDataCapacity(256);
816 }
817
~IPCThreadState()818 IPCThreadState::~IPCThreadState()
819 {
820 }
821
sendReply(const Parcel & reply,uint32_t flags)822 status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
823 {
824 status_t err;
825 status_t statusBuffer;
826 err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
827 if (err < NO_ERROR) return err;
828
829 return waitForResponse(nullptr, nullptr);
830 }
831
waitForResponse(Parcel * reply,status_t * acquireResult)832 status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
833 {
834 uint32_t cmd;
835 int32_t err;
836
837 while (1) {
838 if ((err=talkWithDriver()) < NO_ERROR) break;
839 err = mIn.errorCheck();
840 if (err < NO_ERROR) break;
841 if (mIn.dataAvail() == 0) continue;
842
843 cmd = (uint32_t)mIn.readInt32();
844
845 IF_LOG_COMMANDS() {
846 alog << "Processing waitForResponse Command: "
847 << getReturnString(cmd) << endl;
848 }
849
850 switch (cmd) {
851 case BR_TRANSACTION_COMPLETE:
852 if (!reply && !acquireResult) goto finish;
853 break;
854
855 case BR_DEAD_REPLY:
856 err = DEAD_OBJECT;
857 goto finish;
858
859 case BR_FAILED_REPLY:
860 err = FAILED_TRANSACTION;
861 goto finish;
862
863 case BR_FROZEN_REPLY:
864 err = FAILED_TRANSACTION;
865 goto finish;
866
867 case BR_ACQUIRE_RESULT:
868 {
869 ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
870 const int32_t result = mIn.readInt32();
871 if (!acquireResult) continue;
872 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
873 }
874 goto finish;
875
876 case BR_REPLY:
877 {
878 binder_transaction_data tr;
879 err = mIn.read(&tr, sizeof(tr));
880 ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
881 if (err != NO_ERROR) goto finish;
882
883 if (reply) {
884 if ((tr.flags & TF_STATUS_CODE) == 0) {
885 reply->ipcSetDataReference(
886 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
887 tr.data_size,
888 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
889 tr.offsets_size/sizeof(binder_size_t),
890 freeBuffer, this);
891 } else {
892 err = *reinterpret_cast<const status_t*>(tr.data.ptr.buffer);
893 freeBuffer(nullptr,
894 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
895 tr.data_size,
896 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
897 tr.offsets_size/sizeof(binder_size_t), this);
898 }
899 } else {
900 freeBuffer(nullptr,
901 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
902 tr.data_size,
903 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
904 tr.offsets_size/sizeof(binder_size_t), this);
905 continue;
906 }
907 }
908 goto finish;
909
910 default:
911 err = executeCommand(cmd);
912 if (err != NO_ERROR) goto finish;
913 break;
914 }
915 }
916
917 finish:
918 if (err != NO_ERROR) {
919 if (acquireResult) *acquireResult = err;
920 if (reply) reply->setError(err);
921 mLastError = err;
922 }
923
924 return err;
925 }
926
talkWithDriver(bool doReceive)927 status_t IPCThreadState::talkWithDriver(bool doReceive)
928 {
929 if (mProcess->mDriverFD < 0) {
930 return -EBADF;
931 }
932
933 binder_write_read bwr;
934
935 // Is the read buffer empty?
936 const bool needRead = mIn.dataPosition() >= mIn.dataSize();
937
938 // We don't want to write anything if we are still reading
939 // from data left in the input buffer and the caller
940 // has requested to read the next data.
941 const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
942
943 bwr.write_size = outAvail;
944 bwr.write_buffer = (uintptr_t)mOut.data();
945
946 // This is what we'll read.
947 if (doReceive && needRead) {
948 bwr.read_size = mIn.dataCapacity();
949 bwr.read_buffer = (uintptr_t)mIn.data();
950 } else {
951 bwr.read_size = 0;
952 bwr.read_buffer = 0;
953 }
954
955 IF_LOG_COMMANDS() {
956 TextOutput::Bundle _b(alog);
957 if (outAvail != 0) {
958 alog << "Sending commands to driver: " << indent;
959 const void* cmds = (const void*)bwr.write_buffer;
960 const void* end = ((const uint8_t*)cmds)+bwr.write_size;
961 alog << HexDump(cmds, bwr.write_size) << endl;
962 while (cmds < end) cmds = printCommand(alog, cmds);
963 alog << dedent;
964 }
965 alog << "Size of receive buffer: " << bwr.read_size
966 << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
967 }
968
969 // Return immediately if there is nothing to do.
970 if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
971
972 bwr.write_consumed = 0;
973 bwr.read_consumed = 0;
974 status_t err;
975 do {
976 IF_LOG_COMMANDS() {
977 alog << "About to read/write, write size = " << mOut.dataSize() << endl;
978 }
979 #if defined(__ANDROID__)
980 if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
981 err = NO_ERROR;
982 else
983 err = -errno;
984 #else
985 err = INVALID_OPERATION;
986 #endif
987 if (mProcess->mDriverFD < 0) {
988 err = -EBADF;
989 }
990 IF_LOG_COMMANDS() {
991 alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
992 }
993 } while (err == -EINTR);
994
995 IF_LOG_COMMANDS() {
996 alog << "Our err: " << (void*)(intptr_t)err << ", write consumed: "
997 << bwr.write_consumed << " (of " << mOut.dataSize()
998 << "), read consumed: " << bwr.read_consumed << endl;
999 }
1000
1001 if (err >= NO_ERROR) {
1002 if (bwr.write_consumed > 0) {
1003 if (bwr.write_consumed < mOut.dataSize())
1004 LOG_ALWAYS_FATAL("Driver did not consume write buffer. "
1005 "err: %s consumed: %zu of %zu",
1006 statusToString(err).c_str(),
1007 (size_t)bwr.write_consumed,
1008 mOut.dataSize());
1009 else {
1010 mOut.setDataSize(0);
1011 processPostWriteDerefs();
1012 }
1013 }
1014 if (bwr.read_consumed > 0) {
1015 mIn.setDataSize(bwr.read_consumed);
1016 mIn.setDataPosition(0);
1017 }
1018 IF_LOG_COMMANDS() {
1019 TextOutput::Bundle _b(alog);
1020 alog << "Remaining data size: " << mOut.dataSize() << endl;
1021 alog << "Received commands from driver: " << indent;
1022 const void* cmds = mIn.data();
1023 const void* end = mIn.data() + mIn.dataSize();
1024 alog << HexDump(cmds, mIn.dataSize()) << endl;
1025 while (cmds < end) cmds = printReturnCommand(alog, cmds);
1026 alog << dedent;
1027 }
1028 return NO_ERROR;
1029 }
1030
1031 return err;
1032 }
1033
writeTransactionData(int32_t cmd,uint32_t binderFlags,int32_t handle,uint32_t code,const Parcel & data,status_t * statusBuffer)1034 status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
1035 int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
1036 {
1037 binder_transaction_data tr;
1038
1039 tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
1040 tr.target.handle = handle;
1041 tr.code = code;
1042 tr.flags = binderFlags;
1043 tr.cookie = 0;
1044 tr.sender_pid = 0;
1045 tr.sender_euid = 0;
1046
1047 const status_t err = data.errorCheck();
1048 if (err == NO_ERROR) {
1049 tr.data_size = data.ipcDataSize();
1050 tr.data.ptr.buffer = data.ipcData();
1051 tr.offsets_size = data.ipcObjectsCount()*sizeof(binder_size_t);
1052 tr.data.ptr.offsets = data.ipcObjects();
1053 } else if (statusBuffer) {
1054 tr.flags |= TF_STATUS_CODE;
1055 *statusBuffer = err;
1056 tr.data_size = sizeof(status_t);
1057 tr.data.ptr.buffer = reinterpret_cast<uintptr_t>(statusBuffer);
1058 tr.offsets_size = 0;
1059 tr.data.ptr.offsets = 0;
1060 } else {
1061 return (mLastError = err);
1062 }
1063
1064 mOut.writeInt32(cmd);
1065 mOut.write(&tr, sizeof(tr));
1066
1067 return NO_ERROR;
1068 }
1069
1070 sp<BBinder> the_context_object;
1071
setTheContextObject(sp<BBinder> obj)1072 void IPCThreadState::setTheContextObject(sp<BBinder> obj)
1073 {
1074 the_context_object = obj;
1075 }
1076
executeCommand(int32_t cmd)1077 status_t IPCThreadState::executeCommand(int32_t cmd)
1078 {
1079 BBinder* obj;
1080 RefBase::weakref_type* refs;
1081 status_t result = NO_ERROR;
1082
1083 switch ((uint32_t)cmd) {
1084 case BR_ERROR:
1085 result = mIn.readInt32();
1086 break;
1087
1088 case BR_OK:
1089 break;
1090
1091 case BR_ACQUIRE:
1092 refs = (RefBase::weakref_type*)mIn.readPointer();
1093 obj = (BBinder*)mIn.readPointer();
1094 ALOG_ASSERT(refs->refBase() == obj,
1095 "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
1096 refs, obj, refs->refBase());
1097 obj->incStrong(mProcess.get());
1098 IF_LOG_REMOTEREFS() {
1099 LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
1100 obj->printRefs();
1101 }
1102 mOut.writeInt32(BC_ACQUIRE_DONE);
1103 mOut.writePointer((uintptr_t)refs);
1104 mOut.writePointer((uintptr_t)obj);
1105 break;
1106
1107 case BR_RELEASE:
1108 refs = (RefBase::weakref_type*)mIn.readPointer();
1109 obj = (BBinder*)mIn.readPointer();
1110 ALOG_ASSERT(refs->refBase() == obj,
1111 "BR_RELEASE: object %p does not match cookie %p (expected %p)",
1112 refs, obj, refs->refBase());
1113 IF_LOG_REMOTEREFS() {
1114 LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
1115 obj->printRefs();
1116 }
1117 mPendingStrongDerefs.push(obj);
1118 break;
1119
1120 case BR_INCREFS:
1121 refs = (RefBase::weakref_type*)mIn.readPointer();
1122 obj = (BBinder*)mIn.readPointer();
1123 refs->incWeak(mProcess.get());
1124 mOut.writeInt32(BC_INCREFS_DONE);
1125 mOut.writePointer((uintptr_t)refs);
1126 mOut.writePointer((uintptr_t)obj);
1127 break;
1128
1129 case BR_DECREFS:
1130 refs = (RefBase::weakref_type*)mIn.readPointer();
1131 obj = (BBinder*)mIn.readPointer();
1132 // NOTE: This assertion is not valid, because the object may no
1133 // longer exist (thus the (BBinder*)cast above resulting in a different
1134 // memory address).
1135 //ALOG_ASSERT(refs->refBase() == obj,
1136 // "BR_DECREFS: object %p does not match cookie %p (expected %p)",
1137 // refs, obj, refs->refBase());
1138 mPendingWeakDerefs.push(refs);
1139 break;
1140
1141 case BR_ATTEMPT_ACQUIRE:
1142 refs = (RefBase::weakref_type*)mIn.readPointer();
1143 obj = (BBinder*)mIn.readPointer();
1144
1145 {
1146 const bool success = refs->attemptIncStrong(mProcess.get());
1147 ALOG_ASSERT(success && refs->refBase() == obj,
1148 "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
1149 refs, obj, refs->refBase());
1150
1151 mOut.writeInt32(BC_ACQUIRE_RESULT);
1152 mOut.writeInt32((int32_t)success);
1153 }
1154 break;
1155
1156 case BR_TRANSACTION_SEC_CTX:
1157 case BR_TRANSACTION:
1158 {
1159 binder_transaction_data_secctx tr_secctx;
1160 binder_transaction_data& tr = tr_secctx.transaction_data;
1161
1162 if (cmd == (int) BR_TRANSACTION_SEC_CTX) {
1163 result = mIn.read(&tr_secctx, sizeof(tr_secctx));
1164 } else {
1165 result = mIn.read(&tr, sizeof(tr));
1166 tr_secctx.secctx = 0;
1167 }
1168
1169 ALOG_ASSERT(result == NO_ERROR,
1170 "Not enough command data for brTRANSACTION");
1171 if (result != NO_ERROR) break;
1172
1173 Parcel buffer;
1174 buffer.ipcSetDataReference(
1175 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1176 tr.data_size,
1177 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1178 tr.offsets_size/sizeof(binder_size_t), freeBuffer, this);
1179
1180 const void* origServingStackPointer = mServingStackPointer;
1181 mServingStackPointer = &origServingStackPointer; // anything on the stack
1182
1183 const pid_t origPid = mCallingPid;
1184 const char* origSid = mCallingSid;
1185 const uid_t origUid = mCallingUid;
1186 const int32_t origStrictModePolicy = mStrictModePolicy;
1187 const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
1188 const int32_t origWorkSource = mWorkSource;
1189 const bool origPropagateWorkSet = mPropagateWorkSource;
1190 // Calling work source will be set by Parcel#enforceInterface. Parcel#enforceInterface
1191 // is only guaranteed to be called for AIDL-generated stubs so we reset the work source
1192 // here to never propagate it.
1193 clearCallingWorkSource();
1194 clearPropagateWorkSource();
1195
1196 mCallingPid = tr.sender_pid;
1197 mCallingSid = reinterpret_cast<const char*>(tr_secctx.secctx);
1198 mCallingUid = tr.sender_euid;
1199 mLastTransactionBinderFlags = tr.flags;
1200
1201 // ALOGI(">>>> TRANSACT from pid %d sid %s uid %d\n", mCallingPid,
1202 // (mCallingSid ? mCallingSid : "<N/A>"), mCallingUid);
1203
1204 Parcel reply;
1205 status_t error;
1206 IF_LOG_TRANSACTIONS() {
1207 TextOutput::Bundle _b(alog);
1208 alog << "BR_TRANSACTION thr " << (void*)pthread_self()
1209 << " / obj " << tr.target.ptr << " / code "
1210 << TypeCode(tr.code) << ": " << indent << buffer
1211 << dedent << endl
1212 << "Data addr = "
1213 << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1214 << ", offsets addr="
1215 << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
1216 }
1217 if (tr.target.ptr) {
1218 // We only have a weak reference on the target object, so we must first try to
1219 // safely acquire a strong reference before doing anything else with it.
1220 if (reinterpret_cast<RefBase::weakref_type*>(
1221 tr.target.ptr)->attemptIncStrong(this)) {
1222 error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,
1223 &reply, tr.flags);
1224 reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);
1225 } else {
1226 error = UNKNOWN_TRANSACTION;
1227 }
1228
1229 } else {
1230 error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
1231 }
1232
1233 //ALOGI("<<<< TRANSACT from pid %d restore pid %d sid %s uid %d\n",
1234 // mCallingPid, origPid, (origSid ? origSid : "<N/A>"), origUid);
1235
1236 if ((tr.flags & TF_ONE_WAY) == 0) {
1237 LOG_ONEWAY("Sending reply to %d!", mCallingPid);
1238 if (error < NO_ERROR) reply.setError(error);
1239 sendReply(reply, 0);
1240 } else {
1241 if (error != OK || reply.dataSize() != 0) {
1242 alog << "oneway function results will be dropped but finished with status "
1243 << statusToString(error)
1244 << " and parcel size " << reply.dataSize() << endl;
1245 }
1246 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1247 }
1248
1249 mServingStackPointer = origServingStackPointer;
1250 mCallingPid = origPid;
1251 mCallingSid = origSid;
1252 mCallingUid = origUid;
1253 mStrictModePolicy = origStrictModePolicy;
1254 mLastTransactionBinderFlags = origTransactionBinderFlags;
1255 mWorkSource = origWorkSource;
1256 mPropagateWorkSource = origPropagateWorkSet;
1257
1258 IF_LOG_TRANSACTIONS() {
1259 TextOutput::Bundle _b(alog);
1260 alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
1261 << tr.target.ptr << ": " << indent << reply << dedent << endl;
1262 }
1263
1264 }
1265 break;
1266
1267 case BR_DEAD_BINDER:
1268 {
1269 BpBinder *proxy = (BpBinder*)mIn.readPointer();
1270 proxy->sendObituary();
1271 mOut.writeInt32(BC_DEAD_BINDER_DONE);
1272 mOut.writePointer((uintptr_t)proxy);
1273 } break;
1274
1275 case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1276 {
1277 BpBinder *proxy = (BpBinder*)mIn.readPointer();
1278 proxy->getWeakRefs()->decWeak(proxy);
1279 } break;
1280
1281 case BR_FINISHED:
1282 result = TIMED_OUT;
1283 break;
1284
1285 case BR_NOOP:
1286 break;
1287
1288 case BR_SPAWN_LOOPER:
1289 mProcess->spawnPooledThread(false);
1290 break;
1291
1292 default:
1293 ALOGE("*** BAD COMMAND %d received from Binder driver\n", cmd);
1294 result = UNKNOWN_ERROR;
1295 break;
1296 }
1297
1298 if (result != NO_ERROR) {
1299 mLastError = result;
1300 }
1301
1302 return result;
1303 }
1304
getServingStackPointer() const1305 const void* IPCThreadState::getServingStackPointer() const {
1306 return mServingStackPointer;
1307 }
1308
threadDestructor(void * st)1309 void IPCThreadState::threadDestructor(void *st)
1310 {
1311 IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1312 if (self) {
1313 self->flushCommands();
1314 #if defined(__ANDROID__)
1315 if (self->mProcess->mDriverFD >= 0) {
1316 ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1317 }
1318 #endif
1319 delete self;
1320 }
1321 }
1322
getProcessFreezeInfo(pid_t pid,bool * sync_received,bool * async_received)1323 status_t IPCThreadState::getProcessFreezeInfo(pid_t pid, bool *sync_received, bool *async_received)
1324 {
1325 int ret = 0;
1326 binder_frozen_status_info info;
1327 info.pid = pid;
1328
1329 #if defined(__ANDROID__)
1330 if (ioctl(self()->mProcess->mDriverFD, BINDER_GET_FROZEN_INFO, &info) < 0)
1331 ret = -errno;
1332 #endif
1333 *sync_received = info.sync_recv;
1334 *async_received = info.async_recv;
1335
1336 return ret;
1337 }
1338
freeze(pid_t pid,bool enable,uint32_t timeout_ms)1339 status_t IPCThreadState::freeze(pid_t pid, bool enable, uint32_t timeout_ms) {
1340 struct binder_freeze_info info;
1341 int ret = 0;
1342
1343 info.pid = pid;
1344 info.enable = enable;
1345 info.timeout_ms = timeout_ms;
1346
1347
1348 #if defined(__ANDROID__)
1349 if (ioctl(self()->mProcess->mDriverFD, BINDER_FREEZE, &info) < 0)
1350 ret = -errno;
1351 #endif
1352
1353 //
1354 // ret==-EAGAIN indicates that transactions have not drained.
1355 // Call again to poll for completion.
1356 //
1357 return ret;
1358 }
1359
freeBuffer(Parcel * parcel,const uint8_t * data,size_t,const binder_size_t *,size_t,void *)1360 void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data,
1361 size_t /*dataSize*/,
1362 const binder_size_t* /*objects*/,
1363 size_t /*objectsSize*/, void* /*cookie*/)
1364 {
1365 //ALOGI("Freeing parcel %p", &parcel);
1366 IF_LOG_COMMANDS() {
1367 alog << "Writing BC_FREE_BUFFER for " << data << endl;
1368 }
1369 ALOG_ASSERT(data != NULL, "Called with NULL data");
1370 if (parcel != nullptr) parcel->closeFileDescriptors();
1371 IPCThreadState* state = self();
1372 state->mOut.writeInt32(BC_FREE_BUFFER);
1373 state->mOut.writePointer((uintptr_t)data);
1374 }
1375
1376 } // namespace android
1377