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