IPCThreadState.cpp 37 KB

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