• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2005 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "IPCThreadState"
18 
19 #include <binder/IPCThreadState.h>
20 
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/threads.h>
28 
29 #include <private/binder/binder_module.h>
30 #include <private/binder/Static.h>
31 
32 #include <sys/ioctl.h>
33 #include <signal.h>
34 #include <errno.h>
35 #include <stdio.h>
36 #include <unistd.h>
37 
38 #ifdef HAVE_PTHREADS
39 #include <pthread.h>
40 #include <sched.h>
41 #include <sys/resource.h>
42 #endif
43 #ifdef HAVE_WIN32_THREADS
44 #include <windows.h>
45 #endif
46 
47 
48 #if LOG_NDEBUG
49 
50 #define IF_LOG_TRANSACTIONS() if (false)
51 #define IF_LOG_COMMANDS() if (false)
52 #define LOG_REMOTEREFS(...)
53 #define IF_LOG_REMOTEREFS() if (false)
54 #define LOG_THREADPOOL(...)
55 #define LOG_ONEWAY(...)
56 
57 #else
58 
59 #define IF_LOG_TRANSACTIONS() IF_ALOG(LOG_VERBOSE, "transact")
60 #define IF_LOG_COMMANDS() IF_ALOG(LOG_VERBOSE, "ipc")
61 #define LOG_REMOTEREFS(...) ALOG(LOG_DEBUG, "remoterefs", __VA_ARGS__)
62 #define IF_LOG_REMOTEREFS() IF_ALOG(LOG_DEBUG, "remoterefs")
63 #define LOG_THREADPOOL(...) ALOG(LOG_DEBUG, "threadpool", __VA_ARGS__)
64 #define LOG_ONEWAY(...) ALOG(LOG_DEBUG, "ipc", __VA_ARGS__)
65 
66 #endif
67 
68 // ---------------------------------------------------------------------------
69 
70 namespace android {
71 
72 static const char* getReturnString(size_t idx);
73 static const char* getCommandString(size_t idx);
74 static const void* printReturnCommand(TextOutput& out, const void* _cmd);
75 static const void* printCommand(TextOutput& out, const void* _cmd);
76 
77 // This will result in a missing symbol failure if the IF_LOG_COMMANDS()
78 // conditionals don't get stripped...  but that is probably what we want.
79 #if !LOG_NDEBUG
80 static const char *kReturnStrings[] = {
81     "BR_ERROR",
82     "BR_OK",
83     "BR_TRANSACTION",
84     "BR_REPLY",
85     "BR_ACQUIRE_RESULT",
86     "BR_DEAD_REPLY",
87     "BR_TRANSACTION_COMPLETE",
88     "BR_INCREFS",
89     "BR_ACQUIRE",
90     "BR_RELEASE",
91     "BR_DECREFS",
92     "BR_ATTEMPT_ACQUIRE",
93     "BR_NOOP",
94     "BR_SPAWN_LOOPER",
95     "BR_FINISHED",
96     "BR_DEAD_BINDER",
97     "BR_CLEAR_DEATH_NOTIFICATION_DONE",
98     "BR_FAILED_REPLY"
99 };
100 
101 static const char *kCommandStrings[] = {
102     "BC_TRANSACTION",
103     "BC_REPLY",
104     "BC_ACQUIRE_RESULT",
105     "BC_FREE_BUFFER",
106     "BC_INCREFS",
107     "BC_ACQUIRE",
108     "BC_RELEASE",
109     "BC_DECREFS",
110     "BC_INCREFS_DONE",
111     "BC_ACQUIRE_DONE",
112     "BC_ATTEMPT_ACQUIRE",
113     "BC_REGISTER_LOOPER",
114     "BC_ENTER_LOOPER",
115     "BC_EXIT_LOOPER",
116     "BC_REQUEST_DEATH_NOTIFICATION",
117     "BC_CLEAR_DEATH_NOTIFICATION",
118     "BC_DEAD_BINDER_DONE"
119 };
120 
getReturnString(size_t idx)121 static const char* getReturnString(size_t idx)
122 {
123     if (idx < sizeof(kReturnStrings) / sizeof(kReturnStrings[0]))
124         return kReturnStrings[idx];
125     else
126         return "unknown";
127 }
128 
getCommandString(size_t idx)129 static const char* getCommandString(size_t idx)
130 {
131     if (idx < sizeof(kCommandStrings) / sizeof(kCommandStrings[0]))
132         return kCommandStrings[idx];
133     else
134         return "unknown";
135 }
136 
printBinderTransactionData(TextOutput & out,const void * data)137 static const void* printBinderTransactionData(TextOutput& out, const void* data)
138 {
139     const binder_transaction_data* btd =
140         (const binder_transaction_data*)data;
141     if (btd->target.handle < 1024) {
142         /* want to print descriptors in decimal; guess based on value */
143         out << "target.desc=" << btd->target.handle;
144     } else {
145         out << "target.ptr=" << btd->target.ptr;
146     }
147     out << " (cookie " << btd->cookie << ")" << endl
148         << "code=" << TypeCode(btd->code) << ", flags=" << (void*)btd->flags << endl
149         << "data=" << btd->data.ptr.buffer << " (" << (void*)btd->data_size
150         << " bytes)" << endl
151         << "offsets=" << btd->data.ptr.offsets << " (" << (void*)btd->offsets_size
152         << " bytes)";
153     return btd+1;
154 }
155 
printReturnCommand(TextOutput & out,const void * _cmd)156 static const void* printReturnCommand(TextOutput& out, const void* _cmd)
157 {
158     static const size_t N = sizeof(kReturnStrings)/sizeof(kReturnStrings[0]);
159     const int32_t* cmd = (const int32_t*)_cmd;
160     int32_t code = *cmd++;
161     size_t cmdIndex = code & 0xff;
162     if (code == (int32_t) BR_ERROR) {
163         out << "BR_ERROR: " << (void*)(*cmd++) << endl;
164         return cmd;
165     } else if (cmdIndex >= N) {
166         out << "Unknown reply: " << code << endl;
167         return cmd;
168     }
169     out << kReturnStrings[cmdIndex];
170 
171     switch (code) {
172         case BR_TRANSACTION:
173         case BR_REPLY: {
174             out << ": " << indent;
175             cmd = (const int32_t *)printBinderTransactionData(out, cmd);
176             out << dedent;
177         } break;
178 
179         case BR_ACQUIRE_RESULT: {
180             const int32_t res = *cmd++;
181             out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
182         } break;
183 
184         case BR_INCREFS:
185         case BR_ACQUIRE:
186         case BR_RELEASE:
187         case BR_DECREFS: {
188             const int32_t b = *cmd++;
189             const int32_t c = *cmd++;
190             out << ": target=" << (void*)b << " (cookie " << (void*)c << ")";
191         } break;
192 
193         case BR_ATTEMPT_ACQUIRE: {
194             const int32_t p = *cmd++;
195             const int32_t b = *cmd++;
196             const int32_t c = *cmd++;
197             out << ": target=" << (void*)b << " (cookie " << (void*)c
198                 << "), pri=" << p;
199         } break;
200 
201         case BR_DEAD_BINDER:
202         case BR_CLEAR_DEATH_NOTIFICATION_DONE: {
203             const int32_t c = *cmd++;
204             out << ": death cookie " << (void*)c;
205         } break;
206 
207         default:
208             // no details to show for: BR_OK, BR_DEAD_REPLY,
209             // BR_TRANSACTION_COMPLETE, BR_FINISHED
210             break;
211     }
212 
213     out << endl;
214     return cmd;
215 }
216 
printCommand(TextOutput & out,const void * _cmd)217 static const void* printCommand(TextOutput& out, const void* _cmd)
218 {
219     static const size_t N = sizeof(kCommandStrings)/sizeof(kCommandStrings[0]);
220     const int32_t* cmd = (const int32_t*)_cmd;
221     int32_t code = *cmd++;
222     size_t cmdIndex = code & 0xff;
223 
224     if (cmdIndex >= N) {
225         out << "Unknown command: " << code << endl;
226         return cmd;
227     }
228     out << kCommandStrings[cmdIndex];
229 
230     switch (code) {
231         case BC_TRANSACTION:
232         case BC_REPLY: {
233             out << ": " << indent;
234             cmd = (const int32_t *)printBinderTransactionData(out, cmd);
235             out << dedent;
236         } break;
237 
238         case BC_ACQUIRE_RESULT: {
239             const int32_t res = *cmd++;
240             out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
241         } break;
242 
243         case BC_FREE_BUFFER: {
244             const int32_t buf = *cmd++;
245             out << ": buffer=" << (void*)buf;
246         } break;
247 
248         case BC_INCREFS:
249         case BC_ACQUIRE:
250         case BC_RELEASE:
251         case BC_DECREFS: {
252             const int32_t d = *cmd++;
253             out << ": desc=" << d;
254         } break;
255 
256         case BC_INCREFS_DONE:
257         case BC_ACQUIRE_DONE: {
258             const int32_t b = *cmd++;
259             const int32_t c = *cmd++;
260             out << ": target=" << (void*)b << " (cookie " << (void*)c << ")";
261         } break;
262 
263         case BC_ATTEMPT_ACQUIRE: {
264             const int32_t p = *cmd++;
265             const int32_t d = *cmd++;
266             out << ": desc=" << d << ", pri=" << p;
267         } break;
268 
269         case BC_REQUEST_DEATH_NOTIFICATION:
270         case BC_CLEAR_DEATH_NOTIFICATION: {
271             const int32_t h = *cmd++;
272             const int32_t c = *cmd++;
273             out << ": handle=" << h << " (death cookie " << (void*)c << ")";
274         } break;
275 
276         case BC_DEAD_BINDER_DONE: {
277             const int32_t c = *cmd++;
278             out << ": death cookie " << (void*)c;
279         } break;
280 
281         default:
282             // no details to show for: BC_REGISTER_LOOPER, BC_ENTER_LOOPER,
283             // BC_EXIT_LOOPER
284             break;
285     }
286 
287     out << endl;
288     return cmd;
289 }
290 #endif
291 
292 static pthread_mutex_t gTLSMutex = PTHREAD_MUTEX_INITIALIZER;
293 static bool gHaveTLS = false;
294 static pthread_key_t gTLS = 0;
295 static bool gShutdown = false;
296 static bool gDisableBackgroundScheduling = false;
297 
self()298 IPCThreadState* IPCThreadState::self()
299 {
300     if (gHaveTLS) {
301 restart:
302         const pthread_key_t k = gTLS;
303         IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
304         if (st) return st;
305         return new IPCThreadState;
306     }
307 
308     if (gShutdown) return NULL;
309 
310     pthread_mutex_lock(&gTLSMutex);
311     if (!gHaveTLS) {
312         if (pthread_key_create(&gTLS, threadDestructor) != 0) {
313             pthread_mutex_unlock(&gTLSMutex);
314             return NULL;
315         }
316         gHaveTLS = true;
317     }
318     pthread_mutex_unlock(&gTLSMutex);
319     goto restart;
320 }
321 
selfOrNull()322 IPCThreadState* IPCThreadState::selfOrNull()
323 {
324     if (gHaveTLS) {
325         const pthread_key_t k = gTLS;
326         IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
327         return st;
328     }
329     return NULL;
330 }
331 
shutdown()332 void IPCThreadState::shutdown()
333 {
334     gShutdown = true;
335 
336     if (gHaveTLS) {
337         // XXX Need to wait for all thread pool threads to exit!
338         IPCThreadState* st = (IPCThreadState*)pthread_getspecific(gTLS);
339         if (st) {
340             delete st;
341             pthread_setspecific(gTLS, NULL);
342         }
343         gHaveTLS = false;
344     }
345 }
346 
disableBackgroundScheduling(bool disable)347 void IPCThreadState::disableBackgroundScheduling(bool disable)
348 {
349     gDisableBackgroundScheduling = disable;
350 }
351 
process()352 sp<ProcessState> IPCThreadState::process()
353 {
354     return mProcess;
355 }
356 
clearLastError()357 status_t IPCThreadState::clearLastError()
358 {
359     const status_t err = mLastError;
360     mLastError = NO_ERROR;
361     return err;
362 }
363 
getCallingPid() const364 int IPCThreadState::getCallingPid() const
365 {
366     return mCallingPid;
367 }
368 
getCallingUid() const369 int IPCThreadState::getCallingUid() const
370 {
371     return mCallingUid;
372 }
373 
clearCallingIdentity()374 int64_t IPCThreadState::clearCallingIdentity()
375 {
376     int64_t token = ((int64_t)mCallingUid<<32) | mCallingPid;
377     clearCaller();
378     return token;
379 }
380 
setStrictModePolicy(int32_t policy)381 void IPCThreadState::setStrictModePolicy(int32_t policy)
382 {
383     mStrictModePolicy = policy;
384 }
385 
getStrictModePolicy() const386 int32_t IPCThreadState::getStrictModePolicy() const
387 {
388     return mStrictModePolicy;
389 }
390 
setLastTransactionBinderFlags(int32_t flags)391 void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
392 {
393     mLastTransactionBinderFlags = flags;
394 }
395 
getLastTransactionBinderFlags() const396 int32_t IPCThreadState::getLastTransactionBinderFlags() const
397 {
398     return mLastTransactionBinderFlags;
399 }
400 
restoreCallingIdentity(int64_t token)401 void IPCThreadState::restoreCallingIdentity(int64_t token)
402 {
403     mCallingUid = (int)(token>>32);
404     mCallingPid = (int)token;
405 }
406 
clearCaller()407 void IPCThreadState::clearCaller()
408 {
409     mCallingPid = getpid();
410     mCallingUid = getuid();
411 }
412 
flushCommands()413 void IPCThreadState::flushCommands()
414 {
415     if (mProcess->mDriverFD <= 0)
416         return;
417     talkWithDriver(false);
418 }
419 
getAndExecuteCommand()420 status_t IPCThreadState::getAndExecuteCommand()
421 {
422     status_t result;
423     int32_t cmd;
424 
425     result = talkWithDriver();
426     if (result >= NO_ERROR) {
427         size_t IN = mIn.dataAvail();
428         if (IN < sizeof(int32_t)) return result;
429         cmd = mIn.readInt32();
430         IF_LOG_COMMANDS() {
431             alog << "Processing top-level Command: "
432                  << getReturnString(cmd) << endl;
433         }
434 
435         result = executeCommand(cmd);
436 
437         // After executing the command, ensure that the thread is returned to the
438         // foreground cgroup before rejoining the pool.  The driver takes care of
439         // restoring the priority, but doesn't do anything with cgroups so we
440         // need to take care of that here in userspace.  Note that we do make
441         // sure to go in the foreground after executing a transaction, but
442         // there are other callbacks into user code that could have changed
443         // our group so we want to make absolutely sure it is put back.
444         set_sched_policy(mMyThreadId, SP_FOREGROUND);
445     }
446 
447     return result;
448 }
449 
450 // When we've cleared the incoming command queue, process any pending derefs
processPendingDerefs()451 void IPCThreadState::processPendingDerefs()
452 {
453     if (mIn.dataPosition() >= mIn.dataSize()) {
454         size_t numPending = mPendingWeakDerefs.size();
455         if (numPending > 0) {
456             for (size_t i = 0; i < numPending; i++) {
457                 RefBase::weakref_type* refs = mPendingWeakDerefs[i];
458                 refs->decWeak(mProcess.get());
459             }
460             mPendingWeakDerefs.clear();
461         }
462 
463         numPending = mPendingStrongDerefs.size();
464         if (numPending > 0) {
465             for (size_t i = 0; i < numPending; i++) {
466                 BBinder* obj = mPendingStrongDerefs[i];
467                 obj->decStrong(mProcess.get());
468             }
469             mPendingStrongDerefs.clear();
470         }
471     }
472 }
473 
joinThreadPool(bool isMain)474 void IPCThreadState::joinThreadPool(bool isMain)
475 {
476     LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
477 
478     mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
479 
480     // This thread may have been spawned by a thread that was in the background
481     // scheduling group, so first we will make sure it is in the foreground
482     // one to avoid performing an initial transaction in the background.
483     set_sched_policy(mMyThreadId, SP_FOREGROUND);
484 
485     status_t result;
486     do {
487         processPendingDerefs();
488         // now get the next command to be processed, waiting if necessary
489         result = getAndExecuteCommand();
490 
491         if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
492             ALOGE("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
493                   mProcess->mDriverFD, result);
494             abort();
495         }
496 
497         // Let this thread exit the thread pool if it is no longer
498         // needed and it is not the main process thread.
499         if(result == TIMED_OUT && !isMain) {
500             break;
501         }
502     } while (result != -ECONNREFUSED && result != -EBADF);
503 
504     LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%p\n",
505         (void*)pthread_self(), getpid(), (void*)result);
506 
507     mOut.writeInt32(BC_EXIT_LOOPER);
508     talkWithDriver(false);
509 }
510 
setupPolling(int * fd)511 int IPCThreadState::setupPolling(int* fd)
512 {
513     if (mProcess->mDriverFD <= 0) {
514         return -EBADF;
515     }
516 
517     mOut.writeInt32(BC_ENTER_LOOPER);
518     *fd = mProcess->mDriverFD;
519     return 0;
520 }
521 
handlePolledCommands()522 status_t IPCThreadState::handlePolledCommands()
523 {
524     status_t result;
525 
526     do {
527         result = getAndExecuteCommand();
528     } while (mIn.dataPosition() < mIn.dataSize());
529 
530     processPendingDerefs();
531     flushCommands();
532     return result;
533 }
534 
stopProcess(bool)535 void IPCThreadState::stopProcess(bool /*immediate*/)
536 {
537     //ALOGI("**** STOPPING PROCESS");
538     flushCommands();
539     int fd = mProcess->mDriverFD;
540     mProcess->mDriverFD = -1;
541     close(fd);
542     //kill(getpid(), SIGKILL);
543 }
544 
transact(int32_t handle,uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)545 status_t IPCThreadState::transact(int32_t handle,
546                                   uint32_t code, const Parcel& data,
547                                   Parcel* reply, uint32_t flags)
548 {
549     status_t err = data.errorCheck();
550 
551     flags |= TF_ACCEPT_FDS;
552 
553     IF_LOG_TRANSACTIONS() {
554         TextOutput::Bundle _b(alog);
555         alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
556             << handle << " / code " << TypeCode(code) << ": "
557             << indent << data << dedent << endl;
558     }
559 
560     if (err == NO_ERROR) {
561         LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
562             (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
563         err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);
564     }
565 
566     if (err != NO_ERROR) {
567         if (reply) reply->setError(err);
568         return (mLastError = err);
569     }
570 
571     if ((flags & TF_ONE_WAY) == 0) {
572         #if 0
573         if (code == 4) { // relayout
574             ALOGI(">>>>>> CALLING transaction 4");
575         } else {
576             ALOGI(">>>>>> CALLING transaction %d", code);
577         }
578         #endif
579         if (reply) {
580             err = waitForResponse(reply);
581         } else {
582             Parcel fakeReply;
583             err = waitForResponse(&fakeReply);
584         }
585         #if 0
586         if (code == 4) { // relayout
587             ALOGI("<<<<<< RETURNING transaction 4");
588         } else {
589             ALOGI("<<<<<< RETURNING transaction %d", code);
590         }
591         #endif
592 
593         IF_LOG_TRANSACTIONS() {
594             TextOutput::Bundle _b(alog);
595             alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
596                 << handle << ": ";
597             if (reply) alog << indent << *reply << dedent << endl;
598             else alog << "(none requested)" << endl;
599         }
600     } else {
601         err = waitForResponse(NULL, NULL);
602     }
603 
604     return err;
605 }
606 
incStrongHandle(int32_t handle)607 void IPCThreadState::incStrongHandle(int32_t handle)
608 {
609     LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
610     mOut.writeInt32(BC_ACQUIRE);
611     mOut.writeInt32(handle);
612 }
613 
decStrongHandle(int32_t handle)614 void IPCThreadState::decStrongHandle(int32_t handle)
615 {
616     LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
617     mOut.writeInt32(BC_RELEASE);
618     mOut.writeInt32(handle);
619 }
620 
incWeakHandle(int32_t handle)621 void IPCThreadState::incWeakHandle(int32_t handle)
622 {
623     LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
624     mOut.writeInt32(BC_INCREFS);
625     mOut.writeInt32(handle);
626 }
627 
decWeakHandle(int32_t handle)628 void IPCThreadState::decWeakHandle(int32_t handle)
629 {
630     LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
631     mOut.writeInt32(BC_DECREFS);
632     mOut.writeInt32(handle);
633 }
634 
attemptIncStrongHandle(int32_t handle)635 status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
636 {
637 #if HAS_BC_ATTEMPT_ACQUIRE
638     LOG_REMOTEREFS("IPCThreadState::attemptIncStrongHandle(%d)\n", handle);
639     mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
640     mOut.writeInt32(0); // xxx was thread priority
641     mOut.writeInt32(handle);
642     status_t result = UNKNOWN_ERROR;
643 
644     waitForResponse(NULL, &result);
645 
646 #if LOG_REFCOUNTS
647     printf("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
648         handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
649 #endif
650 
651     return result;
652 #else
653     (void)handle;
654     ALOGE("%s(%d): Not supported\n", __func__, handle);
655     return INVALID_OPERATION;
656 #endif
657 }
658 
expungeHandle(int32_t handle,IBinder * binder)659 void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
660 {
661 #if LOG_REFCOUNTS
662     printf("IPCThreadState::expungeHandle(%ld)\n", handle);
663 #endif
664     self()->mProcess->expungeHandle(handle, binder);
665 }
666 
requestDeathNotification(int32_t handle,BpBinder * proxy)667 status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
668 {
669     mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
670     mOut.writeInt32((int32_t)handle);
671     mOut.writePointer((uintptr_t)proxy);
672     return NO_ERROR;
673 }
674 
clearDeathNotification(int32_t handle,BpBinder * proxy)675 status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
676 {
677     mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
678     mOut.writeInt32((int32_t)handle);
679     mOut.writePointer((uintptr_t)proxy);
680     return NO_ERROR;
681 }
682 
IPCThreadState()683 IPCThreadState::IPCThreadState()
684     : mProcess(ProcessState::self()),
685       mMyThreadId(androidGetTid()),
686       mStrictModePolicy(0),
687       mLastTransactionBinderFlags(0)
688 {
689     pthread_setspecific(gTLS, this);
690     clearCaller();
691     mIn.setDataCapacity(256);
692     mOut.setDataCapacity(256);
693 }
694 
~IPCThreadState()695 IPCThreadState::~IPCThreadState()
696 {
697 }
698 
sendReply(const Parcel & reply,uint32_t flags)699 status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
700 {
701     status_t err;
702     status_t statusBuffer;
703     err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
704     if (err < NO_ERROR) return err;
705 
706     return waitForResponse(NULL, NULL);
707 }
708 
waitForResponse(Parcel * reply,status_t * acquireResult)709 status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
710 {
711     int32_t cmd;
712     int32_t err;
713 
714     while (1) {
715         if ((err=talkWithDriver()) < NO_ERROR) break;
716         err = mIn.errorCheck();
717         if (err < NO_ERROR) break;
718         if (mIn.dataAvail() == 0) continue;
719 
720         cmd = mIn.readInt32();
721 
722         IF_LOG_COMMANDS() {
723             alog << "Processing waitForResponse Command: "
724                 << getReturnString(cmd) << endl;
725         }
726 
727         switch (cmd) {
728         case BR_TRANSACTION_COMPLETE:
729             if (!reply && !acquireResult) goto finish;
730             break;
731 
732         case BR_DEAD_REPLY:
733             err = DEAD_OBJECT;
734             goto finish;
735 
736         case BR_FAILED_REPLY:
737             err = FAILED_TRANSACTION;
738             goto finish;
739 
740         case BR_ACQUIRE_RESULT:
741             {
742                 ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
743                 const int32_t result = mIn.readInt32();
744                 if (!acquireResult) continue;
745                 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
746             }
747             goto finish;
748 
749         case BR_REPLY:
750             {
751                 binder_transaction_data tr;
752                 err = mIn.read(&tr, sizeof(tr));
753                 ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
754                 if (err != NO_ERROR) goto finish;
755 
756                 if (reply) {
757                     if ((tr.flags & TF_STATUS_CODE) == 0) {
758                         reply->ipcSetDataReference(
759                             reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
760                             tr.data_size,
761                             reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
762                             tr.offsets_size/sizeof(binder_size_t),
763                             freeBuffer, this);
764                     } else {
765                         err = *reinterpret_cast<const status_t*>(tr.data.ptr.buffer);
766                         freeBuffer(NULL,
767                             reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
768                             tr.data_size,
769                             reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
770                             tr.offsets_size/sizeof(binder_size_t), this);
771                     }
772                 } else {
773                     freeBuffer(NULL,
774                         reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
775                         tr.data_size,
776                         reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
777                         tr.offsets_size/sizeof(binder_size_t), this);
778                     continue;
779                 }
780             }
781             goto finish;
782 
783         default:
784             err = executeCommand(cmd);
785             if (err != NO_ERROR) goto finish;
786             break;
787         }
788     }
789 
790 finish:
791     if (err != NO_ERROR) {
792         if (acquireResult) *acquireResult = err;
793         if (reply) reply->setError(err);
794         mLastError = err;
795     }
796 
797     return err;
798 }
799 
talkWithDriver(bool doReceive)800 status_t IPCThreadState::talkWithDriver(bool doReceive)
801 {
802     if (mProcess->mDriverFD <= 0) {
803         return -EBADF;
804     }
805 
806     binder_write_read bwr;
807 
808     // Is the read buffer empty?
809     const bool needRead = mIn.dataPosition() >= mIn.dataSize();
810 
811     // We don't want to write anything if we are still reading
812     // from data left in the input buffer and the caller
813     // has requested to read the next data.
814     const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
815 
816     bwr.write_size = outAvail;
817     bwr.write_buffer = (uintptr_t)mOut.data();
818 
819     // This is what we'll read.
820     if (doReceive && needRead) {
821         bwr.read_size = mIn.dataCapacity();
822         bwr.read_buffer = (uintptr_t)mIn.data();
823     } else {
824         bwr.read_size = 0;
825         bwr.read_buffer = 0;
826     }
827 
828     IF_LOG_COMMANDS() {
829         TextOutput::Bundle _b(alog);
830         if (outAvail != 0) {
831             alog << "Sending commands to driver: " << indent;
832             const void* cmds = (const void*)bwr.write_buffer;
833             const void* end = ((const uint8_t*)cmds)+bwr.write_size;
834             alog << HexDump(cmds, bwr.write_size) << endl;
835             while (cmds < end) cmds = printCommand(alog, cmds);
836             alog << dedent;
837         }
838         alog << "Size of receive buffer: " << bwr.read_size
839             << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
840     }
841 
842     // Return immediately if there is nothing to do.
843     if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
844 
845     bwr.write_consumed = 0;
846     bwr.read_consumed = 0;
847     status_t err;
848     do {
849         IF_LOG_COMMANDS() {
850             alog << "About to read/write, write size = " << mOut.dataSize() << endl;
851         }
852 #if defined(HAVE_ANDROID_OS)
853         if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
854             err = NO_ERROR;
855         else
856             err = -errno;
857 #else
858         err = INVALID_OPERATION;
859 #endif
860         if (mProcess->mDriverFD <= 0) {
861             err = -EBADF;
862         }
863         IF_LOG_COMMANDS() {
864             alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
865         }
866     } while (err == -EINTR);
867 
868     IF_LOG_COMMANDS() {
869         alog << "Our err: " << (void*)(intptr_t)err << ", write consumed: "
870             << bwr.write_consumed << " (of " << mOut.dataSize()
871                         << "), read consumed: " << bwr.read_consumed << endl;
872     }
873 
874     if (err >= NO_ERROR) {
875         if (bwr.write_consumed > 0) {
876             if (bwr.write_consumed < mOut.dataSize())
877                 mOut.remove(0, bwr.write_consumed);
878             else
879                 mOut.setDataSize(0);
880         }
881         if (bwr.read_consumed > 0) {
882             mIn.setDataSize(bwr.read_consumed);
883             mIn.setDataPosition(0);
884         }
885         IF_LOG_COMMANDS() {
886             TextOutput::Bundle _b(alog);
887             alog << "Remaining data size: " << mOut.dataSize() << endl;
888             alog << "Received commands from driver: " << indent;
889             const void* cmds = mIn.data();
890             const void* end = mIn.data() + mIn.dataSize();
891             alog << HexDump(cmds, mIn.dataSize()) << endl;
892             while (cmds < end) cmds = printReturnCommand(alog, cmds);
893             alog << dedent;
894         }
895         return NO_ERROR;
896     }
897 
898     return err;
899 }
900 
writeTransactionData(int32_t cmd,uint32_t binderFlags,int32_t handle,uint32_t code,const Parcel & data,status_t * statusBuffer)901 status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
902     int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
903 {
904     binder_transaction_data tr;
905 
906     tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
907     tr.target.handle = handle;
908     tr.code = code;
909     tr.flags = binderFlags;
910     tr.cookie = 0;
911     tr.sender_pid = 0;
912     tr.sender_euid = 0;
913 
914     const status_t err = data.errorCheck();
915     if (err == NO_ERROR) {
916         tr.data_size = data.ipcDataSize();
917         tr.data.ptr.buffer = data.ipcData();
918         tr.offsets_size = data.ipcObjectsCount()*sizeof(binder_size_t);
919         tr.data.ptr.offsets = data.ipcObjects();
920     } else if (statusBuffer) {
921         tr.flags |= TF_STATUS_CODE;
922         *statusBuffer = err;
923         tr.data_size = sizeof(status_t);
924         tr.data.ptr.buffer = reinterpret_cast<uintptr_t>(statusBuffer);
925         tr.offsets_size = 0;
926         tr.data.ptr.offsets = 0;
927     } else {
928         return (mLastError = err);
929     }
930 
931     mOut.writeInt32(cmd);
932     mOut.write(&tr, sizeof(tr));
933 
934     return NO_ERROR;
935 }
936 
937 sp<BBinder> the_context_object;
938 
setTheContextObject(sp<BBinder> obj)939 void setTheContextObject(sp<BBinder> obj)
940 {
941     the_context_object = obj;
942 }
943 
executeCommand(int32_t cmd)944 status_t IPCThreadState::executeCommand(int32_t cmd)
945 {
946     BBinder* obj;
947     RefBase::weakref_type* refs;
948     status_t result = NO_ERROR;
949 
950     switch (cmd) {
951     case BR_ERROR:
952         result = mIn.readInt32();
953         break;
954 
955     case BR_OK:
956         break;
957 
958     case BR_ACQUIRE:
959         refs = (RefBase::weakref_type*)mIn.readPointer();
960         obj = (BBinder*)mIn.readPointer();
961         ALOG_ASSERT(refs->refBase() == obj,
962                    "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
963                    refs, obj, refs->refBase());
964         obj->incStrong(mProcess.get());
965         IF_LOG_REMOTEREFS() {
966             LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
967             obj->printRefs();
968         }
969         mOut.writeInt32(BC_ACQUIRE_DONE);
970         mOut.writePointer((uintptr_t)refs);
971         mOut.writePointer((uintptr_t)obj);
972         break;
973 
974     case BR_RELEASE:
975         refs = (RefBase::weakref_type*)mIn.readPointer();
976         obj = (BBinder*)mIn.readPointer();
977         ALOG_ASSERT(refs->refBase() == obj,
978                    "BR_RELEASE: object %p does not match cookie %p (expected %p)",
979                    refs, obj, refs->refBase());
980         IF_LOG_REMOTEREFS() {
981             LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
982             obj->printRefs();
983         }
984         mPendingStrongDerefs.push(obj);
985         break;
986 
987     case BR_INCREFS:
988         refs = (RefBase::weakref_type*)mIn.readPointer();
989         obj = (BBinder*)mIn.readPointer();
990         refs->incWeak(mProcess.get());
991         mOut.writeInt32(BC_INCREFS_DONE);
992         mOut.writePointer((uintptr_t)refs);
993         mOut.writePointer((uintptr_t)obj);
994         break;
995 
996     case BR_DECREFS:
997         refs = (RefBase::weakref_type*)mIn.readPointer();
998         obj = (BBinder*)mIn.readPointer();
999         // NOTE: This assertion is not valid, because the object may no
1000         // longer exist (thus the (BBinder*)cast above resulting in a different
1001         // memory address).
1002         //ALOG_ASSERT(refs->refBase() == obj,
1003         //           "BR_DECREFS: object %p does not match cookie %p (expected %p)",
1004         //           refs, obj, refs->refBase());
1005         mPendingWeakDerefs.push(refs);
1006         break;
1007 
1008     case BR_ATTEMPT_ACQUIRE:
1009         refs = (RefBase::weakref_type*)mIn.readPointer();
1010         obj = (BBinder*)mIn.readPointer();
1011 
1012         {
1013             const bool success = refs->attemptIncStrong(mProcess.get());
1014             ALOG_ASSERT(success && refs->refBase() == obj,
1015                        "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
1016                        refs, obj, refs->refBase());
1017 
1018             mOut.writeInt32(BC_ACQUIRE_RESULT);
1019             mOut.writeInt32((int32_t)success);
1020         }
1021         break;
1022 
1023     case BR_TRANSACTION:
1024         {
1025             binder_transaction_data tr;
1026             result = mIn.read(&tr, sizeof(tr));
1027             ALOG_ASSERT(result == NO_ERROR,
1028                 "Not enough command data for brTRANSACTION");
1029             if (result != NO_ERROR) break;
1030 
1031             Parcel buffer;
1032             buffer.ipcSetDataReference(
1033                 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1034                 tr.data_size,
1035                 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1036                 tr.offsets_size/sizeof(binder_size_t), freeBuffer, this);
1037 
1038             const pid_t origPid = mCallingPid;
1039             const uid_t origUid = mCallingUid;
1040             const int32_t origStrictModePolicy = mStrictModePolicy;
1041             const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
1042 
1043             mCallingPid = tr.sender_pid;
1044             mCallingUid = tr.sender_euid;
1045             mLastTransactionBinderFlags = tr.flags;
1046 
1047             int curPrio = getpriority(PRIO_PROCESS, mMyThreadId);
1048             if (gDisableBackgroundScheduling) {
1049                 if (curPrio > ANDROID_PRIORITY_NORMAL) {
1050                     // We have inherited a reduced priority from the caller, but do not
1051                     // want to run in that state in this process.  The driver set our
1052                     // priority already (though not our scheduling class), so bounce
1053                     // it back to the default before invoking the transaction.
1054                     setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL);
1055                 }
1056             } else {
1057                 if (curPrio >= ANDROID_PRIORITY_BACKGROUND) {
1058                     // We want to use the inherited priority from the caller.
1059                     // Ensure this thread is in the background scheduling class,
1060                     // since the driver won't modify scheduling classes for us.
1061                     // The scheduling group is reset to default by the caller
1062                     // once this method returns after the transaction is complete.
1063                     set_sched_policy(mMyThreadId, SP_BACKGROUND);
1064                 }
1065             }
1066 
1067             //ALOGI(">>>> TRANSACT from pid %d uid %d\n", mCallingPid, mCallingUid);
1068 
1069             Parcel reply;
1070             status_t error;
1071             IF_LOG_TRANSACTIONS() {
1072                 TextOutput::Bundle _b(alog);
1073                 alog << "BR_TRANSACTION thr " << (void*)pthread_self()
1074                     << " / obj " << tr.target.ptr << " / code "
1075                     << TypeCode(tr.code) << ": " << indent << buffer
1076                     << dedent << endl
1077                     << "Data addr = "
1078                     << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1079                     << ", offsets addr="
1080                     << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
1081             }
1082             if (tr.target.ptr) {
1083                 sp<BBinder> b((BBinder*)tr.cookie);
1084                 error = b->transact(tr.code, buffer, &reply, tr.flags);
1085 
1086             } else {
1087                 error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
1088             }
1089 
1090             //ALOGI("<<<< TRANSACT from pid %d restore pid %d uid %d\n",
1091             //     mCallingPid, origPid, origUid);
1092 
1093             if ((tr.flags & TF_ONE_WAY) == 0) {
1094                 LOG_ONEWAY("Sending reply to %d!", mCallingPid);
1095                 if (error < NO_ERROR) reply.setError(error);
1096                 sendReply(reply, 0);
1097             } else {
1098                 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1099             }
1100 
1101             mCallingPid = origPid;
1102             mCallingUid = origUid;
1103             mStrictModePolicy = origStrictModePolicy;
1104             mLastTransactionBinderFlags = origTransactionBinderFlags;
1105 
1106             IF_LOG_TRANSACTIONS() {
1107                 TextOutput::Bundle _b(alog);
1108                 alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
1109                     << tr.target.ptr << ": " << indent << reply << dedent << endl;
1110             }
1111 
1112         }
1113         break;
1114 
1115     case BR_DEAD_BINDER:
1116         {
1117             BpBinder *proxy = (BpBinder*)mIn.readPointer();
1118             proxy->sendObituary();
1119             mOut.writeInt32(BC_DEAD_BINDER_DONE);
1120             mOut.writePointer((uintptr_t)proxy);
1121         } break;
1122 
1123     case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1124         {
1125             BpBinder *proxy = (BpBinder*)mIn.readPointer();
1126             proxy->getWeakRefs()->decWeak(proxy);
1127         } break;
1128 
1129     case BR_FINISHED:
1130         result = TIMED_OUT;
1131         break;
1132 
1133     case BR_NOOP:
1134         break;
1135 
1136     case BR_SPAWN_LOOPER:
1137         mProcess->spawnPooledThread(false);
1138         break;
1139 
1140     default:
1141         printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
1142         result = UNKNOWN_ERROR;
1143         break;
1144     }
1145 
1146     if (result != NO_ERROR) {
1147         mLastError = result;
1148     }
1149 
1150     return result;
1151 }
1152 
threadDestructor(void * st)1153 void IPCThreadState::threadDestructor(void *st)
1154 {
1155         IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1156         if (self) {
1157                 self->flushCommands();
1158 #if defined(HAVE_ANDROID_OS)
1159         if (self->mProcess->mDriverFD > 0) {
1160             ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1161         }
1162 #endif
1163                 delete self;
1164         }
1165 }
1166 
1167 
freeBuffer(Parcel * parcel,const uint8_t * data,size_t,const binder_size_t *,size_t,void *)1168 void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data,
1169                                 size_t /*dataSize*/,
1170                                 const binder_size_t* /*objects*/,
1171                                 size_t /*objectsSize*/, void* /*cookie*/)
1172 {
1173     //ALOGI("Freeing parcel %p", &parcel);
1174     IF_LOG_COMMANDS() {
1175         alog << "Writing BC_FREE_BUFFER for " << data << endl;
1176     }
1177     ALOG_ASSERT(data != NULL, "Called with NULL data");
1178     if (parcel != NULL) parcel->closeFileDescriptors();
1179     IPCThreadState* state = self();
1180     state->mOut.writeInt32(BC_FREE_BUFFER);
1181     state->mOut.writePointer((uintptr_t)data);
1182 }
1183 
1184 }; // namespace android
1185