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