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