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