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