IPCThreadState.cpp revision 702ea9d42f52fc145090c0f0bfbe64993e4b8b33
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 375 376int32_t IPCThreadState::getStrictModePolicy() const { 377 return mStrictModePolicy; 378} 379 380void IPCThreadState::restoreCallingIdentity(int64_t token) 381{ 382 mCallingUid = (int)(token>>32); 383 mCallingPid = (int)token; 384} 385 386void IPCThreadState::clearCaller() 387{ 388 mCallingPid = getpid(); 389 mCallingUid = getuid(); 390} 391 392void IPCThreadState::flushCommands() 393{ 394 if (mProcess->mDriverFD <= 0) 395 return; 396 talkWithDriver(false); 397} 398 399void IPCThreadState::joinThreadPool(bool isMain) 400{ 401 LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid()); 402 403 mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER); 404 405 // This thread may have been spawned by a thread that was in the background 406 // scheduling group, so first we will make sure it is in the default/foreground 407 // one to avoid performing an initial transaction in the background. 408 androidSetThreadSchedulingGroup(mMyThreadId, ANDROID_TGROUP_DEFAULT); 409 410 status_t result; 411 do { 412 int32_t cmd; 413 414 // When we've cleared the incoming command queue, process any pending derefs 415 if (mIn.dataPosition() >= mIn.dataSize()) { 416 size_t numPending = mPendingWeakDerefs.size(); 417 if (numPending > 0) { 418 for (size_t i = 0; i < numPending; i++) { 419 RefBase::weakref_type* refs = mPendingWeakDerefs[i]; 420 refs->decWeak(mProcess.get()); 421 } 422 mPendingWeakDerefs.clear(); 423 } 424 425 numPending = mPendingStrongDerefs.size(); 426 if (numPending > 0) { 427 for (size_t i = 0; i < numPending; i++) { 428 BBinder* obj = mPendingStrongDerefs[i]; 429 obj->decStrong(mProcess.get()); 430 } 431 mPendingStrongDerefs.clear(); 432 } 433 } 434 435 // now get the next command to be processed, waiting if necessary 436 result = talkWithDriver(); 437 if (result >= NO_ERROR) { 438 size_t IN = mIn.dataAvail(); 439 if (IN < sizeof(int32_t)) continue; 440 cmd = mIn.readInt32(); 441 IF_LOG_COMMANDS() { 442 alog << "Processing top-level Command: " 443 << getReturnString(cmd) << endl; 444 } 445 446 447 result = executeCommand(cmd); 448 } 449 450 // After executing the command, ensure that the thread is returned to the 451 // default cgroup before rejoining the pool. The driver takes care of 452 // restoring the priority, but doesn't do anything with cgroups so we 453 // need to take care of that here in userspace. Note that we do make 454 // sure to go in the foreground after executing a transaction, but 455 // there are other callbacks into user code that could have changed 456 // our group so we want to make absolutely sure it is put back. 457 androidSetThreadSchedulingGroup(mMyThreadId, ANDROID_TGROUP_DEFAULT); 458 459 // Let this thread exit the thread pool if it is no longer 460 // needed and it is not the main process thread. 461 if(result == TIMED_OUT && !isMain) { 462 break; 463 } 464 } while (result != -ECONNREFUSED && result != -EBADF); 465 466 LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%p\n", 467 (void*)pthread_self(), getpid(), (void*)result); 468 469 mOut.writeInt32(BC_EXIT_LOOPER); 470 talkWithDriver(false); 471} 472 473void IPCThreadState::stopProcess(bool immediate) 474{ 475 //LOGI("**** STOPPING PROCESS"); 476 flushCommands(); 477 int fd = mProcess->mDriverFD; 478 mProcess->mDriverFD = -1; 479 close(fd); 480 //kill(getpid(), SIGKILL); 481} 482 483status_t IPCThreadState::transact(int32_t handle, 484 uint32_t code, const Parcel& data, 485 Parcel* reply, uint32_t flags) 486{ 487 status_t err = data.errorCheck(); 488 489 flags |= TF_ACCEPT_FDS; 490 491 IF_LOG_TRANSACTIONS() { 492 TextOutput::Bundle _b(alog); 493 alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand " 494 << handle << " / code " << TypeCode(code) << ": " 495 << indent << data << dedent << endl; 496 } 497 498 if (err == NO_ERROR) { 499 LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(), 500 (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY"); 501 err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL); 502 } 503 504 if (err != NO_ERROR) { 505 if (reply) reply->setError(err); 506 return (mLastError = err); 507 } 508 509 if ((flags & TF_ONE_WAY) == 0) { 510 if (reply) { 511 err = waitForResponse(reply); 512 } else { 513 Parcel fakeReply; 514 err = waitForResponse(&fakeReply); 515 } 516 517 IF_LOG_TRANSACTIONS() { 518 TextOutput::Bundle _b(alog); 519 alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand " 520 << handle << ": "; 521 if (reply) alog << indent << *reply << dedent << endl; 522 else alog << "(none requested)" << endl; 523 } 524 } else { 525 err = waitForResponse(NULL, NULL); 526 } 527 528 return err; 529} 530 531void IPCThreadState::incStrongHandle(int32_t handle) 532{ 533 LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle); 534 mOut.writeInt32(BC_ACQUIRE); 535 mOut.writeInt32(handle); 536} 537 538void IPCThreadState::decStrongHandle(int32_t handle) 539{ 540 LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle); 541 mOut.writeInt32(BC_RELEASE); 542 mOut.writeInt32(handle); 543} 544 545void IPCThreadState::incWeakHandle(int32_t handle) 546{ 547 LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle); 548 mOut.writeInt32(BC_INCREFS); 549 mOut.writeInt32(handle); 550} 551 552void IPCThreadState::decWeakHandle(int32_t handle) 553{ 554 LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle); 555 mOut.writeInt32(BC_DECREFS); 556 mOut.writeInt32(handle); 557} 558 559status_t IPCThreadState::attemptIncStrongHandle(int32_t handle) 560{ 561 mOut.writeInt32(BC_ATTEMPT_ACQUIRE); 562 mOut.writeInt32(0); // xxx was thread priority 563 mOut.writeInt32(handle); 564 status_t result = UNKNOWN_ERROR; 565 566 waitForResponse(NULL, &result); 567 568#if LOG_REFCOUNTS 569 printf("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n", 570 handle, result == NO_ERROR ? "SUCCESS" : "FAILURE"); 571#endif 572 573 return result; 574} 575 576void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder) 577{ 578#if LOG_REFCOUNTS 579 printf("IPCThreadState::expungeHandle(%ld)\n", handle); 580#endif 581 self()->mProcess->expungeHandle(handle, binder); 582} 583 584status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy) 585{ 586 mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION); 587 mOut.writeInt32((int32_t)handle); 588 mOut.writeInt32((int32_t)proxy); 589 return NO_ERROR; 590} 591 592status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy) 593{ 594 mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION); 595 mOut.writeInt32((int32_t)handle); 596 mOut.writeInt32((int32_t)proxy); 597 return NO_ERROR; 598} 599 600IPCThreadState::IPCThreadState() 601 : mProcess(ProcessState::self()), mMyThreadId(androidGetTid()), 602 mStrictModePolicy(0) 603{ 604 pthread_setspecific(gTLS, this); 605 clearCaller(); 606 mIn.setDataCapacity(256); 607 mOut.setDataCapacity(256); 608} 609 610IPCThreadState::~IPCThreadState() 611{ 612} 613 614status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags) 615{ 616 status_t err; 617 status_t statusBuffer; 618 err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer); 619 if (err < NO_ERROR) return err; 620 621 return waitForResponse(NULL, NULL); 622} 623 624status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult) 625{ 626 int32_t cmd; 627 int32_t err; 628 629 while (1) { 630 if ((err=talkWithDriver()) < NO_ERROR) break; 631 err = mIn.errorCheck(); 632 if (err < NO_ERROR) break; 633 if (mIn.dataAvail() == 0) continue; 634 635 cmd = mIn.readInt32(); 636 637 IF_LOG_COMMANDS() { 638 alog << "Processing waitForResponse Command: " 639 << getReturnString(cmd) << endl; 640 } 641 642 switch (cmd) { 643 case BR_TRANSACTION_COMPLETE: 644 if (!reply && !acquireResult) goto finish; 645 break; 646 647 case BR_DEAD_REPLY: 648 err = DEAD_OBJECT; 649 goto finish; 650 651 case BR_FAILED_REPLY: 652 err = FAILED_TRANSACTION; 653 goto finish; 654 655 case BR_ACQUIRE_RESULT: 656 { 657 LOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT"); 658 const int32_t result = mIn.readInt32(); 659 if (!acquireResult) continue; 660 *acquireResult = result ? NO_ERROR : INVALID_OPERATION; 661 } 662 goto finish; 663 664 case BR_REPLY: 665 { 666 binder_transaction_data tr; 667 err = mIn.read(&tr, sizeof(tr)); 668 LOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY"); 669 if (err != NO_ERROR) goto finish; 670 671 if (reply) { 672 if ((tr.flags & TF_STATUS_CODE) == 0) { 673 reply->ipcSetDataReference( 674 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer), 675 tr.data_size, 676 reinterpret_cast<const size_t*>(tr.data.ptr.offsets), 677 tr.offsets_size/sizeof(size_t), 678 freeBuffer, this); 679 } else { 680 err = *static_cast<const status_t*>(tr.data.ptr.buffer); 681 freeBuffer(NULL, 682 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer), 683 tr.data_size, 684 reinterpret_cast<const size_t*>(tr.data.ptr.offsets), 685 tr.offsets_size/sizeof(size_t), this); 686 } 687 } else { 688 freeBuffer(NULL, 689 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer), 690 tr.data_size, 691 reinterpret_cast<const size_t*>(tr.data.ptr.offsets), 692 tr.offsets_size/sizeof(size_t), this); 693 continue; 694 } 695 } 696 goto finish; 697 698 default: 699 err = executeCommand(cmd); 700 if (err != NO_ERROR) goto finish; 701 break; 702 } 703 } 704 705finish: 706 if (err != NO_ERROR) { 707 if (acquireResult) *acquireResult = err; 708 if (reply) reply->setError(err); 709 mLastError = err; 710 } 711 712 return err; 713} 714 715status_t IPCThreadState::talkWithDriver(bool doReceive) 716{ 717 LOG_ASSERT(mProcess->mDriverFD >= 0, "Binder driver is not opened"); 718 719 binder_write_read bwr; 720 721 // Is the read buffer empty? 722 const bool needRead = mIn.dataPosition() >= mIn.dataSize(); 723 724 // We don't want to write anything if we are still reading 725 // from data left in the input buffer and the caller 726 // has requested to read the next data. 727 const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0; 728 729 bwr.write_size = outAvail; 730 bwr.write_buffer = (long unsigned int)mOut.data(); 731 732 // This is what we'll read. 733 if (doReceive && needRead) { 734 bwr.read_size = mIn.dataCapacity(); 735 bwr.read_buffer = (long unsigned int)mIn.data(); 736 } else { 737 bwr.read_size = 0; 738 } 739 740 IF_LOG_COMMANDS() { 741 TextOutput::Bundle _b(alog); 742 if (outAvail != 0) { 743 alog << "Sending commands to driver: " << indent; 744 const void* cmds = (const void*)bwr.write_buffer; 745 const void* end = ((const uint8_t*)cmds)+bwr.write_size; 746 alog << HexDump(cmds, bwr.write_size) << endl; 747 while (cmds < end) cmds = printCommand(alog, cmds); 748 alog << dedent; 749 } 750 alog << "Size of receive buffer: " << bwr.read_size 751 << ", needRead: " << needRead << ", doReceive: " << doReceive << endl; 752 } 753 754 // Return immediately if there is nothing to do. 755 if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR; 756 757 bwr.write_consumed = 0; 758 bwr.read_consumed = 0; 759 status_t err; 760 do { 761 IF_LOG_COMMANDS() { 762 alog << "About to read/write, write size = " << mOut.dataSize() << endl; 763 } 764#if defined(HAVE_ANDROID_OS) 765 if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0) 766 err = NO_ERROR; 767 else 768 err = -errno; 769#else 770 err = INVALID_OPERATION; 771#endif 772 IF_LOG_COMMANDS() { 773 alog << "Finished read/write, write size = " << mOut.dataSize() << endl; 774 } 775 } while (err == -EINTR); 776 777 IF_LOG_COMMANDS() { 778 alog << "Our err: " << (void*)err << ", write consumed: " 779 << bwr.write_consumed << " (of " << mOut.dataSize() 780 << "), read consumed: " << bwr.read_consumed << endl; 781 } 782 783 if (err >= NO_ERROR) { 784 if (bwr.write_consumed > 0) { 785 if (bwr.write_consumed < (ssize_t)mOut.dataSize()) 786 mOut.remove(0, bwr.write_consumed); 787 else 788 mOut.setDataSize(0); 789 } 790 if (bwr.read_consumed > 0) { 791 mIn.setDataSize(bwr.read_consumed); 792 mIn.setDataPosition(0); 793 } 794 IF_LOG_COMMANDS() { 795 TextOutput::Bundle _b(alog); 796 alog << "Remaining data size: " << mOut.dataSize() << endl; 797 alog << "Received commands from driver: " << indent; 798 const void* cmds = mIn.data(); 799 const void* end = mIn.data() + mIn.dataSize(); 800 alog << HexDump(cmds, mIn.dataSize()) << endl; 801 while (cmds < end) cmds = printReturnCommand(alog, cmds); 802 alog << dedent; 803 } 804 return NO_ERROR; 805 } 806 807 return err; 808} 809 810status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags, 811 int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer) 812{ 813 binder_transaction_data tr; 814 815 tr.target.handle = handle; 816 tr.code = code; 817 tr.flags = binderFlags; 818 819 const status_t err = data.errorCheck(); 820 if (err == NO_ERROR) { 821 tr.data_size = data.ipcDataSize(); 822 tr.data.ptr.buffer = data.ipcData(); 823 tr.offsets_size = data.ipcObjectsCount()*sizeof(size_t); 824 tr.data.ptr.offsets = data.ipcObjects(); 825 } else if (statusBuffer) { 826 tr.flags |= TF_STATUS_CODE; 827 *statusBuffer = err; 828 tr.data_size = sizeof(status_t); 829 tr.data.ptr.buffer = statusBuffer; 830 tr.offsets_size = 0; 831 tr.data.ptr.offsets = NULL; 832 } else { 833 return (mLastError = err); 834 } 835 836 mOut.writeInt32(cmd); 837 mOut.write(&tr, sizeof(tr)); 838 839 return NO_ERROR; 840} 841 842sp<BBinder> the_context_object; 843 844void setTheContextObject(sp<BBinder> obj) 845{ 846 the_context_object = obj; 847} 848 849status_t IPCThreadState::executeCommand(int32_t cmd) 850{ 851 BBinder* obj; 852 RefBase::weakref_type* refs; 853 status_t result = NO_ERROR; 854 855 switch (cmd) { 856 case BR_ERROR: 857 result = mIn.readInt32(); 858 break; 859 860 case BR_OK: 861 break; 862 863 case BR_ACQUIRE: 864 refs = (RefBase::weakref_type*)mIn.readInt32(); 865 obj = (BBinder*)mIn.readInt32(); 866 LOG_ASSERT(refs->refBase() == obj, 867 "BR_ACQUIRE: object %p does not match cookie %p (expected %p)", 868 refs, obj, refs->refBase()); 869 obj->incStrong(mProcess.get()); 870 IF_LOG_REMOTEREFS() { 871 LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj); 872 obj->printRefs(); 873 } 874 mOut.writeInt32(BC_ACQUIRE_DONE); 875 mOut.writeInt32((int32_t)refs); 876 mOut.writeInt32((int32_t)obj); 877 break; 878 879 case BR_RELEASE: 880 refs = (RefBase::weakref_type*)mIn.readInt32(); 881 obj = (BBinder*)mIn.readInt32(); 882 LOG_ASSERT(refs->refBase() == obj, 883 "BR_RELEASE: object %p does not match cookie %p (expected %p)", 884 refs, obj, refs->refBase()); 885 IF_LOG_REMOTEREFS() { 886 LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj); 887 obj->printRefs(); 888 } 889 mPendingStrongDerefs.push(obj); 890 break; 891 892 case BR_INCREFS: 893 refs = (RefBase::weakref_type*)mIn.readInt32(); 894 obj = (BBinder*)mIn.readInt32(); 895 refs->incWeak(mProcess.get()); 896 mOut.writeInt32(BC_INCREFS_DONE); 897 mOut.writeInt32((int32_t)refs); 898 mOut.writeInt32((int32_t)obj); 899 break; 900 901 case BR_DECREFS: 902 refs = (RefBase::weakref_type*)mIn.readInt32(); 903 obj = (BBinder*)mIn.readInt32(); 904 // NOTE: This assertion is not valid, because the object may no 905 // longer exist (thus the (BBinder*)cast above resulting in a different 906 // memory address). 907 //LOG_ASSERT(refs->refBase() == obj, 908 // "BR_DECREFS: object %p does not match cookie %p (expected %p)", 909 // refs, obj, refs->refBase()); 910 mPendingWeakDerefs.push(refs); 911 break; 912 913 case BR_ATTEMPT_ACQUIRE: 914 refs = (RefBase::weakref_type*)mIn.readInt32(); 915 obj = (BBinder*)mIn.readInt32(); 916 917 { 918 const bool success = refs->attemptIncStrong(mProcess.get()); 919 LOG_ASSERT(success && refs->refBase() == obj, 920 "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)", 921 refs, obj, refs->refBase()); 922 923 mOut.writeInt32(BC_ACQUIRE_RESULT); 924 mOut.writeInt32((int32_t)success); 925 } 926 break; 927 928 case BR_TRANSACTION: 929 { 930 binder_transaction_data tr; 931 result = mIn.read(&tr, sizeof(tr)); 932 LOG_ASSERT(result == NO_ERROR, 933 "Not enough command data for brTRANSACTION"); 934 if (result != NO_ERROR) break; 935 936 Parcel buffer; 937 buffer.ipcSetDataReference( 938 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer), 939 tr.data_size, 940 reinterpret_cast<const size_t*>(tr.data.ptr.offsets), 941 tr.offsets_size/sizeof(size_t), freeBuffer, this); 942 943 const pid_t origPid = mCallingPid; 944 const uid_t origUid = mCallingUid; 945 946 mCallingPid = tr.sender_pid; 947 mCallingUid = tr.sender_euid; 948 949 int curPrio = getpriority(PRIO_PROCESS, mMyThreadId); 950 if (gDisableBackgroundScheduling) { 951 if (curPrio > ANDROID_PRIORITY_NORMAL) { 952 // We have inherited a reduced priority from the caller, but do not 953 // want to run in that state in this process. The driver set our 954 // priority already (though not our scheduling class), so bounce 955 // it back to the default before invoking the transaction. 956 setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL); 957 } 958 } else { 959 if (curPrio >= ANDROID_PRIORITY_BACKGROUND) { 960 // We want to use the inherited priority from the caller. 961 // Ensure this thread is in the background scheduling class, 962 // since the driver won't modify scheduling classes for us. 963 // The scheduling group is reset to default by the caller 964 // once this method returns after the transaction is complete. 965 androidSetThreadSchedulingGroup(mMyThreadId, 966 ANDROID_TGROUP_BG_NONINTERACT); 967 } 968 } 969 970 //LOGI(">>>> TRANSACT from pid %d uid %d\n", mCallingPid, mCallingUid); 971 972 Parcel reply; 973 IF_LOG_TRANSACTIONS() { 974 TextOutput::Bundle _b(alog); 975 alog << "BR_TRANSACTION thr " << (void*)pthread_self() 976 << " / obj " << tr.target.ptr << " / code " 977 << TypeCode(tr.code) << ": " << indent << buffer 978 << dedent << endl 979 << "Data addr = " 980 << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer) 981 << ", offsets addr=" 982 << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl; 983 } 984 if (tr.target.ptr) { 985 sp<BBinder> b((BBinder*)tr.cookie); 986 const status_t error = b->transact(tr.code, buffer, &reply, 0); 987 if (error < NO_ERROR) reply.setError(error); 988 989 } else { 990 const status_t error = the_context_object->transact(tr.code, buffer, &reply, 0); 991 if (error < NO_ERROR) reply.setError(error); 992 } 993 994 //LOGI("<<<< TRANSACT from pid %d restore pid %d uid %d\n", 995 // mCallingPid, origPid, origUid); 996 997 if ((tr.flags & TF_ONE_WAY) == 0) { 998 LOG_ONEWAY("Sending reply to %d!", mCallingPid); 999 sendReply(reply, 0); 1000 } else { 1001 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid); 1002 } 1003 1004 mCallingPid = origPid; 1005 mCallingUid = origUid; 1006 1007 IF_LOG_TRANSACTIONS() { 1008 TextOutput::Bundle _b(alog); 1009 alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj " 1010 << tr.target.ptr << ": " << indent << reply << dedent << endl; 1011 } 1012 1013 } 1014 break; 1015 1016 case BR_DEAD_BINDER: 1017 { 1018 BpBinder *proxy = (BpBinder*)mIn.readInt32(); 1019 proxy->sendObituary(); 1020 mOut.writeInt32(BC_DEAD_BINDER_DONE); 1021 mOut.writeInt32((int32_t)proxy); 1022 } break; 1023 1024 case BR_CLEAR_DEATH_NOTIFICATION_DONE: 1025 { 1026 BpBinder *proxy = (BpBinder*)mIn.readInt32(); 1027 proxy->getWeakRefs()->decWeak(proxy); 1028 } break; 1029 1030 case BR_FINISHED: 1031 result = TIMED_OUT; 1032 break; 1033 1034 case BR_NOOP: 1035 break; 1036 1037 case BR_SPAWN_LOOPER: 1038 mProcess->spawnPooledThread(false); 1039 break; 1040 1041 default: 1042 printf("*** BAD COMMAND %d received from Binder driver\n", cmd); 1043 result = UNKNOWN_ERROR; 1044 break; 1045 } 1046 1047 if (result != NO_ERROR) { 1048 mLastError = result; 1049 } 1050 1051 return result; 1052} 1053 1054void IPCThreadState::threadDestructor(void *st) 1055{ 1056 IPCThreadState* const self = static_cast<IPCThreadState*>(st); 1057 if (self) { 1058 self->flushCommands(); 1059#if defined(HAVE_ANDROID_OS) 1060 ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0); 1061#endif 1062 delete self; 1063 } 1064} 1065 1066 1067void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data, size_t dataSize, 1068 const size_t* objects, size_t objectsSize, 1069 void* cookie) 1070{ 1071 //LOGI("Freeing parcel %p", &parcel); 1072 IF_LOG_COMMANDS() { 1073 alog << "Writing BC_FREE_BUFFER for " << data << endl; 1074 } 1075 LOG_ASSERT(data != NULL, "Called with NULL data"); 1076 if (parcel != NULL) parcel->closeFileDescriptors(); 1077 IPCThreadState* state = self(); 1078 state->mOut.writeInt32(BC_FREE_BUFFER); 1079 state->mOut.writeInt32((int32_t)data); 1080} 1081 1082}; // namespace android 1083