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