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