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 <utils/Log.h>
25 #include <utils/String8.h>
26 #include <utils/threads.h>
27 
28 #include "binder_kernel.h"
29 #include <hwbinder/Static.h>
30 
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <unistd.h>
36 #include <sys/ioctl.h>
37 #include <sys/mman.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40 
41 #define DEFAULT_BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
42 #define DEFAULT_MAX_BINDER_THREADS 0
43 #define DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION 1
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     return init(DEFAULT_BINDER_VM_SIZE, false /*requireMmapSize*/);
71 }
72 
selfOrNull()73 sp<ProcessState> ProcessState::selfOrNull() {
74     return init(0, false /*requireMmapSize*/);
75 }
76 
initWithMmapSize(size_t mmapSize)77 sp<ProcessState> ProcessState::initWithMmapSize(size_t mmapSize) {
78     return init(mmapSize, true /*requireMmapSize*/);
79 }
80 
init(size_t mmapSize,bool requireMmapSize)81 sp<ProcessState> ProcessState::init(size_t mmapSize, bool requireMmapSize) {
82     [[clang::no_destroy]] static sp<ProcessState> gProcess;
83     [[clang::no_destroy]] static std::mutex gProcessMutex;
84 
85     if (mmapSize == 0) {
86         std::lock_guard<std::mutex> l(gProcessMutex);
87         return gProcess;
88     }
89 
90     [[clang::no_destroy]] static std::once_flag gProcessOnce;
91     std::call_once(gProcessOnce, [&](){
92         std::lock_guard<std::mutex> l(gProcessMutex);
93         gProcess = new ProcessState(mmapSize);
94     });
95 
96     if (requireMmapSize) {
97         LOG_ALWAYS_FATAL_IF(mmapSize != gProcess->getMmapSize(),
98             "ProcessState already initialized with a different mmap size.");
99     }
100 
101     return gProcess;
102 }
103 
startThreadPool()104 void ProcessState::startThreadPool()
105 {
106     AutoMutex _l(mLock);
107     if (!mThreadPoolStarted) {
108         mThreadPoolStarted = true;
109         if (mSpawnThreadOnStart) {
110             spawnPooledThread(true);
111         }
112     }
113 }
114 
getContextObject(const sp<IBinder> &)115 sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
116 {
117     return getStrongProxyForHandle(0);
118 }
119 
becomeContextManager()120 void ProcessState::becomeContextManager()
121 {
122     AutoMutex _l(mLock);
123 
124     flat_binder_object obj {
125         .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
126     };
127 
128     status_t result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
129 
130     // fallback to original method
131     if (result != 0) {
132         android_errorWriteLog(0x534e4554, "121035042");
133 
134         int unused = 0;
135         result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
136     }
137 
138     if (result == -1) {
139         ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
140     }
141 }
142 
143 // Get references to userspace objects held by the kernel binder driver
144 // Writes up to count elements into buf, and returns the total number
145 // of references the kernel has, which may be larger than count.
146 // buf may be NULL if count is 0.  The pointers returned by this method
147 // should only be used for debugging and not dereferenced, they may
148 // already be invalid.
getKernelReferences(size_t buf_count,uintptr_t * buf)149 ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf) {
150     binder_node_debug_info info = {};
151 
152     uintptr_t* end = buf ? buf + buf_count : nullptr;
153     size_t count = 0;
154 
155     do {
156         status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
157         if (result < 0) {
158             return -1;
159         }
160         if (info.ptr != 0) {
161             if (buf && buf < end) *buf++ = info.ptr;
162             count++;
163             if (buf && buf < end) *buf++ = info.cookie;
164             count++;
165         }
166     } while (info.ptr != 0);
167 
168     return count;
169 }
170 
171 // Queries the driver for the current strong reference count of the node
172 // that the handle points to. Can only be used by the servicemanager.
173 //
174 // Returns -1 in case of failure, otherwise the strong reference count.
getStrongRefCountForNodeByHandle(int32_t handle)175 ssize_t ProcessState::getStrongRefCountForNodeByHandle(int32_t handle) {
176     binder_node_info_for_ref info;
177     memset(&info, 0, sizeof(binder_node_info_for_ref));
178 
179     info.handle = handle;
180 
181     status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
182 
183     if (result != OK) {
184         static bool logged = false;
185         if (!logged) {
186           ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
187           logged = true;
188         }
189         return -1;
190     }
191 
192     return info.strong_count;
193 }
194 
getMmapSize()195 size_t ProcessState::getMmapSize() {
196     return mMmapSize;
197 }
198 
setCallRestriction(CallRestriction restriction)199 void ProcessState::setCallRestriction(CallRestriction restriction) {
200     LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
201         "Call restrictions must be set before the threadpool is started.");
202 
203     mCallRestriction = restriction;
204 }
205 
lookupHandleLocked(int32_t handle)206 ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
207 {
208     const size_t N=mHandleToObject.size();
209     if (N <= (size_t)handle) {
210         handle_entry e;
211         e.binder = nullptr;
212         e.refs = nullptr;
213         status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
214         if (err < NO_ERROR) return nullptr;
215     }
216     return &mHandleToObject.editItemAt(handle);
217 }
218 
getStrongProxyForHandle(int32_t handle)219 sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
220 {
221     sp<IBinder> result;
222 
223     AutoMutex _l(mLock);
224 
225     handle_entry* e = lookupHandleLocked(handle);
226 
227     if (e != nullptr) {
228         // We need to create a new BpHwBinder if there isn't currently one, OR we
229         // are unable to acquire a weak reference on this current one.  See comment
230         // in getWeakProxyForHandle() for more info about this.
231         IBinder* b = e->binder;
232         if (b == nullptr || !e->refs->attemptIncWeak(this)) {
233             b = new BpHwBinder(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 != nullptr) {
258         // We need to create a new BpHwBinder 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 BpHwBinder 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 BpHwBinder, and a new reference on its handle
264         // arriving from the driver.
265         IBinder* b = e->binder;
266         if (b == nullptr || !e->refs->attemptIncWeak(this)) {
267             b = new BpHwBinder(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 BpHwBinder
287     // (if someone failed the AttemptIncWeak() above); we don't want
288     // to overwrite it.
289     if (e && e->binder == binder) e->binder = nullptr;
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("HwBinder:%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 
setThreadPoolConfiguration(size_t maxThreads,bool callerJoinsPool)310 status_t ProcessState::setThreadPoolConfiguration(size_t maxThreads, bool callerJoinsPool) {
311     LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
312            "Binder threadpool cannot be shrunk after starting");
313 
314     // if the caller joins the pool, then there will be one thread which is impossible.
315     LOG_ALWAYS_FATAL_IF(maxThreads == 0 && callerJoinsPool,
316            "Binder threadpool must have a minimum of one thread if caller joins pool.");
317 
318     size_t threadsToAllocate = maxThreads;
319 
320     // If the caller is going to join the pool it will contribute one thread to the threadpool.
321     // This is part of the API's contract.
322     if (callerJoinsPool) threadsToAllocate--;
323 
324     // If we can, spawn one thread from userspace when the threadpool is started. This ensures
325     // that there is always a thread available to start more threads as soon as the threadpool
326     // is started.
327     bool spawnThreadOnStart = threadsToAllocate > 0;
328     if (spawnThreadOnStart) threadsToAllocate--;
329 
330     // the BINDER_SET_MAX_THREADS ioctl really tells the kernel how many threads
331     // it's allowed to spawn, *in addition* to any threads we may have already
332     // spawned locally.
333     size_t kernelMaxThreads = threadsToAllocate;
334 
335     AutoMutex _l(mLock);
336     if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &kernelMaxThreads) == -1) {
337         ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
338         return -errno;
339     }
340 
341     mMaxThreads = maxThreads;
342     mSpawnThreadOnStart = spawnThreadOnStart;
343 
344     return NO_ERROR;
345 }
346 
enableOnewaySpamDetection(bool enable)347 status_t ProcessState::enableOnewaySpamDetection(bool enable) {
348     uint32_t enableDetection = enable ? 1 : 0;
349     if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
350         ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
351         return -errno;
352     }
353     return NO_ERROR;
354 }
355 
getMaxThreads()356 size_t ProcessState::getMaxThreads() {
357     return mMaxThreads;
358 }
359 
giveThreadPoolName()360 void ProcessState::giveThreadPoolName() {
361     androidSetThreadName( makeBinderThreadName().string() );
362 }
363 
open_driver()364 static int open_driver()
365 {
366     int fd = open("/dev/hwbinder", O_RDWR | O_CLOEXEC);
367     if (fd >= 0) {
368         int vers = 0;
369         status_t result = ioctl(fd, BINDER_VERSION, &vers);
370         if (result == -1) {
371             ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));
372             close(fd);
373             fd = -1;
374         }
375         if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
376           ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)!", vers, BINDER_CURRENT_PROTOCOL_VERSION);
377             close(fd);
378             fd = -1;
379         }
380         size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
381         result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
382         if (result == -1) {
383             ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
384         }
385         uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
386         result = ioctl(fd, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
387         if (result == -1) {
388             ALOGD("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
389         }
390     } else {
391         ALOGW("Opening '/dev/hwbinder' failed: %s\n", strerror(errno));
392     }
393     return fd;
394 }
395 
ProcessState(size_t mmapSize)396 ProcessState::ProcessState(size_t mmapSize)
397     : mDriverFD(open_driver())
398     , mVMStart(MAP_FAILED)
399     , mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
400     , mExecutingThreadsCount(0)
401     , mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
402     , mStarvationStartTimeMs(0)
403     , mThreadPoolStarted(false)
404     , mSpawnThreadOnStart(true)
405     , mThreadPoolSeq(1)
406     , mMmapSize(mmapSize)
407     , mCallRestriction(CallRestriction::NONE)
408 {
409     if (mDriverFD >= 0) {
410         // mmap the binder, providing a chunk of virtual address space to receive transactions.
411         mVMStart = mmap(nullptr, mMmapSize, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
412         if (mVMStart == MAP_FAILED) {
413             // *sigh*
414             ALOGE("Mmapping /dev/hwbinder failed: %s\n", strerror(errno));
415             close(mDriverFD);
416             mDriverFD = -1;
417         }
418     }
419 
420 #ifdef __ANDROID__
421     LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver could not be opened. Terminating.");
422 #endif
423 }
424 
~ProcessState()425 ProcessState::~ProcessState()
426 {
427     if (mDriverFD >= 0) {
428         if (mVMStart != MAP_FAILED) {
429             munmap(mVMStart, mMmapSize);
430         }
431         close(mDriverFD);
432     }
433     mDriverFD = -1;
434 }
435 
436 } // namespace hardware
437 } // namespace android
438