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/HidlSupport.h>
23 #include <hwbinder/BpHwBinder.h>
24 #include <hwbinder/IPCThreadState.h>
25 #include <utils/Log.h>
26 #include <utils/String8.h>
27 #include <utils/threads.h>
28
29 #include "binder_kernel.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 #include <mutex>
43
44 #define DEFAULT_BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
45 #define DEFAULT_MAX_BINDER_THREADS 0
46 #define DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION 1
47
48 // -------------------------------------------------------------------------
49
50 namespace android {
51 namespace hardware {
52
53 class PoolThread : public Thread
54 {
55 public:
PoolThread(bool isMain)56 explicit PoolThread(bool isMain)
57 : mIsMain(isMain)
58 {
59 }
60
61 protected:
threadLoop()62 virtual bool threadLoop()
63 {
64 IPCThreadState::self()->joinThreadPool(mIsMain);
65 return false;
66 }
67
68 const bool mIsMain;
69 };
70
self()71 sp<ProcessState> ProcessState::self()
72 {
73 return init(DEFAULT_BINDER_VM_SIZE, false /*requireMmapSize*/);
74 }
75
selfOrNull()76 sp<ProcessState> ProcessState::selfOrNull() {
77 return init(0, false /*requireMmapSize*/);
78 }
79
initWithMmapSize(size_t mmapSize)80 sp<ProcessState> ProcessState::initWithMmapSize(size_t mmapSize) {
81 return init(mmapSize, true /*requireMmapSize*/);
82 }
83
init(size_t mmapSize,bool requireMmapSize)84 sp<ProcessState> ProcessState::init(size_t mmapSize, bool requireMmapSize) {
85 [[clang::no_destroy]] static sp<ProcessState> gProcess;
86 [[clang::no_destroy]] static std::mutex gProcessMutex;
87
88 if (mmapSize == 0) {
89 std::lock_guard<std::mutex> l(gProcessMutex);
90 return gProcess;
91 }
92
93 [[clang::no_destroy]] static std::once_flag gProcessOnce;
94 std::call_once(gProcessOnce, [&](){
95 std::lock_guard<std::mutex> l(gProcessMutex);
96 gProcess = new ProcessState(mmapSize);
97 });
98
99 if (requireMmapSize) {
100 LOG_ALWAYS_FATAL_IF(mmapSize != gProcess->getMmapSize(),
101 "ProcessState already initialized with a different mmap size.");
102 }
103
104 return gProcess;
105 }
106
startThreadPool()107 void ProcessState::startThreadPool()
108 {
109 if (!isHwbinderSupportedBlocking()) {
110 ALOGW("HwBinder is not supported on this device. Not starting threadpool.");
111 return;
112 }
113 AutoMutex _l(mLock);
114 if (!mThreadPoolStarted) {
115 mThreadPoolStarted = true;
116 if (mSpawnThreadOnStart) {
117 spawnPooledThread(true);
118 }
119 }
120 }
121
getContextObject(const sp<IBinder> &)122 sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
123 {
124 return getStrongProxyForHandle(0);
125 }
126
becomeContextManager()127 void ProcessState::becomeContextManager()
128 {
129 AutoMutex _l(mLock);
130
131 flat_binder_object obj {
132 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
133 };
134
135 status_t result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
136
137 // fallback to original method
138 if (result != 0) {
139 android_errorWriteLog(0x534e4554, "121035042");
140
141 int unused = 0;
142 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
143 }
144
145 if (result == -1) {
146 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
147 }
148 }
149
150 // Get references to userspace objects held by the kernel binder driver
151 // Writes up to count elements into buf, and returns the total number
152 // of references the kernel has, which may be larger than count.
153 // buf may be NULL if count is 0. The pointers returned by this method
154 // should only be used for debugging and not dereferenced, they may
155 // already be invalid.
getKernelReferences(size_t buf_count,uintptr_t * buf)156 ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf) {
157 binder_node_debug_info info = {};
158
159 uintptr_t* end = buf ? buf + buf_count : nullptr;
160 size_t count = 0;
161
162 do {
163 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
164 if (result < 0) {
165 return -1;
166 }
167 if (info.ptr != 0) {
168 if (buf && buf < end) *buf++ = info.ptr;
169 count++;
170 if (buf && buf < end) *buf++ = info.cookie;
171 count++;
172 }
173 } while (info.ptr != 0);
174
175 return count;
176 }
177
178 // Queries the driver for the current strong reference count of the node
179 // that the handle points to. Can only be used by the servicemanager.
180 //
181 // Returns -1 in case of failure, otherwise the strong reference count.
getStrongRefCountForNodeByHandle(int32_t handle)182 ssize_t ProcessState::getStrongRefCountForNodeByHandle(int32_t handle) {
183 binder_node_info_for_ref info;
184 memset(&info, 0, sizeof(binder_node_info_for_ref));
185
186 info.handle = handle;
187
188 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
189
190 if (result != OK) {
191 static bool logged = false;
192 if (!logged) {
193 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
194 logged = true;
195 }
196 return -1;
197 }
198
199 return info.strong_count;
200 }
201
getMmapSize()202 size_t ProcessState::getMmapSize() {
203 return mMmapSize;
204 }
205
setCallRestriction(CallRestriction restriction)206 void ProcessState::setCallRestriction(CallRestriction restriction) {
207 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
208 "Call restrictions must be set before the threadpool is started.");
209
210 mCallRestriction = restriction;
211 }
212
lookupHandleLocked(int32_t handle)213 ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
214 {
215 const size_t N=mHandleToObject.size();
216 if (N <= (size_t)handle) {
217 handle_entry e;
218 e.binder = nullptr;
219 e.refs = nullptr;
220 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
221 if (err < NO_ERROR) return nullptr;
222 }
223 return &mHandleToObject.editItemAt(handle);
224 }
225
getStrongProxyForHandle(int32_t handle)226 sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
227 {
228 sp<IBinder> result;
229
230 AutoMutex _l(mLock);
231
232 handle_entry* e = lookupHandleLocked(handle);
233
234 if (e != nullptr) {
235 // We need to create a new BpHwBinder if there isn't currently one, OR we
236 // are unable to acquire a weak reference on this current one. See comment
237 // in getWeakProxyForHandle() for more info about this.
238 IBinder* b = e->binder;
239 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
240 b = new BpHwBinder(handle);
241 e->binder = b;
242 if (b) e->refs = b->getWeakRefs();
243 result = b;
244 } else {
245 // This little bit of nastyness is to allow us to add a primary
246 // reference to the remote proxy when this team doesn't have one
247 // but another team is sending the handle to us.
248 result.force_set(b);
249 e->refs->decWeak(this);
250 }
251 }
252
253 return result;
254 }
255
getWeakProxyForHandle(int32_t handle)256 wp<IBinder> ProcessState::getWeakProxyForHandle(int32_t handle)
257 {
258 wp<IBinder> result;
259
260 AutoMutex _l(mLock);
261
262 handle_entry* e = lookupHandleLocked(handle);
263
264 if (e != nullptr) {
265 // We need to create a new BpHwBinder if there isn't currently one, OR we
266 // are unable to acquire a weak reference on this current one. The
267 // attemptIncWeak() is safe because we know the BpHwBinder destructor will always
268 // call expungeHandle(), which acquires the same lock we are holding now.
269 // We need to do this because there is a race condition between someone
270 // releasing a reference on this BpHwBinder, and a new reference on its handle
271 // arriving from the driver.
272 IBinder* b = e->binder;
273 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
274 b = new BpHwBinder(handle);
275 result = b;
276 e->binder = b;
277 if (b) e->refs = b->getWeakRefs();
278 } else {
279 result = b;
280 e->refs->decWeak(this);
281 }
282 }
283
284 return result;
285 }
286
expungeHandle(int32_t handle,IBinder * binder)287 void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
288 {
289 AutoMutex _l(mLock);
290
291 handle_entry* e = lookupHandleLocked(handle);
292
293 // This handle may have already been replaced with a new BpHwBinder
294 // (if someone failed the AttemptIncWeak() above); we don't want
295 // to overwrite it.
296 if (e && e->binder == binder) e->binder = nullptr;
297 }
298
makeBinderThreadName()299 String8 ProcessState::makeBinderThreadName() {
300 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
301 pid_t pid = getpid();
302 String8 name;
303 name.appendFormat("HwBinder:%d_%X", pid, s);
304 return name;
305 }
306
spawnPooledThread(bool isMain)307 void ProcessState::spawnPooledThread(bool isMain)
308 {
309 if (mThreadPoolStarted) {
310 String8 name = makeBinderThreadName();
311 ALOGV("Spawning new pooled thread, name=%s\n", name.c_str());
312 sp<Thread> t = new PoolThread(isMain);
313 t->run(name.c_str());
314 }
315 }
316
setThreadPoolConfiguration(size_t maxThreads,bool callerJoinsPool)317 status_t ProcessState::setThreadPoolConfiguration(size_t maxThreads, bool callerJoinsPool) {
318 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
319 "Binder threadpool cannot be shrunk after starting");
320
321 // if the caller joins the pool, then there will be one thread which is impossible.
322 LOG_ALWAYS_FATAL_IF(maxThreads == 0 && callerJoinsPool,
323 "Binder threadpool must have a minimum of one thread if caller joins pool.");
324
325 if (!isHwbinderSupportedBlocking()) {
326 ALOGW("HwBinder is not supported on this device but this process is calling setThreadPoolConfiguration");
327 }
328
329 size_t threadsToAllocate = maxThreads;
330
331 // If the caller is going to join the pool it will contribute one thread to the threadpool.
332 // This is part of the API's contract.
333 if (callerJoinsPool) threadsToAllocate--;
334
335 // If we can, spawn one thread from userspace when the threadpool is started. This ensures
336 // that there is always a thread available to start more threads as soon as the threadpool
337 // is started.
338 bool spawnThreadOnStart = threadsToAllocate > 0;
339 if (spawnThreadOnStart) threadsToAllocate--;
340
341 // the BINDER_SET_MAX_THREADS ioctl really tells the kernel how many threads
342 // it's allowed to spawn, *in addition* to any threads we may have already
343 // spawned locally.
344 size_t kernelMaxThreads = threadsToAllocate;
345
346 AutoMutex _l(mLock);
347 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &kernelMaxThreads) == -1) {
348 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
349 return -errno;
350 }
351
352 mMaxThreads = maxThreads;
353 mSpawnThreadOnStart = spawnThreadOnStart;
354
355 return NO_ERROR;
356 }
357
enableOnewaySpamDetection(bool enable)358 status_t ProcessState::enableOnewaySpamDetection(bool enable) {
359 uint32_t enableDetection = enable ? 1 : 0;
360 if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
361 ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
362 return -errno;
363 }
364 return NO_ERROR;
365 }
366
getMaxThreads()367 size_t ProcessState::getMaxThreads() {
368 return mMaxThreads;
369 }
370
giveThreadPoolName()371 void ProcessState::giveThreadPoolName() {
372 androidSetThreadName( makeBinderThreadName().c_str() );
373 }
374
open_driver()375 static int open_driver()
376 {
377 int fd = open("/dev/hwbinder", O_RDWR | O_CLOEXEC);
378 if (fd >= 0) {
379 int vers = 0;
380 status_t result = ioctl(fd, BINDER_VERSION, &vers);
381 if (result == -1) {
382 ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));
383 close(fd);
384 fd = -1;
385 }
386 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
387 ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)!", vers, BINDER_CURRENT_PROTOCOL_VERSION);
388 close(fd);
389 fd = -1;
390 }
391 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
392 result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
393 if (result == -1) {
394 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
395 }
396 uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
397 result = ioctl(fd, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
398 if (result == -1) {
399 ALOGV("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
400 }
401 } else {
402 ALOGW("Opening '/dev/hwbinder' failed: %s\n", strerror(errno));
403 }
404 return fd;
405 }
406
ProcessState(size_t mmapSize)407 ProcessState::ProcessState(size_t mmapSize)
408 : mDriverFD(open_driver())
409 , mVMStart(MAP_FAILED)
410 , mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
411 , mExecutingThreadsCount(0)
412 , mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
413 , mStarvationStartTimeMs(0)
414 , mThreadPoolStarted(false)
415 , mSpawnThreadOnStart(true)
416 , mThreadPoolSeq(1)
417 , mMmapSize(mmapSize)
418 , mCallRestriction(CallRestriction::NONE)
419 {
420 if (mDriverFD >= 0) {
421 // mmap the binder, providing a chunk of virtual address space to receive transactions.
422 mVMStart = mmap(nullptr, mMmapSize, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
423 if (mVMStart == MAP_FAILED) {
424 // *sigh*
425 ALOGE("Mmapping /dev/hwbinder failed: %s\n", strerror(errno));
426 close(mDriverFD);
427 mDriverFD = -1;
428 }
429 }
430
431 #ifdef __ANDROID__
432 LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver could not be opened. Terminating.");
433 #endif
434 }
435
~ProcessState()436 ProcessState::~ProcessState()
437 {
438 if (mDriverFD >= 0) {
439 if (mVMStart != MAP_FAILED) {
440 munmap(mVMStart, mMmapSize);
441 }
442 close(mDriverFD);
443 }
444 mDriverFD = -1;
445 }
446
447 } // namespace hardware
448 } // namespace android
449