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