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