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