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