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
17 #define LOG_TAG "ProcessState"
18
19 #include <binder/ProcessState.h>
20
21 #include <utils/Atomic.h>
22 #include <binder/BpBinder.h>
23 #include <binder/IPCThreadState.h>
24 #include <utils/Log.h>
25 #include <utils/String8.h>
26 #include <binder/IServiceManager.h>
27 #include <utils/String8.h>
28 #include <utils/threads.h>
29
30 #include <private/binder/binder_module.h>
31 #include <private/binder/Static.h>
32
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>
41 #include <sys/types.h>
42
43 #define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
44 #define DEFAULT_MAX_BINDER_THREADS 15
45
46 // -------------------------------------------------------------------------
47
48 namespace android {
49
50 class PoolThread : public Thread
51 {
52 public:
PoolThread(bool isMain)53 explicit PoolThread(bool isMain)
54 : mIsMain(isMain)
55 {
56 }
57
58 protected:
threadLoop()59 virtual bool threadLoop()
60 {
61 IPCThreadState::self()->joinThreadPool(mIsMain);
62 return false;
63 }
64
65 const bool mIsMain;
66 };
67
self()68 sp<ProcessState> ProcessState::self()
69 {
70 Mutex::Autolock _l(gProcessMutex);
71 if (gProcess != NULL) {
72 return gProcess;
73 }
74 gProcess = new ProcessState("/dev/binder");
75 return gProcess;
76 }
77
initWithDriver(const char * driver)78 sp<ProcessState> ProcessState::initWithDriver(const char* driver)
79 {
80 Mutex::Autolock _l(gProcessMutex);
81 if (gProcess != NULL) {
82 // Allow for initWithDriver to be called repeatedly with the same
83 // driver.
84 if (!strcmp(gProcess->getDriverName().c_str(), driver)) {
85 return gProcess;
86 }
87 LOG_ALWAYS_FATAL("ProcessState was already initialized.");
88 }
89 gProcess = new ProcessState(driver);
90 return gProcess;
91 }
92
setContextObject(const sp<IBinder> & object)93 void ProcessState::setContextObject(const sp<IBinder>& object)
94 {
95 setContextObject(object, String16("default"));
96 }
97
getContextObject(const sp<IBinder> &)98 sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
99 {
100 return getStrongProxyForHandle(0);
101 }
102
setContextObject(const sp<IBinder> & object,const String16 & name)103 void ProcessState::setContextObject(const sp<IBinder>& object, const String16& name)
104 {
105 AutoMutex _l(mLock);
106 mContexts.add(name, object);
107 }
108
getContextObject(const String16 & name,const sp<IBinder> & caller)109 sp<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) {
122 ALOGE("getContextObject(%s) failed, but we manage the contexts!\n",
123 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
startThreadPool()145 void ProcessState::startThreadPool()
146 {
147 AutoMutex _l(mLock);
148 if (!mThreadPoolStarted) {
149 mThreadPoolStarted = true;
150 spawnPooledThread(true);
151 }
152 }
153
isContextManager(void) const154 bool ProcessState::isContextManager(void) const
155 {
156 return mManagesContexts;
157 }
158
becomeContextManager(context_check_func checkFunc,void * userData)159 bool ProcessState::becomeContextManager(context_check_func checkFunc, void* userData)
160 {
161 if (!mManagesContexts) {
162 AutoMutex _l(mLock);
163 mBinderContextCheckFunc = checkFunc;
164 mBinderContextUserData = userData;
165
166 int dummy = 0;
167 status_t result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &dummy);
168 if (result == 0) {
169 mManagesContexts = true;
170 } else if (result == -1) {
171 mBinderContextCheckFunc = NULL;
172 mBinderContextUserData = NULL;
173 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
174 }
175 }
176 return mManagesContexts;
177 }
178
lookupHandleLocked(int32_t handle)179 ProcessState::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
getStrongProxyForHandle(int32_t handle)192 sp<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)) {
206 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
233 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
getWeakProxyForHandle(int32_t handle)249 wp<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
expungeHandle(int32_t handle,IBinder * binder)280 void 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
makeBinderThreadName()292 String8 ProcessState::makeBinderThreadName() {
293 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
294 pid_t pid = getpid();
295 String8 name;
296 name.appendFormat("Binder:%d_%X", pid, s);
297 return name;
298 }
299
spawnPooledThread(bool isMain)300 void ProcessState::spawnPooledThread(bool isMain)
301 {
302 if (mThreadPoolStarted) {
303 String8 name = makeBinderThreadName();
304 ALOGV("Spawning new pooled thread, name=%s\n", name.string());
305 sp<Thread> t = new PoolThread(isMain);
306 t->run(name.string());
307 }
308 }
309
setThreadPoolMaxThreadCount(size_t maxThreads)310 status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
311 status_t result = NO_ERROR;
312 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
313 mMaxThreads = maxThreads;
314 } else {
315 result = -errno;
316 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
317 }
318 return result;
319 }
320
giveThreadPoolName()321 void ProcessState::giveThreadPoolName() {
322 androidSetThreadName( makeBinderThreadName().string() );
323 }
324
getDriverName()325 String8 ProcessState::getDriverName() {
326 return mDriverName;
327 }
328
open_driver(const char * driver)329 static int open_driver(const char *driver)
330 {
331 int fd = open(driver, O_RDWR | O_CLOEXEC);
332 if (fd >= 0) {
333 int vers = 0;
334 status_t result = ioctl(fd, BINDER_VERSION, &vers);
335 if (result == -1) {
336 ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));
337 close(fd);
338 fd = -1;
339 }
340 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
341 ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)! ioctl() return value: %d",
342 vers, BINDER_CURRENT_PROTOCOL_VERSION, result);
343 close(fd);
344 fd = -1;
345 }
346 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
347 result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
348 if (result == -1) {
349 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
350 }
351 } else {
352 ALOGW("Opening '%s' failed: %s\n", driver, strerror(errno));
353 }
354 return fd;
355 }
356
ProcessState(const char * driver)357 ProcessState::ProcessState(const char *driver)
358 : mDriverName(String8(driver))
359 , mDriverFD(open_driver(driver))
360 , mVMStart(MAP_FAILED)
361 , mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
362 , mThreadCountDecrement(PTHREAD_COND_INITIALIZER)
363 , mExecutingThreadsCount(0)
364 , mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
365 , mStarvationStartTimeMs(0)
366 , mManagesContexts(false)
367 , mBinderContextCheckFunc(NULL)
368 , mBinderContextUserData(NULL)
369 , mThreadPoolStarted(false)
370 , mThreadPoolSeq(1)
371 {
372 if (mDriverFD >= 0) {
373 // 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*
377 ALOGE("Using /dev/binder failed: unable to mmap transaction memory.\n");
378 close(mDriverFD);
379 mDriverFD = -1;
380 mDriverName.clear();
381 }
382 }
383
384 LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver could not be opened. Terminating.");
385 }
386
~ProcessState()387 ProcessState::~ProcessState()
388 {
389 if (mDriverFD >= 0) {
390 if (mVMStart != MAP_FAILED) {
391 munmap(mVMStart, BINDER_VM_SIZE);
392 }
393 close(mDriverFD);
394 }
395 mDriverFD = -1;
396 }
397
398 }; // namespace android
399