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