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 "ProcessState"
18
19 #include <binder/ProcessState.h>
20
21 #include <binder/BpBinder.h>
22 #include <binder/IPCThreadState.h>
23 #include <binder/IServiceManager.h>
24 #include <binder/Stability.h>
25 #include <cutils/atomic.h>
26 #include <utils/Log.h>
27 #include <utils/String8.h>
28 #include <utils/threads.h>
29
30 #include <private/binder/binder_module.h>
31 #include "Static.h"
32
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <mutex>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <unistd.h>
39 #include <sys/ioctl.h>
40 #include <sys/mman.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43
44 #define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
45 #define DEFAULT_MAX_BINDER_THREADS 15
46
47 #ifdef __ANDROID_VNDK__
48 const char* kDefaultDriver = "/dev/vndbinder";
49 #else
50 const char* kDefaultDriver = "/dev/binder";
51 #endif
52
53 // -------------------------------------------------------------------------
54
55 namespace android {
56
57 class PoolThread : public Thread
58 {
59 public:
PoolThread(bool isMain)60 explicit PoolThread(bool isMain)
61 : mIsMain(isMain)
62 {
63 }
64
65 protected:
threadLoop()66 virtual bool threadLoop()
67 {
68 IPCThreadState::self()->joinThreadPool(mIsMain);
69 return false;
70 }
71
72 const bool mIsMain;
73 };
74
self()75 sp<ProcessState> ProcessState::self()
76 {
77 return init(kDefaultDriver, false /*requireDefault*/);
78 }
79
initWithDriver(const char * driver)80 sp<ProcessState> ProcessState::initWithDriver(const char* driver)
81 {
82 return init(driver, true /*requireDefault*/);
83 }
84
selfOrNull()85 sp<ProcessState> ProcessState::selfOrNull()
86 {
87 return init(nullptr, false /*requireDefault*/);
88 }
89
init(const char * driver,bool requireDefault)90 sp<ProcessState> ProcessState::init(const char *driver, bool requireDefault)
91 {
92 [[clang::no_destroy]] static sp<ProcessState> gProcess;
93 [[clang::no_destroy]] static std::mutex gProcessMutex;
94
95 if (driver == nullptr) {
96 std::lock_guard<std::mutex> l(gProcessMutex);
97 return gProcess;
98 }
99
100 [[clang::no_destroy]] static std::once_flag gProcessOnce;
101 std::call_once(gProcessOnce, [&](){
102 if (access(driver, R_OK) == -1) {
103 ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
104 driver = "/dev/binder";
105 }
106
107 std::lock_guard<std::mutex> l(gProcessMutex);
108 gProcess = new ProcessState(driver);
109 });
110
111 if (requireDefault) {
112 // Detect if we are trying to initialize with a different driver, and
113 // consider that an error. ProcessState will only be initialized once above.
114 LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,
115 "ProcessState was already initialized with %s,"
116 " can't initialize with %s.",
117 gProcess->getDriverName().c_str(), driver);
118 }
119
120 return gProcess;
121 }
122
getContextObject(const sp<IBinder> &)123 sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
124 {
125 sp<IBinder> context = getStrongProxyForHandle(0);
126
127 if (context == nullptr) {
128 ALOGW("Not able to get context object on %s.", mDriverName.c_str());
129 }
130
131 // The root object is special since we get it directly from the driver, it is never
132 // written by Parcell::writeStrongBinder.
133 internal::Stability::tryMarkCompilationUnit(context.get());
134
135 return context;
136 }
137
startThreadPool()138 void ProcessState::startThreadPool()
139 {
140 AutoMutex _l(mLock);
141 if (!mThreadPoolStarted) {
142 mThreadPoolStarted = true;
143 spawnPooledThread(true);
144 }
145 }
146
becomeContextManager(context_check_func checkFunc,void * userData)147 bool ProcessState::becomeContextManager(context_check_func checkFunc, void* userData)
148 {
149 AutoMutex _l(mLock);
150 mBinderContextCheckFunc = checkFunc;
151 mBinderContextUserData = userData;
152
153 flat_binder_object obj {
154 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
155 };
156
157 int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
158
159 // fallback to original method
160 if (result != 0) {
161 android_errorWriteLog(0x534e4554, "121035042");
162
163 int dummy = 0;
164 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &dummy);
165 }
166
167 if (result == -1) {
168 mBinderContextCheckFunc = nullptr;
169 mBinderContextUserData = nullptr;
170 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
171 }
172
173 return result == 0;
174 }
175
176 // Get references to userspace objects held by the kernel binder driver
177 // Writes up to count elements into buf, and returns the total number
178 // of references the kernel has, which may be larger than count.
179 // buf may be NULL if count is 0. The pointers returned by this method
180 // should only be used for debugging and not dereferenced, they may
181 // already be invalid.
getKernelReferences(size_t buf_count,uintptr_t * buf)182 ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
183 {
184 binder_node_debug_info info = {};
185
186 uintptr_t* end = buf ? buf + buf_count : nullptr;
187 size_t count = 0;
188
189 do {
190 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
191 if (result < 0) {
192 return -1;
193 }
194 if (info.ptr != 0) {
195 if (buf && buf < end)
196 *buf++ = info.ptr;
197 count++;
198 if (buf && buf < end)
199 *buf++ = info.cookie;
200 count++;
201 }
202 } while (info.ptr != 0);
203
204 return count;
205 }
206
207 // Queries the driver for the current strong reference count of the node
208 // that the handle points to. Can only be used by the servicemanager.
209 //
210 // Returns -1 in case of failure, otherwise the strong reference count.
getStrongRefCountForNodeByHandle(int32_t handle)211 ssize_t ProcessState::getStrongRefCountForNodeByHandle(int32_t handle) {
212 binder_node_info_for_ref info;
213 memset(&info, 0, sizeof(binder_node_info_for_ref));
214
215 info.handle = handle;
216
217 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
218
219 if (result != OK) {
220 static bool logged = false;
221 if (!logged) {
222 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
223 logged = true;
224 }
225 return -1;
226 }
227
228 return info.strong_count;
229 }
230
setCallRestriction(CallRestriction restriction)231 void ProcessState::setCallRestriction(CallRestriction restriction) {
232 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
233 "Call restrictions must be set before the threadpool is started.");
234
235 mCallRestriction = restriction;
236 }
237
lookupHandleLocked(int32_t handle)238 ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
239 {
240 const size_t N=mHandleToObject.size();
241 if (N <= (size_t)handle) {
242 handle_entry e;
243 e.binder = nullptr;
244 e.refs = nullptr;
245 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
246 if (err < NO_ERROR) return nullptr;
247 }
248 return &mHandleToObject.editItemAt(handle);
249 }
250
getStrongProxyForHandle(int32_t handle)251 sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
252 {
253 sp<IBinder> result;
254
255 AutoMutex _l(mLock);
256
257 handle_entry* e = lookupHandleLocked(handle);
258
259 if (e != nullptr) {
260 // We need to create a new BpBinder if there isn't currently one, OR we
261 // are unable to acquire a weak reference on this current one. The
262 // attemptIncWeak() is safe because we know the BpBinder destructor will always
263 // call expungeHandle(), which acquires the same lock we are holding now.
264 // We need to do this because there is a race condition between someone
265 // releasing a reference on this BpBinder, and a new reference on its handle
266 // arriving from the driver.
267 IBinder* b = e->binder;
268 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
269 if (handle == 0) {
270 // Special case for context manager...
271 // The context manager is the only object for which we create
272 // a BpBinder proxy without already holding a reference.
273 // Perform a dummy transaction to ensure the context manager
274 // is registered before we create the first local reference
275 // to it (which will occur when creating the BpBinder).
276 // If a local reference is created for the BpBinder when the
277 // context manager is not present, the driver will fail to
278 // provide a reference to the context manager, but the
279 // driver API does not return status.
280 //
281 // Note that this is not race-free if the context manager
282 // dies while this code runs.
283 //
284 // TODO: add a driver API to wait for context manager, or
285 // stop special casing handle 0 for context manager and add
286 // a driver API to get a handle to the context manager with
287 // proper reference counting.
288
289 Parcel data;
290 status_t status = IPCThreadState::self()->transact(
291 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
292 if (status == DEAD_OBJECT)
293 return nullptr;
294 }
295
296 b = BpBinder::create(handle);
297 e->binder = b;
298 if (b) e->refs = b->getWeakRefs();
299 result = b;
300 } else {
301 // This little bit of nastyness is to allow us to add a primary
302 // reference to the remote proxy when this team doesn't have one
303 // but another team is sending the handle to us.
304 result.force_set(b);
305 e->refs->decWeak(this);
306 }
307 }
308
309 return result;
310 }
311
expungeHandle(int32_t handle,IBinder * binder)312 void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
313 {
314 AutoMutex _l(mLock);
315
316 handle_entry* e = lookupHandleLocked(handle);
317
318 // This handle may have already been replaced with a new BpBinder
319 // (if someone failed the AttemptIncWeak() above); we don't want
320 // to overwrite it.
321 if (e && e->binder == binder) e->binder = nullptr;
322 }
323
makeBinderThreadName()324 String8 ProcessState::makeBinderThreadName() {
325 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
326 pid_t pid = getpid();
327 String8 name;
328 name.appendFormat("Binder:%d_%X", pid, s);
329 return name;
330 }
331
spawnPooledThread(bool isMain)332 void ProcessState::spawnPooledThread(bool isMain)
333 {
334 if (mThreadPoolStarted) {
335 String8 name = makeBinderThreadName();
336 ALOGV("Spawning new pooled thread, name=%s\n", name.string());
337 sp<Thread> t = new PoolThread(isMain);
338 t->run(name.string());
339 }
340 }
341
setThreadPoolMaxThreadCount(size_t maxThreads)342 status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
343 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
344 "Binder threadpool cannot be shrunk after starting");
345 status_t result = NO_ERROR;
346 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
347 mMaxThreads = maxThreads;
348 } else {
349 result = -errno;
350 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
351 }
352 return result;
353 }
354
giveThreadPoolName()355 void ProcessState::giveThreadPoolName() {
356 androidSetThreadName( makeBinderThreadName().string() );
357 }
358
getDriverName()359 String8 ProcessState::getDriverName() {
360 return mDriverName;
361 }
362
open_driver(const char * driver)363 static int open_driver(const char *driver)
364 {
365 int fd = open(driver, O_RDWR | O_CLOEXEC);
366 if (fd >= 0) {
367 int vers = 0;
368 status_t result = ioctl(fd, BINDER_VERSION, &vers);
369 if (result == -1) {
370 ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));
371 close(fd);
372 fd = -1;
373 }
374 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
375 ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)! ioctl() return value: %d",
376 vers, BINDER_CURRENT_PROTOCOL_VERSION, result);
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 } else {
386 ALOGW("Opening '%s' failed: %s\n", driver, strerror(errno));
387 }
388 return fd;
389 }
390
ProcessState(const char * driver)391 ProcessState::ProcessState(const char *driver)
392 : mDriverName(String8(driver))
393 , mDriverFD(open_driver(driver))
394 , mVMStart(MAP_FAILED)
395 , mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
396 , mThreadCountDecrement(PTHREAD_COND_INITIALIZER)
397 , mExecutingThreadsCount(0)
398 , mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
399 , mStarvationStartTimeMs(0)
400 , mBinderContextCheckFunc(nullptr)
401 , mBinderContextUserData(nullptr)
402 , mThreadPoolStarted(false)
403 , mThreadPoolSeq(1)
404 , mCallRestriction(CallRestriction::NONE)
405 {
406
407 // TODO(b/139016109): enforce in build system
408 #if defined(__ANDROID_APEX__)
409 LOG_ALWAYS_FATAL("Cannot use libbinder in APEX (only system.img libbinder) since it is not stable.");
410 #endif
411
412 if (mDriverFD >= 0) {
413 // mmap the binder, providing a chunk of virtual address space to receive transactions.
414 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
415 if (mVMStart == MAP_FAILED) {
416 // *sigh*
417 ALOGE("Using %s failed: unable to mmap transaction memory.\n", mDriverName.c_str());
418 close(mDriverFD);
419 mDriverFD = -1;
420 mDriverName.clear();
421 }
422 }
423
424 LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver '%s' could not be opened. Terminating.", driver);
425 }
426
~ProcessState()427 ProcessState::~ProcessState()
428 {
429 if (mDriverFD >= 0) {
430 if (mVMStart != MAP_FAILED) {
431 munmap(mVMStart, BINDER_VM_SIZE);
432 }
433 close(mDriverFD);
434 }
435 mDriverFD = -1;
436 }
437
438 } // namespace android
439