ProcessState.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 "ProcessState"
  17. #include <cutils/process_name.h>
  18. #include <binder/ProcessState.h>
  19. #include <utils/Atomic.h>
  20. #include <binder/BpBinder.h>
  21. #include <binder/IPCThreadState.h>
  22. #include <utils/Log.h>
  23. #include <utils/String8.h>
  24. #include <binder/IServiceManager.h>
  25. #include <utils/String8.h>
  26. #include <utils/threads.h>
  27. #include <private/binder/binder_module.h>
  28. #include <private/binder/Static.h>
  29. #include <errno.h>
  30. #include <fcntl.h>
  31. #include <stdio.h>
  32. #include <stdlib.h>
  33. #include <unistd.h>
  34. #include <sys/ioctl.h>
  35. #include <sys/mman.h>
  36. #include <sys/stat.h>
  37. #define BINDER_VM_SIZE ((1*1024*1024) - (4096 *2))
  38. #define DEFAULT_MAX_BINDER_THREADS 15
  39. // ---------------------------------------------------------------------------
  40. namespace android {
  41. class PoolThread : public Thread
  42. {
  43. public:
  44. PoolThread(bool isMain)
  45. : mIsMain(isMain)
  46. {
  47. }
  48. protected:
  49. virtual bool threadLoop()
  50. {
  51. IPCThreadState::self()->joinThreadPool(mIsMain);
  52. return false;
  53. }
  54. const bool mIsMain;
  55. };
  56. sp<ProcessState> ProcessState::self()
  57. {
  58. Mutex::Autolock _l(gProcessMutex);
  59. if (gProcess != NULL) {
  60. return gProcess;
  61. }
  62. gProcess = new ProcessState;
  63. return gProcess;
  64. }
  65. void ProcessState::setContextObject(const sp<IBinder>& object)
  66. {
  67. setContextObject(object, String16("default"));
  68. }
  69. sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
  70. {
  71. return getStrongProxyForHandle(0);
  72. }
  73. void ProcessState::setContextObject(const sp<IBinder>& object, const String16& name)
  74. {
  75. AutoMutex _l(mLock);
  76. mContexts.add(name, object);
  77. }
  78. sp<IBinder> ProcessState::getContextObject(const String16& name, const sp<IBinder>& caller)
  79. {
  80. mLock.lock();
  81. sp<IBinder> object(
  82. mContexts.indexOfKey(name) >= 0 ? mContexts.valueFor(name) : NULL);
  83. mLock.unlock();
  84. //printf("Getting context object %s for %p\n", String8(name).string(), caller.get());
  85. if (object != NULL) return object;
  86. // Don't attempt to retrieve contexts if we manage them
  87. if (mManagesContexts) {
  88. ALOGE("getContextObject(%s) failed, but we manage the contexts!\n",
  89. String8(name).string());
  90. return NULL;
  91. }
  92. IPCThreadState* ipc = IPCThreadState::self();
  93. {
  94. Parcel data, reply;
  95. // no interface token on this magic transaction
  96. data.writeString16(name);
  97. data.writeStrongBinder(caller);
  98. status_t result = ipc->transact(0 /*magic*/, 0, data, &reply, 0);
  99. if (result == NO_ERROR) {
  100. object = reply.readStrongBinder();
  101. }
  102. }
  103. ipc->flushCommands();
  104. if (object != NULL) setContextObject(object, name);
  105. return object;
  106. }
  107. void ProcessState::startThreadPool()
  108. {
  109. AutoMutex _l(mLock);
  110. if (!mThreadPoolStarted) {
  111. mThreadPoolStarted = true;
  112. spawnPooledThread(true);
  113. }
  114. }
  115. bool ProcessState::isContextManager(void) const
  116. {
  117. return mManagesContexts;
  118. }
  119. bool ProcessState::becomeContextManager(context_check_func checkFunc, void* userData)
  120. {
  121. if (!mManagesContexts) {
  122. AutoMutex _l(mLock);
  123. mBinderContextCheckFunc = checkFunc;
  124. mBinderContextUserData = userData;
  125. int dummy = 0;
  126. status_t result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &dummy);
  127. if (result == 0) {
  128. mManagesContexts = true;
  129. } else if (result == -1) {
  130. mBinderContextCheckFunc = NULL;
  131. mBinderContextUserData = NULL;
  132. ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
  133. }
  134. }
  135. return mManagesContexts;
  136. }
  137. ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
  138. {
  139. const size_t N=mHandleToObject.size();
  140. if (N <= (size_t)handle) {
  141. handle_entry e;
  142. e.binder = NULL;
  143. e.refs = NULL;
  144. status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
  145. if (err < NO_ERROR) return NULL;
  146. }
  147. return &mHandleToObject.editItemAt(handle);
  148. }
  149. sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
  150. {
  151. sp<IBinder> result;
  152. AutoMutex _l(mLock);
  153. handle_entry* e = lookupHandleLocked(handle);
  154. if (e != NULL) {
  155. // We need to create a new BpBinder if there isn't currently one, OR we
  156. // are unable to acquire a weak reference on this current one. See comment
  157. // in getWeakProxyForHandle() for more info about this.
  158. IBinder* b = e->binder;
  159. if (b == NULL || !e->refs->attemptIncWeak(this)) {
  160. if (handle == 0) {
  161. // Special case for context manager...
  162. // The context manager is the only object for which we create
  163. // a BpBinder proxy without already holding a reference.
  164. // Perform a dummy transaction to ensure the context manager
  165. // is registered before we create the first local reference
  166. // to it (which will occur when creating the BpBinder).
  167. // If a local reference is created for the BpBinder when the
  168. // context manager is not present, the driver will fail to
  169. // provide a reference to the context manager, but the
  170. // driver API does not return status.
  171. //
  172. // Note that this is not race-free if the context manager
  173. // dies while this code runs.
  174. //
  175. // TODO: add a driver API to wait for context manager, or
  176. // stop special casing handle 0 for context manager and add
  177. // a driver API to get a handle to the context manager with
  178. // proper reference counting.
  179. Parcel data;
  180. status_t status = IPCThreadState::self()->transact(
  181. 0, IBinder::PING_TRANSACTION, data, NULL, 0);
  182. if (status == DEAD_OBJECT)
  183. return NULL;
  184. }
  185. b = new BpBinder(handle);
  186. e->binder = b;
  187. if (b) e->refs = b->getWeakRefs();
  188. result = b;
  189. } else {
  190. // This little bit of nastyness is to allow us to add a primary
  191. // reference to the remote proxy when this team doesn't have one
  192. // but another team is sending the handle to us.
  193. result.force_set(b);
  194. e->refs->decWeak(this);
  195. }
  196. }
  197. return result;
  198. }
  199. wp<IBinder> ProcessState::getWeakProxyForHandle(int32_t handle)
  200. {
  201. wp<IBinder> result;
  202. AutoMutex _l(mLock);
  203. handle_entry* e = lookupHandleLocked(handle);
  204. if (e != NULL) {
  205. // We need to create a new BpBinder if there isn't currently one, OR we
  206. // are unable to acquire a weak reference on this current one. The
  207. // attemptIncWeak() is safe because we know the BpBinder destructor will always
  208. // call expungeHandle(), which acquires the same lock we are holding now.
  209. // We need to do this because there is a race condition between someone
  210. // releasing a reference on this BpBinder, and a new reference on its handle
  211. // arriving from the driver.
  212. IBinder* b = e->binder;
  213. if (b == NULL || !e->refs->attemptIncWeak(this)) {
  214. b = new BpBinder(handle);
  215. result = b;
  216. e->binder = b;
  217. if (b) e->refs = b->getWeakRefs();
  218. } else {
  219. result = b;
  220. e->refs->decWeak(this);
  221. }
  222. }
  223. return result;
  224. }
  225. void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
  226. {
  227. AutoMutex _l(mLock);
  228. handle_entry* e = lookupHandleLocked(handle);
  229. // This handle may have already been replaced with a new BpBinder
  230. // (if someone failed the AttemptIncWeak() above); we don't want
  231. // to overwrite it.
  232. if (e && e->binder == binder) e->binder = NULL;
  233. }
  234. String8 ProcessState::makeBinderThreadName() {
  235. int32_t s = android_atomic_add(1, &mThreadPoolSeq);
  236. String8 name;
  237. name.appendFormat("Binder_%X", s);
  238. return name;
  239. }
  240. void ProcessState::spawnPooledThread(bool isMain)
  241. {
  242. if (mThreadPoolStarted) {
  243. String8 name = makeBinderThreadName();
  244. ALOGV("Spawning new pooled thread, name=%s\n", name.string());
  245. sp<Thread> t = new PoolThread(isMain);
  246. t->run(name.string());
  247. }
  248. }
  249. status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
  250. status_t result = NO_ERROR;
  251. if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
  252. mMaxThreads = maxThreads;
  253. } else {
  254. result = -errno;
  255. ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
  256. }
  257. return result;
  258. }
  259. void ProcessState::giveThreadPoolName() {
  260. androidSetThreadName( makeBinderThreadName().string() );
  261. }
  262. static int open_driver()
  263. {
  264. int fd = open("/dev/binder", O_RDWR);
  265. if (fd >= 0) {
  266. fcntl(fd, F_SETFD, FD_CLOEXEC);
  267. int vers = 0;
  268. status_t result = ioctl(fd, BINDER_VERSION, &vers);
  269. if (result == -1) {
  270. ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));
  271. close(fd);
  272. fd = -1;
  273. }
  274. if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
  275. ALOGE("Binder driver protocol does not match user space protocol!");
  276. close(fd);
  277. fd = -1;
  278. }
  279. size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
  280. result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
  281. if (result == -1) {
  282. ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
  283. }
  284. } else {
  285. ALOGW("Opening '/dev/binder' failed: %s\n", strerror(errno));
  286. }
  287. return fd;
  288. }
  289. ProcessState::ProcessState()
  290. : mDriverFD(open_driver())
  291. , mVMStart(MAP_FAILED)
  292. , mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
  293. , mThreadCountDecrement(PTHREAD_COND_INITIALIZER)
  294. , mExecutingThreadsCount(0)
  295. , mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
  296. , mManagesContexts(false)
  297. , mBinderContextCheckFunc(NULL)
  298. , mBinderContextUserData(NULL)
  299. , mThreadPoolStarted(false)
  300. , mThreadPoolSeq(1)
  301. {
  302. if (mDriverFD >= 0) {
  303. // XXX Ideally, there should be a specific define for whether we
  304. // have mmap (or whether we could possibly have the kernel module
  305. // availabla).
  306. #if !defined(HAVE_WIN32_IPC)
  307. // mmap the binder, providing a chunk of virtual address space to receive transactions.
  308. mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
  309. if (mVMStart == MAP_FAILED) {
  310. // *sigh*
  311. ALOGE("Using /dev/binder failed: unable to mmap transaction memory.\n");
  312. close(mDriverFD);
  313. mDriverFD = -1;
  314. }
  315. #else
  316. mDriverFD = -1;
  317. #endif
  318. }
  319. LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver could not be opened. Terminating.");
  320. }
  321. ProcessState::~ProcessState()
  322. {
  323. }
  324. }; // namespace android