2 * Copyright (C) 2005 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define LOG_TAG "IPCThreadState"
19 #include <binder/IPCThreadState.h>
21 #include <binder/Binder.h>
22 #include <binder/BpBinder.h>
23 #include <binder/TextOutput.h>
25 #include <cutils/sched_policy.h>
26 #include <utils/Log.h>
27 #include <utils/threads.h>
29 #include <private/binder/binder_module.h>
30 #include <private/binder/Static.h>
32 #include <sys/ioctl.h>
41 #include <sys/resource.h>
43 #ifdef HAVE_WIN32_THREADS
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(...)
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__)
68 // ---------------------------------------------------------------------------
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);
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.
80 static const char *kReturnStrings[] = {
87 "BR_TRANSACTION_COMPLETE",
97 "BR_CLEAR_DEATH_NOTIFICATION_DONE",
101 static const char *kCommandStrings[] = {
112 "BC_ATTEMPT_ACQUIRE",
113 "BC_REGISTER_LOOPER",
116 "BC_REQUEST_DEATH_NOTIFICATION",
117 "BC_CLEAR_DEATH_NOTIFICATION",
118 "BC_DEAD_BINDER_DONE"
121 static const char* getReturnString(size_t idx)
123 if (idx < sizeof(kReturnStrings) / sizeof(kReturnStrings[0]))
124 return kReturnStrings[idx];
129 static const char* getCommandString(size_t idx)
131 if (idx < sizeof(kCommandStrings) / sizeof(kCommandStrings[0]))
132 return kCommandStrings[idx];
137 static const void* printBinderTransactionData(TextOutput& out, const void* data)
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;
145 out << "target.ptr=" << btd->target.ptr;
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
151 << "offsets=" << btd->data.ptr.offsets << " (" << (void*)btd->offsets_size
156 static const void* printReturnCommand(TextOutput& out, const void* _cmd)
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;
165 } else if (cmdIndex >= N) {
166 out << "Unknown reply: " << code << endl;
169 out << kReturnStrings[cmdIndex];
174 out << ": " << indent;
175 cmd = (const int32_t *)printBinderTransactionData(out, cmd);
179 case BR_ACQUIRE_RESULT: {
180 const int32_t res = *cmd++;
181 out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
188 const int32_t b = *cmd++;
189 const int32_t c = *cmd++;
190 out << ": target=" << (void*)b << " (cookie " << (void*)c << ")";
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
202 case BR_CLEAR_DEATH_NOTIFICATION_DONE: {
203 const int32_t c = *cmd++;
204 out << ": death cookie " << (void*)c;
208 // no details to show for: BR_OK, BR_DEAD_REPLY,
209 // BR_TRANSACTION_COMPLETE, BR_FINISHED
217 static const void* printCommand(TextOutput& out, const void* _cmd)
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;
225 out << "Unknown command: " << code << endl;
228 out << kCommandStrings[cmdIndex];
233 out << ": " << indent;
234 cmd = (const int32_t *)printBinderTransactionData(out, cmd);
238 case BC_ACQUIRE_RESULT: {
239 const int32_t res = *cmd++;
240 out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
243 case BC_FREE_BUFFER: {
244 const int32_t buf = *cmd++;
245 out << ": buffer=" << (void*)buf;
252 const int32_t d = *cmd++;
253 out << ": desc=" << d;
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 << ")";
263 case BC_ATTEMPT_ACQUIRE: {
264 const int32_t p = *cmd++;
265 const int32_t d = *cmd++;
266 out << ": desc=" << d << ", pri=" << p;
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 << ")";
276 case BC_DEAD_BINDER_DONE: {
277 const int32_t c = *cmd++;
278 out << ": death cookie " << (void*)c;
282 // no details to show for: BC_REGISTER_LOOPER, BC_ENTER_LOOPER,
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;
298 IPCThreadState* IPCThreadState::self()
302 const pthread_key_t k = gTLS;
303 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
305 return new IPCThreadState;
308 if (gShutdown) return NULL;
310 pthread_mutex_lock(&gTLSMutex);
312 if (pthread_key_create(&gTLS, threadDestructor) != 0) {
313 pthread_mutex_unlock(&gTLSMutex);
318 pthread_mutex_unlock(&gTLSMutex);
322 IPCThreadState* IPCThreadState::selfOrNull()
325 const pthread_key_t k = gTLS;
326 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
332 void IPCThreadState::shutdown()
337 // XXX Need to wait for all thread pool threads to exit!
338 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(gTLS);
341 pthread_setspecific(gTLS, NULL);
347 void IPCThreadState::disableBackgroundScheduling(bool disable)
349 gDisableBackgroundScheduling = disable;
352 sp<ProcessState> IPCThreadState::process()
357 status_t IPCThreadState::clearLastError()
359 const status_t err = mLastError;
360 mLastError = NO_ERROR;
364 int IPCThreadState::getCallingPid() const
369 int IPCThreadState::getCallingUid() const
374 int64_t IPCThreadState::clearCallingIdentity()
376 int64_t token = ((int64_t)mCallingUid<<32) | mCallingPid;
381 void IPCThreadState::setStrictModePolicy(int32_t policy)
383 mStrictModePolicy = policy;
386 int32_t IPCThreadState::getStrictModePolicy() const
388 return mStrictModePolicy;
391 void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
393 mLastTransactionBinderFlags = flags;
396 int32_t IPCThreadState::getLastTransactionBinderFlags() const
398 return mLastTransactionBinderFlags;
401 void IPCThreadState::restoreCallingIdentity(int64_t token)
403 mCallingUid = (int)(token>>32);
404 mCallingPid = (int)token;
407 void IPCThreadState::clearCaller()
409 mCallingPid = getpid();
410 mCallingUid = getuid();
413 void IPCThreadState::flushCommands()
415 if (mProcess->mDriverFD <= 0)
417 talkWithDriver(false);
420 status_t IPCThreadState::getAndExecuteCommand()
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();
431 alog << "Processing top-level Command: "
432 << getReturnString(cmd) << endl;
435 result = executeCommand(cmd);
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);
450 // When we've cleared the incoming command queue, process any pending derefs
451 void IPCThreadState::processPendingDerefs()
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());
460 mPendingWeakDerefs.clear();
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());
469 mPendingStrongDerefs.clear();
474 void IPCThreadState::joinThreadPool(bool isMain)
476 LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
478 mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
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);
487 processPendingDerefs();
488 // now get the next command to be processed, waiting if necessary
489 result = getAndExecuteCommand();
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);
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) {
502 } while (result != -ECONNREFUSED && result != -EBADF);
504 LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%p\n",
505 (void*)pthread_self(), getpid(), (void*)result);
507 mOut.writeInt32(BC_EXIT_LOOPER);
508 talkWithDriver(false);
511 int IPCThreadState::setupPolling(int* fd)
513 if (mProcess->mDriverFD <= 0) {
517 mOut.writeInt32(BC_ENTER_LOOPER);
518 *fd = mProcess->mDriverFD;
522 status_t IPCThreadState::handlePolledCommands()
527 result = getAndExecuteCommand();
528 } while (mIn.dataPosition() < mIn.dataSize());
530 processPendingDerefs();
535 void IPCThreadState::stopProcess(bool /*immediate*/)
537 //ALOGI("**** STOPPING PROCESS");
539 int fd = mProcess->mDriverFD;
540 mProcess->mDriverFD = -1;
542 //kill(getpid(), SIGKILL);
545 status_t IPCThreadState::transact(int32_t handle,
546 uint32_t code, const Parcel& data,
547 Parcel* reply, uint32_t flags)
549 status_t err = data.errorCheck();
551 flags |= TF_ACCEPT_FDS;
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;
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);
566 if (err != NO_ERROR) {
567 if (reply) reply->setError(err);
568 return (mLastError = err);
571 if ((flags & TF_ONE_WAY) == 0) {
573 if (code == 4) { // relayout
574 ALOGI(">>>>>> CALLING transaction 4");
576 ALOGI(">>>>>> CALLING transaction %d", code);
580 err = waitForResponse(reply);
583 err = waitForResponse(&fakeReply);
586 if (code == 4) { // relayout
587 ALOGI("<<<<<< RETURNING transaction 4");
589 ALOGI("<<<<<< RETURNING transaction %d", code);
593 IF_LOG_TRANSACTIONS() {
594 TextOutput::Bundle _b(alog);
595 alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
597 if (reply) alog << indent << *reply << dedent << endl;
598 else alog << "(none requested)" << endl;
601 err = waitForResponse(NULL, NULL);
607 void IPCThreadState::incStrongHandle(int32_t handle)
609 LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
610 mOut.writeInt32(BC_ACQUIRE);
611 mOut.writeInt32(handle);
614 void IPCThreadState::decStrongHandle(int32_t handle)
616 LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
617 mOut.writeInt32(BC_RELEASE);
618 mOut.writeInt32(handle);
621 void IPCThreadState::incWeakHandle(int32_t handle)
623 LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
624 mOut.writeInt32(BC_INCREFS);
625 mOut.writeInt32(handle);
628 void IPCThreadState::decWeakHandle(int32_t handle)
630 LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
631 mOut.writeInt32(BC_DECREFS);
632 mOut.writeInt32(handle);
635 status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
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;
644 waitForResponse(NULL, &result);
647 printf("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
648 handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
654 ALOGE("%s(%d): Not supported\n", __func__, handle);
655 return INVALID_OPERATION;
659 void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
662 printf("IPCThreadState::expungeHandle(%ld)\n", handle);
664 self()->mProcess->expungeHandle(handle, binder);
667 status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
669 mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
670 mOut.writeInt32((int32_t)handle);
671 mOut.writePointer((uintptr_t)proxy);
675 status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
677 mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
678 mOut.writeInt32((int32_t)handle);
679 mOut.writePointer((uintptr_t)proxy);
683 IPCThreadState::IPCThreadState()
684 : mProcess(ProcessState::self()),
685 mMyThreadId(gettid()),
686 mStrictModePolicy(0),
687 mLastTransactionBinderFlags(0)
689 pthread_setspecific(gTLS, this);
691 mIn.setDataCapacity(256);
692 mOut.setDataCapacity(256);
695 IPCThreadState::~IPCThreadState()
699 status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
702 status_t statusBuffer;
703 err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
704 if (err < NO_ERROR) return err;
706 return waitForResponse(NULL, NULL);
709 status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
715 if ((err=talkWithDriver()) < NO_ERROR) break;
716 err = mIn.errorCheck();
717 if (err < NO_ERROR) break;
718 if (mIn.dataAvail() == 0) continue;
720 cmd = mIn.readInt32();
723 alog << "Processing waitForResponse Command: "
724 << getReturnString(cmd) << endl;
728 case BR_TRANSACTION_COMPLETE:
729 if (!reply && !acquireResult) goto finish;
736 case BR_FAILED_REPLY:
737 err = FAILED_TRANSACTION;
740 case BR_ACQUIRE_RESULT:
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;
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;
757 if ((tr.flags & TF_STATUS_CODE) == 0) {
758 reply->ipcSetDataReference(
759 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
761 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
762 tr.offsets_size/sizeof(binder_size_t),
765 err = *reinterpret_cast<const status_t*>(tr.data.ptr.buffer);
767 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
769 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
770 tr.offsets_size/sizeof(binder_size_t), this);
774 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
776 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
777 tr.offsets_size/sizeof(binder_size_t), this);
784 err = executeCommand(cmd);
785 if (err != NO_ERROR) goto finish;
791 if (err != NO_ERROR) {
792 if (acquireResult) *acquireResult = err;
793 if (reply) reply->setError(err);
800 status_t IPCThreadState::talkWithDriver(bool doReceive)
802 if (mProcess->mDriverFD <= 0) {
806 binder_write_read bwr;
808 // Is the read buffer empty?
809 const bool needRead = mIn.dataPosition() >= mIn.dataSize();
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;
816 bwr.write_size = outAvail;
817 bwr.write_buffer = (uintptr_t)mOut.data();
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();
829 TextOutput::Bundle _b(alog);
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);
838 alog << "Size of receive buffer: " << bwr.read_size
839 << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
842 // Return immediately if there is nothing to do.
843 if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
845 bwr.write_consumed = 0;
846 bwr.read_consumed = 0;
850 alog << "About to read/write, write size = " << mOut.dataSize() << endl;
852 #if defined(HAVE_ANDROID_OS)
853 if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
858 err = INVALID_OPERATION;
860 if (mProcess->mDriverFD <= 0) {
864 alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
866 } while (err == -EINTR);
869 alog << "Our err: " << (void*)(intptr_t)err << ", write consumed: "
870 << bwr.write_consumed << " (of " << mOut.dataSize()
871 << "), read consumed: " << bwr.read_consumed << endl;
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);
881 if (bwr.read_consumed > 0) {
882 mIn.setDataSize(bwr.read_consumed);
883 mIn.setDataPosition(0);
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);
901 status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
902 int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
904 binder_transaction_data tr;
906 tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
907 tr.target.handle = handle;
909 tr.flags = binderFlags;
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;
923 tr.data_size = sizeof(status_t);
924 tr.data.ptr.buffer = reinterpret_cast<uintptr_t>(statusBuffer);
926 tr.data.ptr.offsets = 0;
928 return (mLastError = err);
931 mOut.writeInt32(cmd);
932 mOut.write(&tr, sizeof(tr));
937 sp<BBinder> the_context_object;
939 void setTheContextObject(sp<BBinder> obj)
941 the_context_object = obj;
944 status_t IPCThreadState::executeCommand(int32_t cmd)
947 RefBase::weakref_type* refs;
948 status_t result = NO_ERROR;
952 result = mIn.readInt32();
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);
969 mOut.writeInt32(BC_ACQUIRE_DONE);
970 mOut.writePointer((uintptr_t)refs);
971 mOut.writePointer((uintptr_t)obj);
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);
984 mPendingStrongDerefs.push(obj);
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);
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
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);
1008 case BR_ATTEMPT_ACQUIRE:
1009 refs = (RefBase::weakref_type*)mIn.readPointer();
1010 obj = (BBinder*)mIn.readPointer();
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());
1018 mOut.writeInt32(BC_ACQUIRE_RESULT);
1019 mOut.writeInt32((int32_t)success);
1023 case BR_TRANSACTION:
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;
1032 buffer.ipcSetDataReference(
1033 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1035 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1036 tr.offsets_size/sizeof(binder_size_t), freeBuffer, this);
1038 const pid_t origPid = mCallingPid;
1039 const uid_t origUid = mCallingUid;
1040 const int32_t origStrictModePolicy = mStrictModePolicy;
1041 const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
1043 mCallingPid = tr.sender_pid;
1044 mCallingUid = tr.sender_euid;
1045 mLastTransactionBinderFlags = tr.flags;
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);
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);
1067 //ALOGI(">>>> TRANSACT from pid %d uid %d\n", mCallingPid, mCallingUid);
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
1078 << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1079 << ", offsets addr="
1080 << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
1082 if (tr.target.ptr) {
1083 sp<BBinder> b((BBinder*)tr.cookie);
1084 error = b->transact(tr.code, buffer, &reply, tr.flags);
1087 error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
1090 //ALOGI("<<<< TRANSACT from pid %d restore pid %d uid %d\n",
1091 // mCallingPid, origPid, origUid);
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);
1098 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1101 mCallingPid = origPid;
1102 mCallingUid = origUid;
1103 mStrictModePolicy = origStrictModePolicy;
1104 mLastTransactionBinderFlags = origTransactionBinderFlags;
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;
1115 case BR_DEAD_BINDER:
1117 BpBinder *proxy = (BpBinder*)mIn.readPointer();
1118 proxy->sendObituary();
1119 mOut.writeInt32(BC_DEAD_BINDER_DONE);
1120 mOut.writePointer((uintptr_t)proxy);
1123 case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1125 BpBinder *proxy = (BpBinder*)mIn.readPointer();
1126 proxy->getWeakRefs()->decWeak(proxy);
1136 case BR_SPAWN_LOOPER:
1137 mProcess->spawnPooledThread(false);
1141 printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
1142 result = UNKNOWN_ERROR;
1146 if (result != NO_ERROR) {
1147 mLastError = result;
1153 void IPCThreadState::threadDestructor(void *st)
1155 IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1157 self->flushCommands();
1158 #if defined(HAVE_ANDROID_OS)
1159 if (self->mProcess->mDriverFD > 0) {
1160 ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
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*/)
1173 //ALOGI("Freeing parcel %p", &parcel);
1175 alog << "Writing BC_FREE_BUFFER for " << data << endl;
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);
1184 }; // namespace android