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 <android-base/strings.h>
22 #include <binder/BpBinder.h>
23 #include <binder/Functional.h>
24 #include <binder/IPCThreadState.h>
25 #include <binder/IServiceManager.h>
26 #include <binder/Stability.h>
27 #include <cutils/atomic.h>
28 #include <utils/AndroidThreads.h>
29 #include <utils/Log.h>
30 #include <utils/String8.h>
31 #include <utils/Thread.h>
32
33 #include "Static.h"
34 #include "Utils.h"
35 #include "binder_module.h"
36
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <pthread.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <sys/ioctl.h>
43 #include <sys/mman.h>
44 #include <sys/stat.h>
45 #include <sys/types.h>
46 #include <unistd.h>
47 #include <mutex>
48
49 #define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
50 #define DEFAULT_MAX_BINDER_THREADS 15
51 #define DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION 1
52
53 #ifdef __ANDROID_VNDK__
54 const char* kDefaultDriver = "/dev/vndbinder";
55 #else
56 const char* kDefaultDriver = "/dev/binder";
57 #endif
58
59 // -------------------------------------------------------------------------
60
61 namespace android {
62
63 using namespace android::binder::impl;
64 using android::binder::unique_fd;
65
66 class PoolThread : public Thread
67 {
68 public:
PoolThread(bool isMain)69 explicit PoolThread(bool isMain)
70 : mIsMain(isMain)
71 {
72 }
73
74 protected:
threadLoop()75 virtual bool threadLoop()
76 {
77 IPCThreadState::self()->joinThreadPool(mIsMain);
78 return false;
79 }
80
81 const bool mIsMain;
82 };
83
self()84 sp<ProcessState> ProcessState::self()
85 {
86 return init(kDefaultDriver, false /*requireDefault*/);
87 }
88
initWithDriver(const char * driver)89 sp<ProcessState> ProcessState::initWithDriver(const char* driver)
90 {
91 return init(driver, true /*requireDefault*/);
92 }
93
selfOrNull()94 sp<ProcessState> ProcessState::selfOrNull()
95 {
96 return init(nullptr, false /*requireDefault*/);
97 }
98
99 [[clang::no_destroy]] static sp<ProcessState> gProcess;
100 [[clang::no_destroy]] static std::mutex gProcessMutex;
101
verifyNotForked(bool forked)102 static void verifyNotForked(bool forked) {
103 LOG_ALWAYS_FATAL_IF(forked, "libbinder ProcessState can not be used after fork");
104 }
105
isVndservicemanagerEnabled()106 bool ProcessState::isVndservicemanagerEnabled() {
107 return access("/vendor/bin/vndservicemanager", R_OK) == 0;
108 }
109
init(const char * driver,bool requireDefault)110 sp<ProcessState> ProcessState::init(const char* driver, bool requireDefault) {
111 if (driver == nullptr) {
112 std::lock_guard<std::mutex> l(gProcessMutex);
113 if (gProcess) {
114 verifyNotForked(gProcess->mForked);
115 }
116 return gProcess;
117 }
118
119 [[clang::no_destroy]] static std::once_flag gProcessOnce;
120 std::call_once(gProcessOnce, [&](){
121 if (access(driver, R_OK) == -1) {
122 ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
123 driver = "/dev/binder";
124 }
125
126 if (0 == strcmp(driver, "/dev/vndbinder") && !isVndservicemanagerEnabled()) {
127 ALOGE("vndservicemanager is not started on this device, you can save resources/threads "
128 "by not initializing ProcessState with /dev/vndbinder.");
129 }
130
131 // we must install these before instantiating the gProcess object,
132 // otherwise this would race with creating it, and there could be the
133 // possibility of an invalid gProcess object forked by another thread
134 // before these are installed
135 int ret = pthread_atfork(ProcessState::onFork, ProcessState::parentPostFork,
136 ProcessState::childPostFork);
137 LOG_ALWAYS_FATAL_IF(ret != 0, "pthread_atfork error %s", strerror(ret));
138
139 std::lock_guard<std::mutex> l(gProcessMutex);
140 gProcess = sp<ProcessState>::make(driver);
141 });
142
143 if (requireDefault) {
144 // Detect if we are trying to initialize with a different driver, and
145 // consider that an error. ProcessState will only be initialized once above.
146 LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,
147 "ProcessState was already initialized with %s,"
148 " can't initialize with %s.",
149 gProcess->getDriverName().c_str(), driver);
150 }
151
152 verifyNotForked(gProcess->mForked);
153 return gProcess;
154 }
155
getContextObject(const sp<IBinder> &)156 sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
157 {
158 sp<IBinder> context = getStrongProxyForHandle(0);
159
160 if (context) {
161 // The root object is special since we get it directly from the driver, it is never
162 // written by Parcell::writeStrongBinder.
163 internal::Stability::markCompilationUnit(context.get());
164 } else {
165 ALOGW("Not able to get context object on %s.", mDriverName.c_str());
166 }
167
168 return context;
169 }
170
onFork()171 void ProcessState::onFork() {
172 // make sure another thread isn't currently retrieving ProcessState
173 gProcessMutex.lock();
174 }
175
parentPostFork()176 void ProcessState::parentPostFork() {
177 gProcessMutex.unlock();
178 }
179
childPostFork()180 void ProcessState::childPostFork() {
181 // another thread might call fork before gProcess is instantiated, but after
182 // the thread handler is installed
183 if (gProcess) {
184 gProcess->mForked = true;
185
186 // "O_CLOFORK"
187 close(gProcess->mDriverFD);
188 gProcess->mDriverFD = -1;
189 }
190 gProcessMutex.unlock();
191 }
192
startThreadPool()193 void ProcessState::startThreadPool()
194 {
195 std::unique_lock<std::mutex> _l(mLock);
196 if (!mThreadPoolStarted) {
197 if (mMaxThreads == 0) {
198 // see also getThreadPoolMaxTotalThreadCount
199 ALOGW("Extra binder thread started, but 0 threads requested. Do not use "
200 "*startThreadPool when zero threads are requested.");
201 }
202 mThreadPoolStarted = true;
203 spawnPooledThread(true);
204 }
205 }
206
becomeContextManager()207 bool ProcessState::becomeContextManager()
208 {
209 std::unique_lock<std::mutex> _l(mLock);
210
211 flat_binder_object obj {
212 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
213 };
214
215 int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
216
217 // fallback to original method
218 if (result != 0) {
219 android_errorWriteLog(0x534e4554, "121035042");
220
221 int unused = 0;
222 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
223 }
224
225 if (result == -1) {
226 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
227 }
228
229 return result == 0;
230 }
231
232 // Get references to userspace objects held by the kernel binder driver
233 // Writes up to count elements into buf, and returns the total number
234 // of references the kernel has, which may be larger than count.
235 // buf may be NULL if count is 0. The pointers returned by this method
236 // should only be used for debugging and not dereferenced, they may
237 // already be invalid.
getKernelReferences(size_t buf_count,uintptr_t * buf)238 ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
239 {
240 binder_node_debug_info info = {};
241
242 uintptr_t* end = buf ? buf + buf_count : nullptr;
243 size_t count = 0;
244
245 do {
246 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
247 if (result < 0) {
248 return -1;
249 }
250 if (info.ptr != 0) {
251 if (buf && buf < end)
252 *buf++ = info.ptr;
253 count++;
254 if (buf && buf < end)
255 *buf++ = info.cookie;
256 count++;
257 }
258 } while (info.ptr != 0);
259
260 return count;
261 }
262
263 // Queries the driver for the current strong reference count of the node
264 // that the handle points to. Can only be used by the servicemanager.
265 //
266 // Returns -1 in case of failure, otherwise the strong reference count.
getStrongRefCountForNode(const sp<BpBinder> & binder)267 ssize_t ProcessState::getStrongRefCountForNode(const sp<BpBinder>& binder) {
268 if (binder->isRpcBinder()) return -1;
269
270 binder_node_info_for_ref info;
271 memset(&info, 0, sizeof(binder_node_info_for_ref));
272
273 info.handle = binder->getPrivateAccessor().binderHandle();
274
275 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
276
277 if (result != OK) {
278 static bool logged = false;
279 if (!logged) {
280 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
281 logged = true;
282 }
283 return -1;
284 }
285
286 return info.strong_count;
287 }
288
setCallRestriction(CallRestriction restriction)289 void ProcessState::setCallRestriction(CallRestriction restriction) {
290 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
291 "Call restrictions must be set before the threadpool is started.");
292
293 mCallRestriction = restriction;
294 }
295
lookupHandleLocked(int32_t handle)296 ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
297 {
298 const size_t N=mHandleToObject.size();
299 if (N <= (size_t)handle) {
300 handle_entry e;
301 e.binder = nullptr;
302 e.refs = nullptr;
303 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
304 if (err < NO_ERROR) return nullptr;
305 }
306 return &mHandleToObject.editItemAt(handle);
307 }
308
309 // see b/166779391: cannot change the VNDK interface, so access like this
310 extern sp<BBinder> the_context_object;
311
getStrongProxyForHandle(int32_t handle)312 sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
313 {
314 sp<IBinder> result;
315
316 std::unique_lock<std::mutex> _l(mLock);
317
318 if (handle == 0 && the_context_object != nullptr) return the_context_object;
319
320 handle_entry* e = lookupHandleLocked(handle);
321
322 if (e != nullptr) {
323 // We need to create a new BpBinder if there isn't currently one, OR we
324 // are unable to acquire a weak reference on this current one. The
325 // attemptIncWeak() is safe because we know the BpBinder destructor will always
326 // call expungeHandle(), which acquires the same lock we are holding now.
327 // We need to do this because there is a race condition between someone
328 // releasing a reference on this BpBinder, and a new reference on its handle
329 // arriving from the driver.
330 IBinder* b = e->binder;
331 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
332 if (handle == 0) {
333 // Special case for context manager...
334 // The context manager is the only object for which we create
335 // a BpBinder proxy without already holding a reference.
336 // Perform a dummy transaction to ensure the context manager
337 // is registered before we create the first local reference
338 // to it (which will occur when creating the BpBinder).
339 // If a local reference is created for the BpBinder when the
340 // context manager is not present, the driver will fail to
341 // provide a reference to the context manager, but the
342 // driver API does not return status.
343 //
344 // Note that this is not race-free if the context manager
345 // dies while this code runs.
346
347 IPCThreadState* ipc = IPCThreadState::self();
348
349 CallRestriction originalCallRestriction = ipc->getCallRestriction();
350 ipc->setCallRestriction(CallRestriction::NONE);
351
352 Parcel data;
353 status_t status = ipc->transact(
354 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
355
356 ipc->setCallRestriction(originalCallRestriction);
357
358 if (status == DEAD_OBJECT)
359 return nullptr;
360 }
361
362 sp<BpBinder> b = BpBinder::PrivateAccessor::create(handle);
363 e->binder = b.get();
364 if (b) e->refs = b->getWeakRefs();
365 result = b;
366 } else {
367 // This little bit of nastyness is to allow us to add a primary
368 // reference to the remote proxy when this team doesn't have one
369 // but another team is sending the handle to us.
370 result.force_set(b);
371 e->refs->decWeak(this);
372 }
373 }
374
375 return result;
376 }
377
expungeHandle(int32_t handle,IBinder * binder)378 void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
379 {
380 std::unique_lock<std::mutex> _l(mLock);
381
382 handle_entry* e = lookupHandleLocked(handle);
383
384 // This handle may have already been replaced with a new BpBinder
385 // (if someone failed the AttemptIncWeak() above); we don't want
386 // to overwrite it.
387 if (e && e->binder == binder) e->binder = nullptr;
388 }
389
makeBinderThreadName()390 String8 ProcessState::makeBinderThreadName() {
391 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
392 pid_t pid = getpid();
393
394 std::string_view driverName = mDriverName.c_str();
395 android::base::ConsumePrefix(&driverName, "/dev/");
396
397 String8 name;
398 name.appendFormat("%.*s:%d_%X", static_cast<int>(driverName.length()), driverName.data(), pid,
399 s);
400 return name;
401 }
402
spawnPooledThread(bool isMain)403 void ProcessState::spawnPooledThread(bool isMain)
404 {
405 if (mThreadPoolStarted) {
406 String8 name = makeBinderThreadName();
407 ALOGV("Spawning new pooled thread, name=%s\n", name.c_str());
408 sp<Thread> t = sp<PoolThread>::make(isMain);
409 t->run(name.c_str());
410 pthread_mutex_lock(&mThreadCountLock);
411 mKernelStartedThreads++;
412 pthread_mutex_unlock(&mThreadCountLock);
413 }
414 // TODO: if startThreadPool is called on another thread after the process
415 // starts up, the kernel might think that it already requested those
416 // binder threads, and additional won't be started. This is likely to
417 // cause deadlocks, and it will also cause getThreadPoolMaxTotalThreadCount
418 // to return too high of a value.
419 }
420
setThreadPoolMaxThreadCount(size_t maxThreads)421 status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
422 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
423 "Binder threadpool cannot be shrunk after starting");
424 status_t result = NO_ERROR;
425 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
426 mMaxThreads = maxThreads;
427 } else {
428 result = -errno;
429 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
430 }
431 return result;
432 }
433
getThreadPoolMaxTotalThreadCount() const434 size_t ProcessState::getThreadPoolMaxTotalThreadCount() const {
435 pthread_mutex_lock(&mThreadCountLock);
436 auto detachGuard = make_scope_guard([&]() { pthread_mutex_unlock(&mThreadCountLock); });
437
438 if (mThreadPoolStarted) {
439 LOG_ALWAYS_FATAL_IF(mKernelStartedThreads > mMaxThreads + 1,
440 "too many kernel-started threads: %zu > %zu + 1", mKernelStartedThreads,
441 mMaxThreads);
442
443 // calling startThreadPool starts a thread
444 size_t threads = 1;
445
446 // the kernel is configured to start up to mMaxThreads more threads
447 threads += mMaxThreads;
448
449 // Users may call IPCThreadState::joinThreadPool directly. We don't
450 // currently have a way to count this directly (it could be added by
451 // adding a separate private joinKernelThread method in IPCThreadState).
452 // So, if we are in a race between the kernel thread variable being
453 // incremented in this file and mCurrentThreads being incremented
454 // in IPCThreadState, temporarily forget about the extra join threads.
455 // This is okay, because most callers of this method only care about
456 // having 0, 1, or more threads.
457 if (mCurrentThreads > mKernelStartedThreads) {
458 threads += mCurrentThreads - mKernelStartedThreads;
459 }
460
461 return threads;
462 }
463
464 // must not be initialized or maybe has poll thread setup, we
465 // currently don't track this in libbinder
466 LOG_ALWAYS_FATAL_IF(mKernelStartedThreads != 0,
467 "Expecting 0 kernel started threads but have"
468 " %zu",
469 mKernelStartedThreads);
470 return mCurrentThreads;
471 }
472
isThreadPoolStarted() const473 bool ProcessState::isThreadPoolStarted() const {
474 return mThreadPoolStarted;
475 }
476
477 #define DRIVER_FEATURES_PATH "/dev/binderfs/features/"
isDriverFeatureEnabled(const DriverFeature feature)478 bool ProcessState::isDriverFeatureEnabled(const DriverFeature feature) {
479 static const char* const names[] = {
480 [static_cast<int>(DriverFeature::ONEWAY_SPAM_DETECTION)] =
481 DRIVER_FEATURES_PATH "oneway_spam_detection",
482 [static_cast<int>(DriverFeature::EXTENDED_ERROR)] =
483 DRIVER_FEATURES_PATH "extended_error",
484 };
485 int fd = open(names[static_cast<int>(feature)], O_RDONLY | O_CLOEXEC);
486 char on;
487 if (fd == -1) {
488 ALOGE_IF(errno != ENOENT, "%s: cannot open %s: %s", __func__,
489 names[static_cast<int>(feature)], strerror(errno));
490 return false;
491 }
492 if (read(fd, &on, sizeof(on)) == -1) {
493 ALOGE("%s: error reading to %s: %s", __func__,
494 names[static_cast<int>(feature)], strerror(errno));
495 close(fd);
496 return false;
497 }
498 close(fd);
499 return on == '1';
500 }
501
enableOnewaySpamDetection(bool enable)502 status_t ProcessState::enableOnewaySpamDetection(bool enable) {
503 uint32_t enableDetection = enable ? 1 : 0;
504 if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
505 ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
506 return -errno;
507 }
508 return NO_ERROR;
509 }
510
giveThreadPoolName()511 void ProcessState::giveThreadPoolName() {
512 androidSetThreadName(makeBinderThreadName().c_str());
513 }
514
getDriverName()515 String8 ProcessState::getDriverName() {
516 return mDriverName;
517 }
518
open_driver(const char * driver,String8 * error)519 static unique_fd open_driver(const char* driver, String8* error) {
520 auto fd = unique_fd(open(driver, O_RDWR | O_CLOEXEC));
521 if (!fd.ok()) {
522 error->appendFormat("%d (%s) Opening '%s' failed", errno, strerror(errno), driver);
523 return {};
524 }
525 int vers = 0;
526 int result = ioctl(fd.get(), BINDER_VERSION, &vers);
527 if (result == -1) {
528 error->appendFormat("%d (%s) Binder ioctl to obtain version failed", errno,
529 strerror(errno));
530 return {};
531 }
532 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
533 error->appendFormat("Binder driver protocol(%d) does not match user space protocol(%d)! "
534 "ioctl() return value: %d",
535 vers, BINDER_CURRENT_PROTOCOL_VERSION, result);
536 return {};
537 }
538 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
539 result = ioctl(fd.get(), BINDER_SET_MAX_THREADS, &maxThreads);
540 if (result == -1) {
541 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
542 }
543 uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
544 result = ioctl(fd.get(), BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
545 if (result == -1) {
546 ALOGE_IF(ProcessState::isDriverFeatureEnabled(
547 ProcessState::DriverFeature::ONEWAY_SPAM_DETECTION),
548 "Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
549 }
550 return fd;
551 }
552
ProcessState(const char * driver)553 ProcessState::ProcessState(const char* driver)
554 : mDriverName(String8(driver)),
555 mDriverFD(-1),
556 mVMStart(MAP_FAILED),
557 mThreadCountLock(PTHREAD_MUTEX_INITIALIZER),
558 mThreadCountDecrement(PTHREAD_COND_INITIALIZER),
559 mExecutingThreadsCount(0),
560 mWaitingForThreads(0),
561 mMaxThreads(DEFAULT_MAX_BINDER_THREADS),
562 mCurrentThreads(0),
563 mKernelStartedThreads(0),
564 mStarvationStartTimeMs(0),
565 mForked(false),
566 mThreadPoolStarted(false),
567 mThreadPoolSeq(1),
568 mCallRestriction(CallRestriction::NONE) {
569 String8 error;
570 unique_fd opened = open_driver(driver, &error);
571
572 if (opened.ok()) {
573 // mmap the binder, providing a chunk of virtual address space to receive transactions.
574 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE,
575 opened.get(), 0);
576 if (mVMStart == MAP_FAILED) {
577 // *sigh*
578 ALOGE("Using %s failed: unable to mmap transaction memory.", driver);
579 opened.reset();
580 mDriverName.clear();
581 }
582 }
583
584 #ifdef __ANDROID__
585 LOG_ALWAYS_FATAL_IF(!opened.ok(),
586 "Binder driver '%s' could not be opened. Error: %s. Terminating.",
587 error.c_str(), driver);
588 #endif
589
590 if (opened.ok()) {
591 mDriverFD = opened.release();
592 }
593 }
594
~ProcessState()595 ProcessState::~ProcessState()
596 {
597 if (mDriverFD >= 0) {
598 if (mVMStart != MAP_FAILED) {
599 munmap(mVMStart, BINDER_VM_SIZE);
600 }
601 close(mDriverFD);
602 }
603 mDriverFD = -1;
604 }
605
606 } // namespace android
607