ProcessState.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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-ProcessState"
  17. #include <hwbinder/ProcessState.h>
  18. #include <cutils/atomic.h>
  19. #include <hwbinder/BpHwBinder.h>
  20. #include <hwbinder/IPCThreadState.h>
  21. #include <hwbinder/binder_kernel.h>
  22. #include <utils/Log.h>
  23. #include <utils/String8.h>
  24. #include <utils/threads.h>
  25. #include <private/binder/binder_module.h>
  26. #include <hwbinder/Static.h>
  27. #include <errno.h>
  28. #include <fcntl.h>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <unistd.h>
  32. #include <sys/ioctl.h>
  33. #include <sys/mman.h>
  34. #include <sys/stat.h>
  35. #include <sys/types.h>
  36. #define DEFAULT_BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
  37. #define DEFAULT_MAX_BINDER_THREADS 0
  38. #define INIT_SYSTEM_CONTEXT_MGR_HANDLE 100000000
  39. // -------------------------------------------------------------------------
  40. namespace android {
  41. namespace hardware {
  42. class PoolThread : public Thread
  43. {
  44. public:
  45. explicit PoolThread(bool isMain)
  46. : mIsMain(isMain)
  47. {
  48. }
  49. protected:
  50. virtual bool threadLoop()
  51. {
  52. IPCThreadState::self()->joinThreadPool(mIsMain);
  53. return false;
  54. }
  55. const bool mIsMain;
  56. };
  57. sp<ProcessState> ProcessState::self()
  58. {
  59. Mutex::Autolock _l(gProcessMutex);
  60. if (gProcess != nullptr) {
  61. return gProcess;
  62. }
  63. gProcess = new ProcessState(DEFAULT_BINDER_VM_SIZE);
  64. return gProcess;
  65. }
  66. sp<ProcessState> ProcessState::selfOrNull() {
  67. Mutex::Autolock _l(gProcessMutex);
  68. return gProcess;
  69. }
  70. sp<ProcessState> ProcessState::initWithMmapSize(size_t mmap_size) {
  71. Mutex::Autolock _l(gProcessMutex);
  72. if (gProcess != nullptr) {
  73. LOG_ALWAYS_FATAL_IF(mmap_size != gProcess->getMmapSize(),
  74. "ProcessState already initialized with a different mmap size.");
  75. return gProcess;
  76. }
  77. gProcess = new ProcessState(mmap_size);
  78. return gProcess;
  79. }
  80. void ProcessState::setContextObject(const sp<IBinder>& object)
  81. {
  82. setContextObject(object, String16("default"));
  83. }
  84. sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
  85. {
  86. return getStrongProxyForHandle(0);
  87. }
  88. sp<IBinder> ProcessState::getMgrContextObject(int index)
  89. {
  90. sp<IBinder> result;
  91. if(index < 0 || index >= MAX_CONTEXT)
  92. return result;
  93. return getStrongProxyForHandle(INIT_SYSTEM_CONTEXT_MGR_HANDLE + index);
  94. }
  95. void ProcessState::setContextObject(const sp<IBinder>& object, const String16& name)
  96. {
  97. AutoMutex _l(mLock);
  98. mContexts.add(name, object);
  99. }
  100. sp<IBinder> ProcessState::getContextObject(const String16& name, const sp<IBinder>& caller)
  101. {
  102. mLock.lock();
  103. sp<IBinder> object(
  104. mContexts.indexOfKey(name) >= 0 ? mContexts.valueFor(name) : nullptr);
  105. mLock.unlock();
  106. //printf("Getting context object %s for %p\n", String8(name).string(), caller.get());
  107. if (object != nullptr) return object;
  108. // Don't attempt to retrieve contexts if we manage them
  109. if (mManagesContexts) {
  110. ALOGE("getContextObject(%s) failed, but we manage the contexts!\n",
  111. String8(name).string());
  112. return nullptr;
  113. }
  114. IPCThreadState* ipc = IPCThreadState::self();
  115. {
  116. Parcel data, reply;
  117. // no interface token on this magic transaction
  118. data.writeString16(name);
  119. data.writeStrongBinder(caller);
  120. status_t result = ipc->transact(0 /*magic*/, 0, data, &reply, 0);
  121. if (result == NO_ERROR) {
  122. object = reply.readStrongBinder();
  123. }
  124. }
  125. ipc->flushCommands();
  126. if (object != nullptr) setContextObject(object, name);
  127. return object;
  128. }
  129. void ProcessState::startThreadPool()
  130. {
  131. AutoMutex _l(mLock);
  132. if (!mThreadPoolStarted) {
  133. mThreadPoolStarted = true;
  134. if (mSpawnThreadOnStart) {
  135. spawnPooledThread(true);
  136. }
  137. }
  138. }
  139. bool ProcessState::isContextManager(void) const
  140. {
  141. return mManagesContexts;
  142. }
  143. bool ProcessState::becomeContextManager(context_check_func checkFunc, void* userData)
  144. {
  145. if (!mManagesContexts) {
  146. AutoMutex _l(mLock);
  147. mBinderContextCheckFunc = checkFunc;
  148. mBinderContextUserData = userData;
  149. flat_binder_object obj {
  150. .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
  151. };
  152. status_t result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
  153. // fallback to original method
  154. if (result != 0) {
  155. android_errorWriteLog(0x534e4554, "121035042");
  156. int dummy = 0;
  157. result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &dummy);
  158. }
  159. if (result == 0) {
  160. mManagesContexts = true;
  161. } else if (result == -1) {
  162. mBinderContextCheckFunc = nullptr;
  163. mBinderContextUserData = nullptr;
  164. ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
  165. }
  166. }
  167. return mManagesContexts;
  168. }
  169. // Get references to userspace objects held by the kernel binder driver
  170. // Writes up to count elements into buf, and returns the total number
  171. // of references the kernel has, which may be larger than count.
  172. // buf may be NULL if count is 0. The pointers returned by this method
  173. // should only be used for debugging and not dereferenced, they may
  174. // already be invalid.
  175. ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf) {
  176. binder_node_debug_info info = {};
  177. uintptr_t* end = buf ? buf + buf_count : nullptr;
  178. size_t count = 0;
  179. do {
  180. status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
  181. if (result < 0) {
  182. return -1;
  183. }
  184. if (info.ptr != 0) {
  185. if (buf && buf < end) *buf++ = info.ptr;
  186. count++;
  187. if (buf && buf < end) *buf++ = info.cookie;
  188. count++;
  189. }
  190. } while (info.ptr != 0);
  191. return count;
  192. }
  193. // Queries the driver for the current strong reference count of the node
  194. // that the handle points to. Can only be used by the servicemanager.
  195. //
  196. // Returns -1 in case of failure, otherwise the strong reference count.
  197. ssize_t ProcessState::getStrongRefCountForNodeByHandle(int32_t handle) {
  198. binder_node_info_for_ref info;
  199. memset(&info, 0, sizeof(binder_node_info_for_ref));
  200. info.handle = handle;
  201. status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
  202. if (result != OK) {
  203. return -1;
  204. }
  205. return info.strong_count;
  206. }
  207. size_t ProcessState::getMmapSize() {
  208. return mMmapSize;
  209. }
  210. void ProcessState::setCallRestriction(CallRestriction restriction) {
  211. LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull(), "Call restrictions must be set before the threadpool is started.");
  212. mCallRestriction = restriction;
  213. }
  214. ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
  215. {
  216. if(handle >= INIT_SYSTEM_CONTEXT_MGR_HANDLE){
  217. return &mSystemContextMgrHandle[handle - INIT_SYSTEM_CONTEXT_MGR_HANDLE];
  218. }
  219. const size_t N=mHandleToObject.size();
  220. if (N <= (size_t)handle) {
  221. handle_entry e;
  222. e.binder = nullptr;
  223. e.refs = nullptr;
  224. status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
  225. if (err < NO_ERROR) return nullptr;
  226. }
  227. return &mHandleToObject.editItemAt(handle);
  228. }
  229. sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
  230. {
  231. sp<IBinder> result;
  232. AutoMutex _l(mLock);
  233. handle_entry* e = lookupHandleLocked(handle);
  234. if (e != nullptr) {
  235. // We need to create a new BpHwBinder if there isn't currently one, OR we
  236. // are unable to acquire a weak reference on this current one. See comment
  237. // in getWeakProxyForHandle() for more info about this.
  238. IBinder* b = e->binder;
  239. if (b == nullptr || !e->refs->attemptIncWeak(this)) {
  240. b = new BpHwBinder(handle);
  241. e->binder = b;
  242. if (b) e->refs = b->getWeakRefs();
  243. result = b;
  244. } else {
  245. // This little bit of nastyness is to allow us to add a primary
  246. // reference to the remote proxy when this team doesn't have one
  247. // but another team is sending the handle to us.
  248. result.force_set(b);
  249. e->refs->decWeak(this);
  250. }
  251. }
  252. return result;
  253. }
  254. wp<IBinder> ProcessState::getWeakProxyForHandle(int32_t handle)
  255. {
  256. wp<IBinder> result;
  257. AutoMutex _l(mLock);
  258. handle_entry* e = lookupHandleLocked(handle);
  259. if (e != nullptr) {
  260. // We need to create a new BpHwBinder if there isn't currently one, OR we
  261. // are unable to acquire a weak reference on this current one. The
  262. // attemptIncWeak() is safe because we know the BpHwBinder destructor will always
  263. // call expungeHandle(), which acquires the same lock we are holding now.
  264. // We need to do this because there is a race condition between someone
  265. // releasing a reference on this BpHwBinder, and a new reference on its handle
  266. // arriving from the driver.
  267. IBinder* b = e->binder;
  268. if (b == nullptr || !e->refs->attemptIncWeak(this)) {
  269. b = new BpHwBinder(handle);
  270. result = b;
  271. e->binder = b;
  272. if (b) e->refs = b->getWeakRefs();
  273. } else {
  274. result = b;
  275. e->refs->decWeak(this);
  276. }
  277. }
  278. return result;
  279. }
  280. void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
  281. {
  282. AutoMutex _l(mLock);
  283. handle_entry* e = lookupHandleLocked(handle);
  284. // This handle may have already been replaced with a new BpHwBinder
  285. // (if someone failed the AttemptIncWeak() above); we don't want
  286. // to overwrite it.
  287. if (e && e->binder == binder) e->binder = nullptr;
  288. }
  289. String8 ProcessState::makeBinderThreadName() {
  290. int32_t s = android_atomic_add(1, &mThreadPoolSeq);
  291. pid_t pid = getpid();
  292. String8 name;
  293. name.appendFormat("HwBinder:%d_%X", pid, s);
  294. return name;
  295. }
  296. void ProcessState::spawnPooledThread(bool isMain)
  297. {
  298. if (mThreadPoolStarted) {
  299. String8 name = makeBinderThreadName();
  300. ALOGV("Spawning new pooled thread, name=%s\n", name.string());
  301. sp<Thread> t = new PoolThread(isMain);
  302. t->run(name.string());
  303. }
  304. }
  305. status_t ProcessState::setThreadPoolConfiguration(size_t maxThreads, bool callerJoinsPool) {
  306. // if the caller joins the pool, then there will be one thread which is impossible.
  307. LOG_ALWAYS_FATAL_IF(maxThreads == 0 && callerJoinsPool,
  308. "Binder threadpool must have a minimum of one thread if caller joins pool.");
  309. size_t threadsToAllocate = maxThreads;
  310. // If the caller is going to join the pool it will contribute one thread to the threadpool.
  311. // This is part of the API's contract.
  312. if (callerJoinsPool) threadsToAllocate--;
  313. // If we can, spawn one thread from userspace when the threadpool is started. This ensures
  314. // that there is always a thread available to start more threads as soon as the threadpool
  315. // is started.
  316. bool spawnThreadOnStart = threadsToAllocate > 0;
  317. if (spawnThreadOnStart) threadsToAllocate--;
  318. // the BINDER_SET_MAX_THREADS ioctl really tells the kernel how many threads
  319. // it's allowed to spawn, *in addition* to any threads we may have already
  320. // spawned locally.
  321. size_t kernelMaxThreads = threadsToAllocate;
  322. AutoMutex _l(mLock);
  323. if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &kernelMaxThreads) == -1) {
  324. ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
  325. return -errno;
  326. }
  327. mMaxThreads = maxThreads;
  328. mSpawnThreadOnStart = spawnThreadOnStart;
  329. return NO_ERROR;
  330. }
  331. size_t ProcessState::getMaxThreads() {
  332. return mMaxThreads;
  333. }
  334. void ProcessState::giveThreadPoolName() {
  335. androidSetThreadName( makeBinderThreadName().string() );
  336. }
  337. static int open_driver()
  338. {
  339. int fd = open("/dev/hwbinder", O_RDWR | O_CLOEXEC);
  340. if (fd >= 0) {
  341. int vers = 0;
  342. status_t result = ioctl(fd, BINDER_VERSION, &vers);
  343. if (result == -1) {
  344. ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));
  345. close(fd);
  346. fd = -1;
  347. }
  348. if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
  349. ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)!", vers, BINDER_CURRENT_PROTOCOL_VERSION);
  350. close(fd);
  351. fd = -1;
  352. }
  353. size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
  354. result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
  355. if (result == -1) {
  356. ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
  357. }
  358. } else {
  359. ALOGW("Opening '/dev/hwbinder' failed: %s\n", strerror(errno));
  360. }
  361. return fd;
  362. }
  363. ProcessState::ProcessState(size_t mmap_size)
  364. : mDriverFD(open_driver())
  365. , mVMStart(MAP_FAILED)
  366. , mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
  367. , mThreadCountDecrement(PTHREAD_COND_INITIALIZER)
  368. , mExecutingThreadsCount(0)
  369. , mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
  370. , mStarvationStartTimeMs(0)
  371. , mManagesContexts(false)
  372. , mBinderContextCheckFunc(nullptr)
  373. , mBinderContextUserData(nullptr)
  374. , mThreadPoolStarted(false)
  375. , mSpawnThreadOnStart(true)
  376. , mThreadPoolSeq(1)
  377. , mMmapSize(mmap_size)
  378. , mCallRestriction(CallRestriction::NONE)
  379. {
  380. if (mDriverFD >= 0) {
  381. // mmap the binder, providing a chunk of virtual address space to receive transactions.
  382. mVMStart = mmap(nullptr, mMmapSize, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
  383. if (mVMStart == MAP_FAILED) {
  384. // *sigh*
  385. ALOGE("Mmapping /dev/hwbinder failed: %s\n", strerror(errno));
  386. close(mDriverFD);
  387. mDriverFD = -1;
  388. }
  389. }
  390. else {
  391. ALOGE("Binder driver could not be opened. Terminating.");
  392. }
  393. for(int i=0; i < MAX_CONTEXT; i++)
  394. {
  395. mSystemContextMgrHandle[i].binder = nullptr;
  396. mSystemContextMgrHandle[i].refs = nullptr;
  397. }
  398. }
  399. ProcessState::~ProcessState()
  400. {
  401. if (mDriverFD >= 0) {
  402. if (mVMStart != MAP_FAILED) {
  403. munmap(mVMStart, mMmapSize);
  404. }
  405. close(mDriverFD);
  406. }
  407. mDriverFD = -1;
  408. }
  409. }; // namespace hardware
  410. }; // namespace android