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 != nullptr) {
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 != nullptr) {
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) : nullptr);
116 mLock.unlock();
117
118 //printf("Getting context object %s for %p\n", String8(name).string(), caller.get());
119
120 if (object != nullptr) 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 nullptr;
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 != nullptr) 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 = nullptr;
188 mBinderContextUserData = nullptr;
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 : nullptr;
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
223 // Queries the driver for the current strong reference count of the node
224 // that the handle points to. Can only be used by the servicemanager.
225 //
226 // Returns -1 in case of failure, otherwise the strong reference count.
getStrongRefCountForNodeByHandle(int32_t handle)227 ssize_t ProcessState::getStrongRefCountForNodeByHandle(int32_t handle) {
228 binder_node_info_for_ref info;
229 memset(&info, 0, sizeof(binder_node_info_for_ref));
230
231 info.handle = handle;
232
233 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
234
235 if (result != OK) {
236 return -1;
237 }
238
239 return info.strong_count;
240 }
241
getMmapSize()242 size_t ProcessState::getMmapSize() {
243 return mMmapSize;
244 }
245
setCallRestriction(CallRestriction restriction)246 void ProcessState::setCallRestriction(CallRestriction restriction) {
247 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull(), "Call restrictions must be set before the threadpool is started.");
248
249 mCallRestriction = restriction;
250 }
251
lookupHandleLocked(int32_t handle)252 ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
253 {
254 const size_t N=mHandleToObject.size();
255 if (N <= (size_t)handle) {
256 handle_entry e;
257 e.binder = nullptr;
258 e.refs = nullptr;
259 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
260 if (err < NO_ERROR) return nullptr;
261 }
262 return &mHandleToObject.editItemAt(handle);
263 }
264
getStrongProxyForHandle(int32_t handle)265 sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
266 {
267 sp<IBinder> result;
268
269 AutoMutex _l(mLock);
270
271 handle_entry* e = lookupHandleLocked(handle);
272
273 if (e != nullptr) {
274 // We need to create a new BpHwBinder if there isn't currently one, OR we
275 // are unable to acquire a weak reference on this current one. See comment
276 // in getWeakProxyForHandle() for more info about this.
277 IBinder* b = e->binder;
278 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
279 b = new BpHwBinder(handle);
280 e->binder = b;
281 if (b) e->refs = b->getWeakRefs();
282 result = b;
283 } else {
284 // This little bit of nastyness is to allow us to add a primary
285 // reference to the remote proxy when this team doesn't have one
286 // but another team is sending the handle to us.
287 result.force_set(b);
288 e->refs->decWeak(this);
289 }
290 }
291
292 return result;
293 }
294
getWeakProxyForHandle(int32_t handle)295 wp<IBinder> ProcessState::getWeakProxyForHandle(int32_t handle)
296 {
297 wp<IBinder> result;
298
299 AutoMutex _l(mLock);
300
301 handle_entry* e = lookupHandleLocked(handle);
302
303 if (e != nullptr) {
304 // We need to create a new BpHwBinder if there isn't currently one, OR we
305 // are unable to acquire a weak reference on this current one. The
306 // attemptIncWeak() is safe because we know the BpHwBinder destructor will always
307 // call expungeHandle(), which acquires the same lock we are holding now.
308 // We need to do this because there is a race condition between someone
309 // releasing a reference on this BpHwBinder, and a new reference on its handle
310 // arriving from the driver.
311 IBinder* b = e->binder;
312 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
313 b = new BpHwBinder(handle);
314 result = b;
315 e->binder = b;
316 if (b) e->refs = b->getWeakRefs();
317 } else {
318 result = b;
319 e->refs->decWeak(this);
320 }
321 }
322
323 return result;
324 }
325
expungeHandle(int32_t handle,IBinder * binder)326 void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
327 {
328 AutoMutex _l(mLock);
329
330 handle_entry* e = lookupHandleLocked(handle);
331
332 // This handle may have already been replaced with a new BpHwBinder
333 // (if someone failed the AttemptIncWeak() above); we don't want
334 // to overwrite it.
335 if (e && e->binder == binder) e->binder = nullptr;
336 }
337
makeBinderThreadName()338 String8 ProcessState::makeBinderThreadName() {
339 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
340 pid_t pid = getpid();
341 String8 name;
342 name.appendFormat("HwBinder:%d_%X", pid, s);
343 return name;
344 }
345
spawnPooledThread(bool isMain)346 void ProcessState::spawnPooledThread(bool isMain)
347 {
348 if (mThreadPoolStarted) {
349 String8 name = makeBinderThreadName();
350 ALOGV("Spawning new pooled thread, name=%s\n", name.string());
351 sp<Thread> t = new PoolThread(isMain);
352 t->run(name.string());
353 }
354 }
355
setThreadPoolConfiguration(size_t maxThreads,bool callerJoinsPool)356 status_t ProcessState::setThreadPoolConfiguration(size_t maxThreads, bool callerJoinsPool) {
357 // if the caller joins the pool, then there will be one thread which is impossible.
358 LOG_ALWAYS_FATAL_IF(maxThreads == 0 && callerJoinsPool,
359 "Binder threadpool must have a minimum of one thread if caller joins pool.");
360
361 size_t threadsToAllocate = maxThreads;
362
363 // If the caller is going to join the pool it will contribute one thread to the threadpool.
364 // This is part of the API's contract.
365 if (callerJoinsPool) threadsToAllocate--;
366
367 // If we can, spawn one thread from userspace when the threadpool is started. This ensures
368 // that there is always a thread available to start more threads as soon as the threadpool
369 // is started.
370 bool spawnThreadOnStart = threadsToAllocate > 0;
371 if (spawnThreadOnStart) threadsToAllocate--;
372
373 // the BINDER_SET_MAX_THREADS ioctl really tells the kernel how many threads
374 // it's allowed to spawn, *in addition* to any threads we may have already
375 // spawned locally.
376 size_t kernelMaxThreads = threadsToAllocate;
377
378 AutoMutex _l(mLock);
379 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &kernelMaxThreads) == -1) {
380 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
381 return -errno;
382 }
383
384 mMaxThreads = maxThreads;
385 mSpawnThreadOnStart = spawnThreadOnStart;
386
387 return NO_ERROR;
388 }
389
getMaxThreads()390 size_t ProcessState::getMaxThreads() {
391 return mMaxThreads;
392 }
393
giveThreadPoolName()394 void ProcessState::giveThreadPoolName() {
395 androidSetThreadName( makeBinderThreadName().string() );
396 }
397
open_driver()398 static int open_driver()
399 {
400 int fd = open("/dev/hwbinder", O_RDWR | O_CLOEXEC);
401 if (fd >= 0) {
402 int vers = 0;
403 status_t result = ioctl(fd, BINDER_VERSION, &vers);
404 if (result == -1) {
405 ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));
406 close(fd);
407 fd = -1;
408 }
409 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
410 ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)!", vers, BINDER_CURRENT_PROTOCOL_VERSION);
411 close(fd);
412 fd = -1;
413 }
414 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
415 result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
416 if (result == -1) {
417 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
418 }
419 } else {
420 ALOGW("Opening '/dev/hwbinder' failed: %s\n", strerror(errno));
421 }
422 return fd;
423 }
424
ProcessState(size_t mmap_size)425 ProcessState::ProcessState(size_t mmap_size)
426 : mDriverFD(open_driver())
427 , mVMStart(MAP_FAILED)
428 , mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
429 , mThreadCountDecrement(PTHREAD_COND_INITIALIZER)
430 , mExecutingThreadsCount(0)
431 , mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
432 , mStarvationStartTimeMs(0)
433 , mManagesContexts(false)
434 , mBinderContextCheckFunc(nullptr)
435 , mBinderContextUserData(nullptr)
436 , mThreadPoolStarted(false)
437 , mSpawnThreadOnStart(true)
438 , mThreadPoolSeq(1)
439 , mMmapSize(mmap_size)
440 , mCallRestriction(CallRestriction::NONE)
441 {
442 if (mDriverFD >= 0) {
443 // mmap the binder, providing a chunk of virtual address space to receive transactions.
444 mVMStart = mmap(nullptr, mMmapSize, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
445 if (mVMStart == MAP_FAILED) {
446 // *sigh*
447 ALOGE("Mmapping /dev/hwbinder failed: %s\n", strerror(errno));
448 close(mDriverFD);
449 mDriverFD = -1;
450 }
451 }
452 else {
453 ALOGE("Binder driver could not be opened. Terminating.");
454 }
455 }
456
~ProcessState()457 ProcessState::~ProcessState()
458 {
459 if (mDriverFD >= 0) {
460 if (mVMStart != MAP_FAILED) {
461 munmap(mVMStart, mMmapSize);
462 }
463 close(mDriverFD);
464 }
465 mDriverFD = -1;
466 }
467
468 }; // namespace hardware
469 }; // namespace android
470