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