IPCThreadState.cpp 42 KB

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