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 
21 #include <binder/Binder.h>
22 #include <binder/BpBinder.h>
23 #include <binder/TextOutput.h>
24 
25 #include <cutils/sched_policy.h>
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 <private/binder/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 
50 #define LOG_THREADPOOL(...)
51 #define LOG_ONEWAY(...)
52 
53 #else
54 
55 #define IF_LOG_TRANSACTIONS() IF_ALOG(LOG_VERBOSE, "transact")
56 #define IF_LOG_COMMANDS() IF_ALOG(LOG_VERBOSE, "ipc")
57 #define LOG_REMOTEREFS(...) ALOG(LOG_DEBUG, "remoterefs", __VA_ARGS__)
58 #define IF_LOG_REMOTEREFS() IF_ALOG(LOG_DEBUG, "remoterefs")
59 #define LOG_THREADPOOL(...) ALOG(LOG_DEBUG, "threadpool", __VA_ARGS__)
60 #define LOG_ONEWAY(...) ALOG(LOG_DEBUG, "ipc", __VA_ARGS__)
61 
62 #endif
63 
64 // ---------------------------------------------------------------------------
65 
66 namespace android {
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 };
90 
91 static const char *kCommandStrings[] = {
92     "BC_TRANSACTION",
93     "BC_REPLY",
94     "BC_ACQUIRE_RESULT",
95     "BC_FREE_BUFFER",
96     "BC_INCREFS",
97     "BC_ACQUIRE",
98     "BC_RELEASE",
99     "BC_DECREFS",
100     "BC_INCREFS_DONE",
101     "BC_ACQUIRE_DONE",
102     "BC_ATTEMPT_ACQUIRE",
103     "BC_REGISTER_LOOPER",
104     "BC_ENTER_LOOPER",
105     "BC_EXIT_LOOPER",
106     "BC_REQUEST_DEATH_NOTIFICATION",
107     "BC_CLEAR_DEATH_NOTIFICATION",
108     "BC_DEAD_BINDER_DONE"
109 };
110 
getReturnString(uint32_t cmd)111 static const char* getReturnString(uint32_t cmd)
112 {
113     size_t idx = cmd & 0xff;
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 
backgroundSchedulingDisabled()341 bool IPCThreadState::backgroundSchedulingDisabled()
342 {
343     return gDisableBackgroundScheduling;
344 }
345 
process()346 sp<ProcessState> IPCThreadState::process()
347 {
348     return mProcess;
349 }
350 
clearLastError()351 status_t IPCThreadState::clearLastError()
352 {
353     const status_t err = mLastError;
354     mLastError = NO_ERROR;
355     return err;
356 }
357 
getCallingPid() const358 pid_t IPCThreadState::getCallingPid() const
359 {
360     return mCallingPid;
361 }
362 
getCallingUid() const363 uid_t IPCThreadState::getCallingUid() const
364 {
365     return mCallingUid;
366 }
367 
clearCallingIdentity()368 int64_t IPCThreadState::clearCallingIdentity()
369 {
370     int64_t token = ((int64_t)mCallingUid<<32) | mCallingPid;
371     clearCaller();
372     return token;
373 }
374 
setStrictModePolicy(int32_t policy)375 void IPCThreadState::setStrictModePolicy(int32_t policy)
376 {
377     mStrictModePolicy = policy;
378 }
379 
getStrictModePolicy() const380 int32_t IPCThreadState::getStrictModePolicy() const
381 {
382     return mStrictModePolicy;
383 }
384 
setLastTransactionBinderFlags(int32_t flags)385 void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
386 {
387     mLastTransactionBinderFlags = flags;
388 }
389 
getLastTransactionBinderFlags() const390 int32_t IPCThreadState::getLastTransactionBinderFlags() const
391 {
392     return mLastTransactionBinderFlags;
393 }
394 
restoreCallingIdentity(int64_t token)395 void IPCThreadState::restoreCallingIdentity(int64_t token)
396 {
397     mCallingUid = (int)(token>>32);
398     mCallingPid = (int)token;
399 }
400 
clearCaller()401 void IPCThreadState::clearCaller()
402 {
403     mCallingPid = getpid();
404     mCallingUid = getuid();
405 }
406 
flushCommands()407 void IPCThreadState::flushCommands()
408 {
409     if (mProcess->mDriverFD <= 0)
410         return;
411     talkWithDriver(false);
412     // The flush could have caused post-write refcount decrements to have
413     // been executed, which in turn could result in BC_RELEASE/BC_DECREFS
414     // being queued in mOut. So flush again, if we need to.
415     if (mOut.dataSize() > 0) {
416         talkWithDriver(false);
417     }
418     if (mOut.dataSize() > 0) {
419         ALOGW("mOut.dataSize() > 0 after flushCommands()");
420     }
421 }
422 
blockUntilThreadAvailable()423 void IPCThreadState::blockUntilThreadAvailable()
424 {
425     pthread_mutex_lock(&mProcess->mThreadCountLock);
426     while (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads) {
427         ALOGW("Waiting for thread to be free. mExecutingThreadsCount=%lu mMaxThreads=%lu\n",
428                 static_cast<unsigned long>(mProcess->mExecutingThreadsCount),
429                 static_cast<unsigned long>(mProcess->mMaxThreads));
430         pthread_cond_wait(&mProcess->mThreadCountDecrement, &mProcess->mThreadCountLock);
431     }
432     pthread_mutex_unlock(&mProcess->mThreadCountLock);
433 }
434 
getAndExecuteCommand()435 status_t IPCThreadState::getAndExecuteCommand()
436 {
437     status_t result;
438     int32_t cmd;
439 
440     result = talkWithDriver();
441     if (result >= NO_ERROR) {
442         size_t IN = mIn.dataAvail();
443         if (IN < sizeof(int32_t)) return result;
444         cmd = mIn.readInt32();
445         IF_LOG_COMMANDS() {
446             alog << "Processing top-level Command: "
447                  << getReturnString(cmd) << endl;
448         }
449 
450         pthread_mutex_lock(&mProcess->mThreadCountLock);
451         mProcess->mExecutingThreadsCount++;
452         if (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads &&
453                 mProcess->mStarvationStartTimeMs == 0) {
454             mProcess->mStarvationStartTimeMs = uptimeMillis();
455         }
456         pthread_mutex_unlock(&mProcess->mThreadCountLock);
457 
458         result = executeCommand(cmd);
459 
460         pthread_mutex_lock(&mProcess->mThreadCountLock);
461         mProcess->mExecutingThreadsCount--;
462         if (mProcess->mExecutingThreadsCount < mProcess->mMaxThreads &&
463                 mProcess->mStarvationStartTimeMs != 0) {
464             int64_t starvationTimeMs = uptimeMillis() - mProcess->mStarvationStartTimeMs;
465             if (starvationTimeMs > 100) {
466                 ALOGE("binder thread pool (%zu threads) starved for %" PRId64 " ms",
467                       mProcess->mMaxThreads, starvationTimeMs);
468             }
469             mProcess->mStarvationStartTimeMs = 0;
470         }
471         pthread_cond_broadcast(&mProcess->mThreadCountDecrement);
472         pthread_mutex_unlock(&mProcess->mThreadCountLock);
473     }
474 
475     return result;
476 }
477 
478 // When we've cleared the incoming command queue, process any pending derefs
processPendingDerefs()479 void IPCThreadState::processPendingDerefs()
480 {
481     if (mIn.dataPosition() >= mIn.dataSize()) {
482         /*
483          * The decWeak()/decStrong() calls may cause a destructor to run,
484          * which in turn could have initiated an outgoing transaction,
485          * which in turn could cause us to add to the pending refs
486          * vectors; so instead of simply iterating, loop until they're empty.
487          *
488          * We do this in an outer loop, because calling decStrong()
489          * may result in something being added to mPendingWeakDerefs,
490          * which could be delayed until the next incoming command
491          * from the driver if we don't process it now.
492          */
493         while (mPendingWeakDerefs.size() > 0 || mPendingStrongDerefs.size() > 0) {
494             while (mPendingWeakDerefs.size() > 0) {
495                 RefBase::weakref_type* refs = mPendingWeakDerefs[0];
496                 mPendingWeakDerefs.removeAt(0);
497                 refs->decWeak(mProcess.get());
498             }
499 
500             if (mPendingStrongDerefs.size() > 0) {
501                 // We don't use while() here because we don't want to re-order
502                 // strong and weak decs at all; if this decStrong() causes both a
503                 // decWeak() and a decStrong() to be queued, we want to process
504                 // the decWeak() first.
505                 BBinder* obj = mPendingStrongDerefs[0];
506                 mPendingStrongDerefs.removeAt(0);
507                 obj->decStrong(mProcess.get());
508             }
509         }
510     }
511 }
512 
processPostWriteDerefs()513 void IPCThreadState::processPostWriteDerefs()
514 {
515     for (size_t i = 0; i < mPostWriteWeakDerefs.size(); i++) {
516         RefBase::weakref_type* refs = mPostWriteWeakDerefs[i];
517         refs->decWeak(mProcess.get());
518     }
519     mPostWriteWeakDerefs.clear();
520 
521     for (size_t i = 0; i < mPostWriteStrongDerefs.size(); i++) {
522         RefBase* obj = mPostWriteStrongDerefs[i];
523         obj->decStrong(mProcess.get());
524     }
525     mPostWriteStrongDerefs.clear();
526 }
527 
joinThreadPool(bool isMain)528 void IPCThreadState::joinThreadPool(bool isMain)
529 {
530     LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
531 
532     mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
533 
534     status_t result;
535     do {
536         processPendingDerefs();
537         // now get the next command to be processed, waiting if necessary
538         result = getAndExecuteCommand();
539 
540         if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
541             ALOGE("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
542                   mProcess->mDriverFD, result);
543             abort();
544         }
545 
546         // Let this thread exit the thread pool if it is no longer
547         // needed and it is not the main process thread.
548         if(result == TIMED_OUT && !isMain) {
549             break;
550         }
551     } while (result != -ECONNREFUSED && result != -EBADF);
552 
553     LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%d\n",
554         (void*)pthread_self(), getpid(), result);
555 
556     mOut.writeInt32(BC_EXIT_LOOPER);
557     talkWithDriver(false);
558 }
559 
setupPolling(int * fd)560 int IPCThreadState::setupPolling(int* fd)
561 {
562     if (mProcess->mDriverFD <= 0) {
563         return -EBADF;
564     }
565 
566     mOut.writeInt32(BC_ENTER_LOOPER);
567     *fd = mProcess->mDriverFD;
568     return 0;
569 }
570 
handlePolledCommands()571 status_t IPCThreadState::handlePolledCommands()
572 {
573     status_t result;
574 
575     do {
576         result = getAndExecuteCommand();
577     } while (mIn.dataPosition() < mIn.dataSize());
578 
579     processPendingDerefs();
580     flushCommands();
581     return result;
582 }
583 
stopProcess(bool)584 void IPCThreadState::stopProcess(bool /*immediate*/)
585 {
586     //ALOGI("**** STOPPING PROCESS");
587     flushCommands();
588     int fd = mProcess->mDriverFD;
589     mProcess->mDriverFD = -1;
590     close(fd);
591     //kill(getpid(), SIGKILL);
592 }
593 
transact(int32_t handle,uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)594 status_t IPCThreadState::transact(int32_t handle,
595                                   uint32_t code, const Parcel& data,
596                                   Parcel* reply, uint32_t flags)
597 {
598     status_t err;
599 
600     flags |= TF_ACCEPT_FDS;
601 
602     IF_LOG_TRANSACTIONS() {
603         TextOutput::Bundle _b(alog);
604         alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
605             << handle << " / code " << TypeCode(code) << ": "
606             << indent << data << dedent << endl;
607     }
608 
609     LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
610         (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
611     err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);
612 
613     if (err != NO_ERROR) {
614         if (reply) reply->setError(err);
615         return (mLastError = err);
616     }
617 
618     if ((flags & TF_ONE_WAY) == 0) {
619         #if 0
620         if (code == 4) { // relayout
621             ALOGI(">>>>>> CALLING transaction 4");
622         } else {
623             ALOGI(">>>>>> CALLING transaction %d", code);
624         }
625         #endif
626         if (reply) {
627             err = waitForResponse(reply);
628         } else {
629             Parcel fakeReply;
630             err = waitForResponse(&fakeReply);
631         }
632         #if 0
633         if (code == 4) { // relayout
634             ALOGI("<<<<<< RETURNING transaction 4");
635         } else {
636             ALOGI("<<<<<< RETURNING transaction %d", code);
637         }
638         #endif
639 
640         IF_LOG_TRANSACTIONS() {
641             TextOutput::Bundle _b(alog);
642             alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
643                 << handle << ": ";
644             if (reply) alog << indent << *reply << dedent << endl;
645             else alog << "(none requested)" << endl;
646         }
647     } else {
648         err = waitForResponse(NULL, NULL);
649     }
650 
651     return err;
652 }
653 
incStrongHandle(int32_t handle,BpBinder * proxy)654 void IPCThreadState::incStrongHandle(int32_t handle, BpBinder *proxy)
655 {
656     LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
657     mOut.writeInt32(BC_ACQUIRE);
658     mOut.writeInt32(handle);
659     // Create a temp reference until the driver has handled this command.
660     proxy->incStrong(mProcess.get());
661     mPostWriteStrongDerefs.push(proxy);
662 }
663 
decStrongHandle(int32_t handle)664 void IPCThreadState::decStrongHandle(int32_t handle)
665 {
666     LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
667     mOut.writeInt32(BC_RELEASE);
668     mOut.writeInt32(handle);
669 }
670 
incWeakHandle(int32_t handle,BpBinder * proxy)671 void IPCThreadState::incWeakHandle(int32_t handle, BpBinder *proxy)
672 {
673     LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
674     mOut.writeInt32(BC_INCREFS);
675     mOut.writeInt32(handle);
676     // Create a temp reference until the driver has handled this command.
677     proxy->getWeakRefs()->incWeak(mProcess.get());
678     mPostWriteWeakDerefs.push(proxy->getWeakRefs());
679 }
680 
decWeakHandle(int32_t handle)681 void IPCThreadState::decWeakHandle(int32_t handle)
682 {
683     LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
684     mOut.writeInt32(BC_DECREFS);
685     mOut.writeInt32(handle);
686 }
687 
attemptIncStrongHandle(int32_t handle)688 status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
689 {
690 #if HAS_BC_ATTEMPT_ACQUIRE
691     LOG_REMOTEREFS("IPCThreadState::attemptIncStrongHandle(%d)\n", handle);
692     mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
693     mOut.writeInt32(0); // xxx was thread priority
694     mOut.writeInt32(handle);
695     status_t result = UNKNOWN_ERROR;
696 
697     waitForResponse(NULL, &result);
698 
699 #if LOG_REFCOUNTS
700     ALOGV("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
701         handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
702 #endif
703 
704     return result;
705 #else
706     (void)handle;
707     ALOGE("%s(%d): Not supported\n", __func__, handle);
708     return INVALID_OPERATION;
709 #endif
710 }
711 
expungeHandle(int32_t handle,IBinder * binder)712 void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
713 {
714 #if LOG_REFCOUNTS
715     ALOGV("IPCThreadState::expungeHandle(%ld)\n", handle);
716 #endif
717     self()->mProcess->expungeHandle(handle, binder); // NOLINT
718 }
719 
requestDeathNotification(int32_t handle,BpBinder * proxy)720 status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
721 {
722     mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
723     mOut.writeInt32((int32_t)handle);
724     mOut.writePointer((uintptr_t)proxy);
725     return NO_ERROR;
726 }
727 
clearDeathNotification(int32_t handle,BpBinder * proxy)728 status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
729 {
730     mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
731     mOut.writeInt32((int32_t)handle);
732     mOut.writePointer((uintptr_t)proxy);
733     return NO_ERROR;
734 }
735 
IPCThreadState()736 IPCThreadState::IPCThreadState()
737     : mProcess(ProcessState::self()),
738       mStrictModePolicy(0),
739       mLastTransactionBinderFlags(0)
740 {
741     pthread_setspecific(gTLS, this);
742     clearCaller();
743     mIn.setDataCapacity(256);
744     mOut.setDataCapacity(256);
745 }
746 
~IPCThreadState()747 IPCThreadState::~IPCThreadState()
748 {
749 }
750 
sendReply(const Parcel & reply,uint32_t flags)751 status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
752 {
753     status_t err;
754     status_t statusBuffer;
755     err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
756     if (err < NO_ERROR) return err;
757 
758     return waitForResponse(NULL, NULL);
759 }
760 
waitForResponse(Parcel * reply,status_t * acquireResult)761 status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
762 {
763     uint32_t cmd;
764     int32_t err;
765 
766     while (1) {
767         if ((err=talkWithDriver()) < NO_ERROR) break;
768         err = mIn.errorCheck();
769         if (err < NO_ERROR) break;
770         if (mIn.dataAvail() == 0) continue;
771 
772         cmd = (uint32_t)mIn.readInt32();
773 
774         IF_LOG_COMMANDS() {
775             alog << "Processing waitForResponse Command: "
776                 << getReturnString(cmd) << endl;
777         }
778 
779         switch (cmd) {
780         case BR_TRANSACTION_COMPLETE:
781             if (!reply && !acquireResult) goto finish;
782             break;
783 
784         case BR_DEAD_REPLY:
785             err = DEAD_OBJECT;
786             goto finish;
787 
788         case BR_FAILED_REPLY:
789             err = FAILED_TRANSACTION;
790             goto finish;
791 
792         case BR_ACQUIRE_RESULT:
793             {
794                 ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
795                 const int32_t result = mIn.readInt32();
796                 if (!acquireResult) continue;
797                 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
798             }
799             goto finish;
800 
801         case BR_REPLY:
802             {
803                 binder_transaction_data tr;
804                 err = mIn.read(&tr, sizeof(tr));
805                 ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
806                 if (err != NO_ERROR) goto finish;
807 
808                 if (reply) {
809                     if ((tr.flags & TF_STATUS_CODE) == 0) {
810                         reply->ipcSetDataReference(
811                             reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
812                             tr.data_size,
813                             reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
814                             tr.offsets_size/sizeof(binder_size_t),
815                             freeBuffer, this);
816                     } else {
817                         err = *reinterpret_cast<const status_t*>(tr.data.ptr.buffer);
818                         freeBuffer(NULL,
819                             reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
820                             tr.data_size,
821                             reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
822                             tr.offsets_size/sizeof(binder_size_t), this);
823                     }
824                 } else {
825                     freeBuffer(NULL,
826                         reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
827                         tr.data_size,
828                         reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
829                         tr.offsets_size/sizeof(binder_size_t), this);
830                     continue;
831                 }
832             }
833             goto finish;
834 
835         default:
836             err = executeCommand(cmd);
837             if (err != NO_ERROR) goto finish;
838             break;
839         }
840     }
841 
842 finish:
843     if (err != NO_ERROR) {
844         if (acquireResult) *acquireResult = err;
845         if (reply) reply->setError(err);
846         mLastError = err;
847     }
848 
849     return err;
850 }
851 
talkWithDriver(bool doReceive)852 status_t IPCThreadState::talkWithDriver(bool doReceive)
853 {
854     if (mProcess->mDriverFD <= 0) {
855         return -EBADF;
856     }
857 
858     binder_write_read bwr;
859 
860     // Is the read buffer empty?
861     const bool needRead = mIn.dataPosition() >= mIn.dataSize();
862 
863     // We don't want to write anything if we are still reading
864     // from data left in the input buffer and the caller
865     // has requested to read the next data.
866     const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
867 
868     bwr.write_size = outAvail;
869     bwr.write_buffer = (uintptr_t)mOut.data();
870 
871     // This is what we'll read.
872     if (doReceive && needRead) {
873         bwr.read_size = mIn.dataCapacity();
874         bwr.read_buffer = (uintptr_t)mIn.data();
875     } else {
876         bwr.read_size = 0;
877         bwr.read_buffer = 0;
878     }
879 
880     IF_LOG_COMMANDS() {
881         TextOutput::Bundle _b(alog);
882         if (outAvail != 0) {
883             alog << "Sending commands to driver: " << indent;
884             const void* cmds = (const void*)bwr.write_buffer;
885             const void* end = ((const uint8_t*)cmds)+bwr.write_size;
886             alog << HexDump(cmds, bwr.write_size) << endl;
887             while (cmds < end) cmds = printCommand(alog, cmds);
888             alog << dedent;
889         }
890         alog << "Size of receive buffer: " << bwr.read_size
891             << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
892     }
893 
894     // Return immediately if there is nothing to do.
895     if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
896 
897     bwr.write_consumed = 0;
898     bwr.read_consumed = 0;
899     status_t err;
900     do {
901         IF_LOG_COMMANDS() {
902             alog << "About to read/write, write size = " << mOut.dataSize() << endl;
903         }
904 #if defined(__ANDROID__)
905         if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
906             err = NO_ERROR;
907         else
908             err = -errno;
909 #else
910         err = INVALID_OPERATION;
911 #endif
912         if (mProcess->mDriverFD <= 0) {
913             err = -EBADF;
914         }
915         IF_LOG_COMMANDS() {
916             alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
917         }
918     } while (err == -EINTR);
919 
920     IF_LOG_COMMANDS() {
921         alog << "Our err: " << (void*)(intptr_t)err << ", write consumed: "
922             << bwr.write_consumed << " (of " << mOut.dataSize()
923                         << "), read consumed: " << bwr.read_consumed << endl;
924     }
925 
926     if (err >= NO_ERROR) {
927         if (bwr.write_consumed > 0) {
928             if (bwr.write_consumed < mOut.dataSize())
929                 mOut.remove(0, bwr.write_consumed);
930             else {
931                 mOut.setDataSize(0);
932                 processPostWriteDerefs();
933             }
934         }
935         if (bwr.read_consumed > 0) {
936             mIn.setDataSize(bwr.read_consumed);
937             mIn.setDataPosition(0);
938         }
939         IF_LOG_COMMANDS() {
940             TextOutput::Bundle _b(alog);
941             alog << "Remaining data size: " << mOut.dataSize() << endl;
942             alog << "Received commands from driver: " << indent;
943             const void* cmds = mIn.data();
944             const void* end = mIn.data() + mIn.dataSize();
945             alog << HexDump(cmds, mIn.dataSize()) << endl;
946             while (cmds < end) cmds = printReturnCommand(alog, cmds);
947             alog << dedent;
948         }
949         return NO_ERROR;
950     }
951 
952     return err;
953 }
954 
writeTransactionData(int32_t cmd,uint32_t binderFlags,int32_t handle,uint32_t code,const Parcel & data,status_t * statusBuffer)955 status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
956     int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
957 {
958     binder_transaction_data tr;
959 
960     tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
961     tr.target.handle = handle;
962     tr.code = code;
963     tr.flags = binderFlags;
964     tr.cookie = 0;
965     tr.sender_pid = 0;
966     tr.sender_euid = 0;
967 
968     const status_t err = data.errorCheck();
969     if (err == NO_ERROR) {
970         tr.data_size = data.ipcDataSize();
971         tr.data.ptr.buffer = data.ipcData();
972         tr.offsets_size = data.ipcObjectsCount()*sizeof(binder_size_t);
973         tr.data.ptr.offsets = data.ipcObjects();
974     } else if (statusBuffer) {
975         tr.flags |= TF_STATUS_CODE;
976         *statusBuffer = err;
977         tr.data_size = sizeof(status_t);
978         tr.data.ptr.buffer = reinterpret_cast<uintptr_t>(statusBuffer);
979         tr.offsets_size = 0;
980         tr.data.ptr.offsets = 0;
981     } else {
982         return (mLastError = err);
983     }
984 
985     mOut.writeInt32(cmd);
986     mOut.write(&tr, sizeof(tr));
987 
988     return NO_ERROR;
989 }
990 
991 sp<BBinder> the_context_object;
992 
setTheContextObject(sp<BBinder> obj)993 void setTheContextObject(sp<BBinder> obj)
994 {
995     the_context_object = obj;
996 }
997 
executeCommand(int32_t cmd)998 status_t IPCThreadState::executeCommand(int32_t cmd)
999 {
1000     BBinder* obj;
1001     RefBase::weakref_type* refs;
1002     status_t result = NO_ERROR;
1003 
1004     switch ((uint32_t)cmd) {
1005     case BR_ERROR:
1006         result = mIn.readInt32();
1007         break;
1008 
1009     case BR_OK:
1010         break;
1011 
1012     case BR_ACQUIRE:
1013         refs = (RefBase::weakref_type*)mIn.readPointer();
1014         obj = (BBinder*)mIn.readPointer();
1015         ALOG_ASSERT(refs->refBase() == obj,
1016                    "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
1017                    refs, obj, refs->refBase());
1018         obj->incStrong(mProcess.get());
1019         IF_LOG_REMOTEREFS() {
1020             LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
1021             obj->printRefs();
1022         }
1023         mOut.writeInt32(BC_ACQUIRE_DONE);
1024         mOut.writePointer((uintptr_t)refs);
1025         mOut.writePointer((uintptr_t)obj);
1026         break;
1027 
1028     case BR_RELEASE:
1029         refs = (RefBase::weakref_type*)mIn.readPointer();
1030         obj = (BBinder*)mIn.readPointer();
1031         ALOG_ASSERT(refs->refBase() == obj,
1032                    "BR_RELEASE: object %p does not match cookie %p (expected %p)",
1033                    refs, obj, refs->refBase());
1034         IF_LOG_REMOTEREFS() {
1035             LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
1036             obj->printRefs();
1037         }
1038         mPendingStrongDerefs.push(obj);
1039         break;
1040 
1041     case BR_INCREFS:
1042         refs = (RefBase::weakref_type*)mIn.readPointer();
1043         obj = (BBinder*)mIn.readPointer();
1044         refs->incWeak(mProcess.get());
1045         mOut.writeInt32(BC_INCREFS_DONE);
1046         mOut.writePointer((uintptr_t)refs);
1047         mOut.writePointer((uintptr_t)obj);
1048         break;
1049 
1050     case BR_DECREFS:
1051         refs = (RefBase::weakref_type*)mIn.readPointer();
1052         obj = (BBinder*)mIn.readPointer();
1053         // NOTE: This assertion is not valid, because the object may no
1054         // longer exist (thus the (BBinder*)cast above resulting in a different
1055         // memory address).
1056         //ALOG_ASSERT(refs->refBase() == obj,
1057         //           "BR_DECREFS: object %p does not match cookie %p (expected %p)",
1058         //           refs, obj, refs->refBase());
1059         mPendingWeakDerefs.push(refs);
1060         break;
1061 
1062     case BR_ATTEMPT_ACQUIRE:
1063         refs = (RefBase::weakref_type*)mIn.readPointer();
1064         obj = (BBinder*)mIn.readPointer();
1065 
1066         {
1067             const bool success = refs->attemptIncStrong(mProcess.get());
1068             ALOG_ASSERT(success && refs->refBase() == obj,
1069                        "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
1070                        refs, obj, refs->refBase());
1071 
1072             mOut.writeInt32(BC_ACQUIRE_RESULT);
1073             mOut.writeInt32((int32_t)success);
1074         }
1075         break;
1076 
1077     case BR_TRANSACTION:
1078         {
1079             binder_transaction_data tr;
1080             result = mIn.read(&tr, sizeof(tr));
1081             ALOG_ASSERT(result == NO_ERROR,
1082                 "Not enough command data for brTRANSACTION");
1083             if (result != NO_ERROR) break;
1084 
1085             Parcel buffer;
1086             buffer.ipcSetDataReference(
1087                 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1088                 tr.data_size,
1089                 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1090                 tr.offsets_size/sizeof(binder_size_t), freeBuffer, this);
1091 
1092             const pid_t origPid = mCallingPid;
1093             const uid_t origUid = mCallingUid;
1094             const int32_t origStrictModePolicy = mStrictModePolicy;
1095             const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
1096 
1097             mCallingPid = tr.sender_pid;
1098             mCallingUid = tr.sender_euid;
1099             mLastTransactionBinderFlags = tr.flags;
1100 
1101             //ALOGI(">>>> TRANSACT from pid %d uid %d\n", mCallingPid, mCallingUid);
1102 
1103             Parcel reply;
1104             status_t error;
1105             IF_LOG_TRANSACTIONS() {
1106                 TextOutput::Bundle _b(alog);
1107                 alog << "BR_TRANSACTION thr " << (void*)pthread_self()
1108                     << " / obj " << tr.target.ptr << " / code "
1109                     << TypeCode(tr.code) << ": " << indent << buffer
1110                     << dedent << endl
1111                     << "Data addr = "
1112                     << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1113                     << ", offsets addr="
1114                     << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
1115             }
1116             if (tr.target.ptr) {
1117                 // We only have a weak reference on the target object, so we must first try to
1118                 // safely acquire a strong reference before doing anything else with it.
1119                 if (reinterpret_cast<RefBase::weakref_type*>(
1120                         tr.target.ptr)->attemptIncStrong(this)) {
1121                     error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,
1122                             &reply, tr.flags);
1123                     reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);
1124                 } else {
1125                     error = UNKNOWN_TRANSACTION;
1126                 }
1127 
1128             } else {
1129                 error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
1130             }
1131 
1132             //ALOGI("<<<< TRANSACT from pid %d restore pid %d uid %d\n",
1133             //     mCallingPid, origPid, origUid);
1134 
1135             if ((tr.flags & TF_ONE_WAY) == 0) {
1136                 LOG_ONEWAY("Sending reply to %d!", mCallingPid);
1137                 if (error < NO_ERROR) reply.setError(error);
1138                 sendReply(reply, 0);
1139             } else {
1140                 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1141             }
1142 
1143             mCallingPid = origPid;
1144             mCallingUid = origUid;
1145             mStrictModePolicy = origStrictModePolicy;
1146             mLastTransactionBinderFlags = origTransactionBinderFlags;
1147 
1148             IF_LOG_TRANSACTIONS() {
1149                 TextOutput::Bundle _b(alog);
1150                 alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
1151                     << tr.target.ptr << ": " << indent << reply << dedent << endl;
1152             }
1153 
1154         }
1155         break;
1156 
1157     case BR_DEAD_BINDER:
1158         {
1159             BpBinder *proxy = (BpBinder*)mIn.readPointer();
1160             proxy->sendObituary();
1161             mOut.writeInt32(BC_DEAD_BINDER_DONE);
1162             mOut.writePointer((uintptr_t)proxy);
1163         } break;
1164 
1165     case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1166         {
1167             BpBinder *proxy = (BpBinder*)mIn.readPointer();
1168             proxy->getWeakRefs()->decWeak(proxy);
1169         } break;
1170 
1171     case BR_FINISHED:
1172         result = TIMED_OUT;
1173         break;
1174 
1175     case BR_NOOP:
1176         break;
1177 
1178     case BR_SPAWN_LOOPER:
1179         mProcess->spawnPooledThread(false);
1180         break;
1181 
1182     default:
1183         ALOGE("*** BAD COMMAND %d received from Binder driver\n", cmd);
1184         result = UNKNOWN_ERROR;
1185         break;
1186     }
1187 
1188     if (result != NO_ERROR) {
1189         mLastError = result;
1190     }
1191 
1192     return result;
1193 }
1194 
threadDestructor(void * st)1195 void IPCThreadState::threadDestructor(void *st)
1196 {
1197         IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1198         if (self) {
1199                 self->flushCommands();
1200 #if defined(__ANDROID__)
1201         if (self->mProcess->mDriverFD > 0) {
1202             ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1203         }
1204 #endif
1205                 delete self;
1206         }
1207 }
1208 
1209 
freeBuffer(Parcel * parcel,const uint8_t * data,size_t,const binder_size_t *,size_t,void *)1210 void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data,
1211                                 size_t /*dataSize*/,
1212                                 const binder_size_t* /*objects*/,
1213                                 size_t /*objectsSize*/, void* /*cookie*/)
1214 {
1215     //ALOGI("Freeing parcel %p", &parcel);
1216     IF_LOG_COMMANDS() {
1217         alog << "Writing BC_FREE_BUFFER for " << data << endl;
1218     }
1219     ALOG_ASSERT(data != NULL, "Called with NULL data");
1220     if (parcel != NULL) parcel->closeFileDescriptors();
1221     IPCThreadState* state = self();
1222     state->mOut.writeInt32(BC_FREE_BUFFER);
1223     state->mOut.writePointer((uintptr_t)data);
1224 }
1225 
1226 }; // namespace android
1227