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