blob: add5e744dbcef57b30dc1c51c9654da09fd7350b [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "ProcessState"
18
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070019#include <binder/ProcessState.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020
21#include <utils/Atomic.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070022#include <binder/BpBinder.h>
23#include <binder/IPCThreadState.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080024#include <utils/Log.h>
25#include <utils/String8.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070026#include <binder/IServiceManager.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080027#include <utils/String8.h>
28#include <utils/threads.h>
29
Mathias Agopian208059f2009-05-18 15:08:03 -070030#include <private/binder/binder_module.h>
31#include <private/binder/Static.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
33#include <errno.h>
34#include <fcntl.h>
35#include <stdio.h>
36#include <stdlib.h>
37#include <unistd.h>
38#include <sys/ioctl.h>
39#include <sys/mman.h>
40#include <sys/stat.h>
Philip Cuadraa082fa82016-04-08 10:29:14 -070041#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080042
Ganesh Mahendran6ac7fb52017-03-03 09:41:14 +080043#define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
Wale Ogunwale376b8222015-04-13 16:16:10 -070044#define DEFAULT_MAX_BINDER_THREADS 15
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080045
Philip Cuadraa082fa82016-04-08 10:29:14 -070046// -------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080047
48namespace android {
Wale Ogunwale376b8222015-04-13 16:16:10 -070049
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050class PoolThread : public Thread
51{
52public:
Chih-Hung Hsiehe2347b72016-04-25 15:41:05 -070053 explicit PoolThread(bool isMain)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054 : mIsMain(isMain)
55 {
56 }
57
58protected:
59 virtual bool threadLoop()
60 {
61 IPCThreadState::self()->joinThreadPool(mIsMain);
62 return false;
63 }
64
65 const bool mIsMain;
66};
67
68sp<ProcessState> ProcessState::self()
69{
Mathias Agopiane8db8712012-04-16 19:30:56 -070070 Mutex::Autolock _l(gProcessMutex);
71 if (gProcess != NULL) {
72 return gProcess;
73 }
Martijn Coenen55d871c2017-03-21 15:56:40 -070074 gProcess = new ProcessState("/dev/binder");
75 return gProcess;
76}
77
78sp<ProcessState> ProcessState::initWithDriver(const char* driver)
79{
80 Mutex::Autolock _l(gProcessMutex);
81 if (gProcess != NULL) {
Iliyan Malcheved1ffe02017-04-14 00:34:57 -070082 // Allow for initWithDriver to be called repeatedly with the same
83 // driver.
84 if (!strcmp(gProcess->getDriverName().c_str(), driver)) {
85 return gProcess;
86 }
Martijn Coenen55d871c2017-03-21 15:56:40 -070087 LOG_ALWAYS_FATAL("ProcessState was already initialized.");
88 }
89 gProcess = new ProcessState(driver);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090 return gProcess;
91}
92
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093void ProcessState::setContextObject(const sp<IBinder>& object)
94{
95 setContextObject(object, String16("default"));
96}
97
Colin Cross6f4f3ab2014-02-05 17:42:44 -080098sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099{
Jeff Browne16986c2011-07-08 18:52:57 -0700100 return getStrongProxyForHandle(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101}
102
103void ProcessState::setContextObject(const sp<IBinder>& object, const String16& name)
104{
105 AutoMutex _l(mLock);
106 mContexts.add(name, object);
107}
108
109sp<IBinder> ProcessState::getContextObject(const String16& name, const sp<IBinder>& caller)
110{
111 mLock.lock();
112 sp<IBinder> object(
113 mContexts.indexOfKey(name) >= 0 ? mContexts.valueFor(name) : NULL);
114 mLock.unlock();
115
116 //printf("Getting context object %s for %p\n", String8(name).string(), caller.get());
117
118 if (object != NULL) return object;
119
120 // Don't attempt to retrieve contexts if we manage them
121 if (mManagesContexts) {
Steve Blocke6f43dd2012-01-06 19:20:56 +0000122 ALOGE("getContextObject(%s) failed, but we manage the contexts!\n",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123 String8(name).string());
124 return NULL;
125 }
126
127 IPCThreadState* ipc = IPCThreadState::self();
128 {
129 Parcel data, reply;
130 // no interface token on this magic transaction
131 data.writeString16(name);
132 data.writeStrongBinder(caller);
133 status_t result = ipc->transact(0 /*magic*/, 0, data, &reply, 0);
134 if (result == NO_ERROR) {
135 object = reply.readStrongBinder();
136 }
137 }
138
139 ipc->flushCommands();
140
141 if (object != NULL) setContextObject(object, name);
142 return object;
143}
144
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800145void ProcessState::startThreadPool()
146{
147 AutoMutex _l(mLock);
148 if (!mThreadPoolStarted) {
149 mThreadPoolStarted = true;
150 spawnPooledThread(true);
151 }
152}
153
154bool ProcessState::isContextManager(void) const
155{
156 return mManagesContexts;
157}
158
159bool ProcessState::becomeContextManager(context_check_func checkFunc, void* userData)
160{
161 if (!mManagesContexts) {
162 AutoMutex _l(mLock);
163 mBinderContextCheckFunc = checkFunc;
164 mBinderContextUserData = userData;
Jeff Browne16986c2011-07-08 18:52:57 -0700165
166 int dummy = 0;
Jeff Browne16986c2011-07-08 18:52:57 -0700167 status_t result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &dummy);
Jeff Browne16986c2011-07-08 18:52:57 -0700168 if (result == 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169 mManagesContexts = true;
Jeff Browne16986c2011-07-08 18:52:57 -0700170 } else if (result == -1) {
171 mBinderContextCheckFunc = NULL;
172 mBinderContextUserData = NULL;
Steve Blocke6f43dd2012-01-06 19:20:56 +0000173 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174 }
175 }
176 return mManagesContexts;
177}
178
179ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
180{
181 const size_t N=mHandleToObject.size();
182 if (N <= (size_t)handle) {
183 handle_entry e;
184 e.binder = NULL;
185 e.refs = NULL;
186 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
187 if (err < NO_ERROR) return NULL;
188 }
189 return &mHandleToObject.editItemAt(handle);
190}
191
192sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
193{
194 sp<IBinder> result;
195
196 AutoMutex _l(mLock);
197
198 handle_entry* e = lookupHandleLocked(handle);
199
200 if (e != NULL) {
201 // We need to create a new BpBinder if there isn't currently one, OR we
202 // are unable to acquire a weak reference on this current one. See comment
203 // in getWeakProxyForHandle() for more info about this.
204 IBinder* b = e->binder;
205 if (b == NULL || !e->refs->attemptIncWeak(this)) {
Todd Poynora7b0f042013-06-18 17:25:37 -0700206 if (handle == 0) {
207 // Special case for context manager...
208 // The context manager is the only object for which we create
209 // a BpBinder proxy without already holding a reference.
210 // Perform a dummy transaction to ensure the context manager
211 // is registered before we create the first local reference
212 // to it (which will occur when creating the BpBinder).
213 // If a local reference is created for the BpBinder when the
214 // context manager is not present, the driver will fail to
215 // provide a reference to the context manager, but the
216 // driver API does not return status.
217 //
218 // Note that this is not race-free if the context manager
219 // dies while this code runs.
220 //
221 // TODO: add a driver API to wait for context manager, or
222 // stop special casing handle 0 for context manager and add
223 // a driver API to get a handle to the context manager with
224 // proper reference counting.
225
226 Parcel data;
227 status_t status = IPCThreadState::self()->transact(
228 0, IBinder::PING_TRANSACTION, data, NULL, 0);
229 if (status == DEAD_OBJECT)
230 return NULL;
231 }
232
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233 b = new BpBinder(handle);
234 e->binder = b;
235 if (b) e->refs = b->getWeakRefs();
236 result = b;
237 } else {
238 // This little bit of nastyness is to allow us to add a primary
239 // reference to the remote proxy when this team doesn't have one
240 // but another team is sending the handle to us.
241 result.force_set(b);
242 e->refs->decWeak(this);
243 }
244 }
245
246 return result;
247}
248
249wp<IBinder> ProcessState::getWeakProxyForHandle(int32_t handle)
250{
251 wp<IBinder> result;
252
253 AutoMutex _l(mLock);
254
255 handle_entry* e = lookupHandleLocked(handle);
256
257 if (e != NULL) {
258 // We need to create a new BpBinder if there isn't currently one, OR we
259 // are unable to acquire a weak reference on this current one. The
260 // attemptIncWeak() is safe because we know the BpBinder destructor will always
261 // call expungeHandle(), which acquires the same lock we are holding now.
262 // We need to do this because there is a race condition between someone
263 // releasing a reference on this BpBinder, and a new reference on its handle
264 // arriving from the driver.
265 IBinder* b = e->binder;
266 if (b == NULL || !e->refs->attemptIncWeak(this)) {
267 b = new BpBinder(handle);
268 result = b;
269 e->binder = b;
270 if (b) e->refs = b->getWeakRefs();
271 } else {
272 result = b;
273 e->refs->decWeak(this);
274 }
275 }
276
277 return result;
278}
279
280void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
281{
282 AutoMutex _l(mLock);
283
284 handle_entry* e = lookupHandleLocked(handle);
285
286 // This handle may have already been replaced with a new BpBinder
287 // (if someone failed the AttemptIncWeak() above); we don't want
288 // to overwrite it.
289 if (e && e->binder == binder) e->binder = NULL;
290}
291
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800292String8 ProcessState::makeBinderThreadName() {
293 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
Philip Cuadraa082fa82016-04-08 10:29:14 -0700294 pid_t pid = getpid();
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800295 String8 name;
Philip Cuadraa082fa82016-04-08 10:29:14 -0700296 name.appendFormat("Binder:%d_%X", pid, s);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800297 return name;
298}
299
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800300void ProcessState::spawnPooledThread(bool isMain)
301{
302 if (mThreadPoolStarted) {
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800303 String8 name = makeBinderThreadName();
304 ALOGV("Spawning new pooled thread, name=%s\n", name.string());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 sp<Thread> t = new PoolThread(isMain);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800306 t->run(name.string());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307 }
308}
309
Mathias Agopian1b80f792012-04-17 16:11:08 -0700310status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
311 status_t result = NO_ERROR;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700312 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
313 mMaxThreads = maxThreads;
314 } else {
Mathias Agopian1b80f792012-04-17 16:11:08 -0700315 result = -errno;
316 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
317 }
318 return result;
319}
320
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800321void ProcessState::giveThreadPoolName() {
322 androidSetThreadName( makeBinderThreadName().string() );
323}
324
Iliyan Malchev32062242017-04-10 14:06:11 -0700325String8 ProcessState::getDriverName() {
326 return mDriverName;
327}
328
Martijn Coenen55d871c2017-03-21 15:56:40 -0700329static int open_driver(const char *driver)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800330{
Martijn Coenen55d871c2017-03-21 15:56:40 -0700331 int fd = open(driver, O_RDWR | O_CLOEXEC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800332 if (fd >= 0) {
Jin Wei78181df2012-10-18 17:00:48 +0800333 int vers = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334 status_t result = ioctl(fd, BINDER_VERSION, &vers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800335 if (result == -1) {
Steve Blocke6f43dd2012-01-06 19:20:56 +0000336 ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800337 close(fd);
338 fd = -1;
339 }
340 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
Greg Hartman67ac00f2017-01-03 16:54:59 -0800341 ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)! ioctl() return value: %d",
342 vers, BINDER_CURRENT_PROTOCOL_VERSION, result);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343 close(fd);
344 fd = -1;
345 }
Wale Ogunwale376b8222015-04-13 16:16:10 -0700346 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800347 result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
348 if (result == -1) {
Steve Blocke6f43dd2012-01-06 19:20:56 +0000349 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800350 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351 } else {
Martijn Coenen55d871c2017-03-21 15:56:40 -0700352 ALOGW("Opening '%s' failed: %s\n", driver, strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800353 }
354 return fd;
355}
356
Martijn Coenen55d871c2017-03-21 15:56:40 -0700357ProcessState::ProcessState(const char *driver)
Iliyan Malchev32062242017-04-10 14:06:11 -0700358 : mDriverName(String8(driver))
359 , mDriverFD(open_driver(driver))
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800360 , mVMStart(MAP_FAILED)
Wale Ogunwale376b8222015-04-13 16:16:10 -0700361 , mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
362 , mThreadCountDecrement(PTHREAD_COND_INITIALIZER)
363 , mExecutingThreadsCount(0)
364 , mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
Colin Cross96e83222016-04-15 14:29:55 -0700365 , mStarvationStartTimeMs(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800366 , mManagesContexts(false)
367 , mBinderContextCheckFunc(NULL)
368 , mBinderContextUserData(NULL)
369 , mThreadPoolStarted(false)
370 , mThreadPoolSeq(1)
371{
372 if (mDriverFD >= 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800373 // mmap the binder, providing a chunk of virtual address space to receive transactions.
374 mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
375 if (mVMStart == MAP_FAILED) {
376 // *sigh*
Steve Blocke6f43dd2012-01-06 19:20:56 +0000377 ALOGE("Using /dev/binder failed: unable to mmap transaction memory.\n");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378 close(mDriverFD);
379 mDriverFD = -1;
Iliyan Malchev32062242017-04-10 14:06:11 -0700380 mDriverName.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800382 }
Jeff Browne16986c2011-07-08 18:52:57 -0700383
384 LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver could not be opened. Terminating.");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800385}
386
387ProcessState::~ProcessState()
388{
zhongjieff405782016-03-09 15:05:04 +0800389 if (mDriverFD >= 0) {
390 if (mVMStart != MAP_FAILED) {
391 munmap(mVMStart, BINDER_VM_SIZE);
392 }
393 close(mDriverFD);
394 }
395 mDriverFD = -1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800396}
397
398}; // namespace android