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