blob: c5bb41e925f77e747aeb3672a45e7ae0a7025db3 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
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
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070019#include <binder/ProcessState.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020
Steven Moreland13a43c92021-08-30 13:21:48 -070021#include <android-base/result.h>
Steven Moreland281abad2022-02-24 22:06:40 +000022#include <android-base/strings.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070023#include <binder/BpBinder.h>
24#include <binder/IPCThreadState.h>
Steven Moreland2716e112018-02-23 14:57:20 -080025#include <binder/IServiceManager.h>
Steven Morelandc709dd82019-08-05 20:30:14 -070026#include <binder/Stability.h>
Steven Moreland2716e112018-02-23 14:57:20 -080027#include <cutils/atomic.h>
Andrei Homescu8028ff42022-03-14 22:11:54 +000028#include <utils/AndroidThreads.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080029#include <utils/Log.h>
30#include <utils/String8.h>
Andrei Homescu8028ff42022-03-14 22:11:54 +000031#include <utils/Thread.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
Steven Morelanda4853cd2019-07-12 15:44:37 -070033#include "Static.h"
Steven Moreland6ba5a252021-05-04 22:49:00 +000034#include "binder_module.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
36#include <errno.h>
37#include <fcntl.h>
Steven Moreland4fdb12f2020-07-21 02:21:48 +000038#include <mutex>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080039#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>
Philip Cuadraa082fa82016-04-08 10:29:14 -070045#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080046
Steven Moreland072cc7e2019-07-12 21:01:54 +000047#define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
Wale Ogunwale376b8222015-04-13 16:16:10 -070048#define DEFAULT_MAX_BINDER_THREADS 15
Hang Lub185ac02021-03-24 13:17:22 +080049#define DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION 1
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050
Martijn Coenen7bca77a2019-03-13 11:51:08 +000051#ifdef __ANDROID_VNDK__
52const char* kDefaultDriver = "/dev/vndbinder";
53#else
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070054const char* kDefaultDriver = "/dev/binder";
Martijn Coenen7bca77a2019-03-13 11:51:08 +000055#endif
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070056
Philip Cuadraa082fa82016-04-08 10:29:14 -070057// -------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
59namespace android {
Wale Ogunwale376b8222015-04-13 16:16:10 -070060
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061class PoolThread : public Thread
62{
63public:
Chih-Hung Hsiehe2347b72016-04-25 15:41:05 -070064 explicit PoolThread(bool isMain)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065 : mIsMain(isMain)
66 {
67 }
Jooyung Han1b228f42020-01-30 13:41:12 +090068
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080069protected:
70 virtual bool threadLoop()
71 {
72 IPCThreadState::self()->joinThreadPool(mIsMain);
73 return false;
74 }
Jooyung Han1b228f42020-01-30 13:41:12 +090075
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076 const bool mIsMain;
77};
78
79sp<ProcessState> ProcessState::self()
80{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000081 return init(kDefaultDriver, false /*requireDefault*/);
Martijn Coenen55d871c2017-03-21 15:56:40 -070082}
83
84sp<ProcessState> ProcessState::initWithDriver(const char* driver)
85{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000086 return init(driver, true /*requireDefault*/);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087}
88
Steven Moreland072cc7e2019-07-12 21:01:54 +000089sp<ProcessState> ProcessState::selfOrNull()
90{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000091 return init(nullptr, false /*requireDefault*/);
92}
93
Steven Morelandee9df902021-10-14 14:00:08 -070094[[clang::no_destroy]] static sp<ProcessState> gProcess;
95[[clang::no_destroy]] static std::mutex gProcessMutex;
96
97static void verifyNotForked(bool forked) {
Steven Morelandbd98e0f2021-10-14 14:24:15 -070098 LOG_ALWAYS_FATAL_IF(forked, "libbinder ProcessState can not be used after fork");
Steven Morelandee9df902021-10-14 14:00:08 -070099}
100
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000101sp<ProcessState> ProcessState::init(const char *driver, bool requireDefault)
102{
Steven Moreland49c39362022-05-13 20:10:24 +0000103#ifdef BINDER_IPC_32BIT
104 LOG_ALWAYS_FATAL("32-bit binder IPC is not supported for new devices starting in Android P. If "
105 "you do need to use this mode, please see b/232423610 or file an issue with "
106 "AOSP upstream as otherwise this will be removed soon.");
107#endif
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000108
109 if (driver == nullptr) {
110 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Morelandee9df902021-10-14 14:00:08 -0700111 if (gProcess) {
112 verifyNotForked(gProcess->mForked);
113 }
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000114 return gProcess;
115 }
116
117 [[clang::no_destroy]] static std::once_flag gProcessOnce;
118 std::call_once(gProcessOnce, [&](){
119 if (access(driver, R_OK) == -1) {
120 ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
121 driver = "/dev/binder";
122 }
123
Steven Morelandee9df902021-10-14 14:00:08 -0700124 // we must install these before instantiating the gProcess object,
125 // otherwise this would race with creating it, and there could be the
126 // possibility of an invalid gProcess object forked by another thread
127 // before these are installed
128 int ret = pthread_atfork(ProcessState::onFork, ProcessState::parentPostFork,
129 ProcessState::childPostFork);
130 LOG_ALWAYS_FATAL_IF(ret != 0, "pthread_atfork error %s", strerror(ret));
131
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000132 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000133 gProcess = sp<ProcessState>::make(driver);
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000134 });
135
136 if (requireDefault) {
137 // Detect if we are trying to initialize with a different driver, and
138 // consider that an error. ProcessState will only be initialized once above.
139 LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,
140 "ProcessState was already initialized with %s,"
141 " can't initialize with %s.",
142 gProcess->getDriverName().c_str(), driver);
143 }
144
Steven Morelandee9df902021-10-14 14:00:08 -0700145 verifyNotForked(gProcess->mForked);
Colin Cross9d45ccc2017-06-20 17:48:33 -0700146 return gProcess;
147}
148
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800149sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800150{
Steven Morelandc709dd82019-08-05 20:30:14 -0700151 sp<IBinder> context = getStrongProxyForHandle(0);
152
Steven Moreland4da8fb02020-12-29 22:51:32 +0000153 if (context) {
154 // The root object is special since we get it directly from the driver, it is never
155 // written by Parcell::writeStrongBinder.
156 internal::Stability::markCompilationUnit(context.get());
157 } else {
158 ALOGW("Not able to get context object on %s.", mDriverName.c_str());
Steven Moreland8d93a712020-02-19 15:16:15 -0800159 }
160
Steven Morelandc709dd82019-08-05 20:30:14 -0700161 return context;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162}
163
Steven Morelandee9df902021-10-14 14:00:08 -0700164void ProcessState::onFork() {
165 // make sure another thread isn't currently retrieving ProcessState
166 gProcessMutex.lock();
167}
168
169void ProcessState::parentPostFork() {
170 gProcessMutex.unlock();
171}
172
173void ProcessState::childPostFork() {
174 // another thread might call fork before gProcess is instantiated, but after
175 // the thread handler is installed
176 if (gProcess) {
177 gProcess->mForked = true;
178 }
179 gProcessMutex.unlock();
180}
181
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800182void ProcessState::startThreadPool()
183{
184 AutoMutex _l(mLock);
185 if (!mThreadPoolStarted) {
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000186 if (mMaxThreads == 0) {
187 ALOGW("Extra binder thread started, but 0 threads requested. Do not use "
188 "*startThreadPool when zero threads are requested.");
189 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800190 mThreadPoolStarted = true;
191 spawnPooledThread(true);
192 }
193}
194
Steven Moreland61096622020-08-31 23:36:39 +0000195bool ProcessState::becomeContextManager()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196{
Steven Moreland4411d712019-07-12 14:02:53 -0700197 AutoMutex _l(mLock);
Jeff Browne16986c2011-07-08 18:52:57 -0700198
Steven Moreland4411d712019-07-12 14:02:53 -0700199 flat_binder_object obj {
200 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
201 };
Steven Moreland3085a472018-12-26 13:59:23 -0800202
Steven Moreland4411d712019-07-12 14:02:53 -0700203 int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
Steven Moreland3085a472018-12-26 13:59:23 -0800204
Steven Moreland4411d712019-07-12 14:02:53 -0700205 // fallback to original method
206 if (result != 0) {
207 android_errorWriteLog(0x534e4554, "121035042");
Steven Moreland3085a472018-12-26 13:59:23 -0800208
Hungming Chen28b42522020-08-28 17:29:55 +0800209 int unused = 0;
210 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800211 }
Steven Moreland4411d712019-07-12 14:02:53 -0700212
213 if (result == -1) {
Steven Moreland4411d712019-07-12 14:02:53 -0700214 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
215 }
216
217 return result == 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800218}
219
Colin Cross9d45ccc2017-06-20 17:48:33 -0700220// Get references to userspace objects held by the kernel binder driver
221// Writes up to count elements into buf, and returns the total number
222// of references the kernel has, which may be larger than count.
223// buf may be NULL if count is 0. The pointers returned by this method
224// should only be used for debugging and not dereferenced, they may
225// already be invalid.
226ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
227{
Colin Cross9d45ccc2017-06-20 17:48:33 -0700228 binder_node_debug_info info = {};
229
Yi Kongfdd8da92018-06-07 17:52:27 -0700230 uintptr_t* end = buf ? buf + buf_count : nullptr;
Colin Cross9d45ccc2017-06-20 17:48:33 -0700231 size_t count = 0;
232
233 do {
234 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
235 if (result < 0) {
236 return -1;
237 }
238 if (info.ptr != 0) {
239 if (buf && buf < end)
240 *buf++ = info.ptr;
241 count++;
242 if (buf && buf < end)
243 *buf++ = info.cookie;
244 count++;
245 }
246 } while (info.ptr != 0);
247
248 return count;
249}
250
Jon Spivack902e6fc2019-10-18 21:22:37 -0700251// Queries the driver for the current strong reference count of the node
252// that the handle points to. Can only be used by the servicemanager.
253//
254// Returns -1 in case of failure, otherwise the strong reference count.
Steven Morelande8393882020-12-18 02:27:20 +0000255ssize_t ProcessState::getStrongRefCountForNode(const sp<BpBinder>& binder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000256 if (binder->isRpcBinder()) return -1;
257
Jon Spivack902e6fc2019-10-18 21:22:37 -0700258 binder_node_info_for_ref info;
259 memset(&info, 0, sizeof(binder_node_info_for_ref));
260
Steven Moreland99157622021-09-13 16:27:34 -0700261 info.handle = binder->getPrivateAccessor().binderHandle();
Jon Spivack902e6fc2019-10-18 21:22:37 -0700262
263 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
264
265 if (result != OK) {
266 static bool logged = false;
267 if (!logged) {
268 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
269 logged = true;
270 }
271 return -1;
272 }
273
274 return info.strong_count;
275}
276
Steven Moreland7732a092019-01-02 17:54:16 -0800277void ProcessState::setCallRestriction(CallRestriction restriction) {
Steven Moreland28723ae2019-04-01 18:52:30 -0700278 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
279 "Call restrictions must be set before the threadpool is started.");
Steven Moreland7732a092019-01-02 17:54:16 -0800280
281 mCallRestriction = restriction;
282}
283
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
285{
286 const size_t N=mHandleToObject.size();
287 if (N <= (size_t)handle) {
288 handle_entry e;
Yi Kongfdd8da92018-06-07 17:52:27 -0700289 e.binder = nullptr;
290 e.refs = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
Yi Kongfdd8da92018-06-07 17:52:27 -0700292 if (err < NO_ERROR) return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800293 }
294 return &mHandleToObject.editItemAt(handle);
295}
296
297sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
298{
299 sp<IBinder> result;
300
301 AutoMutex _l(mLock);
302
303 handle_entry* e = lookupHandleLocked(handle);
304
Yi Kongfdd8da92018-06-07 17:52:27 -0700305 if (e != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800306 // We need to create a new BpBinder if there isn't currently one, OR we
Steven Morelande171d622019-07-17 16:06:01 -0700307 // are unable to acquire a weak reference on this current one. The
308 // attemptIncWeak() is safe because we know the BpBinder destructor will always
309 // call expungeHandle(), which acquires the same lock we are holding now.
310 // We need to do this because there is a race condition between someone
311 // releasing a reference on this BpBinder, and a new reference on its handle
312 // arriving from the driver.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800313 IBinder* b = e->binder;
Yi Kongfdd8da92018-06-07 17:52:27 -0700314 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
Todd Poynora7b0f042013-06-18 17:25:37 -0700315 if (handle == 0) {
316 // Special case for context manager...
317 // The context manager is the only object for which we create
318 // a BpBinder proxy without already holding a reference.
319 // Perform a dummy transaction to ensure the context manager
320 // is registered before we create the first local reference
321 // to it (which will occur when creating the BpBinder).
322 // If a local reference is created for the BpBinder when the
323 // context manager is not present, the driver will fail to
324 // provide a reference to the context manager, but the
325 // driver API does not return status.
326 //
327 // Note that this is not race-free if the context manager
328 // dies while this code runs.
Todd Poynora7b0f042013-06-18 17:25:37 -0700329
Steven Moreland9514b202020-09-21 18:03:27 +0000330 IPCThreadState* ipc = IPCThreadState::self();
331
332 CallRestriction originalCallRestriction = ipc->getCallRestriction();
333 ipc->setCallRestriction(CallRestriction::NONE);
334
Todd Poynora7b0f042013-06-18 17:25:37 -0700335 Parcel data;
Steven Moreland9514b202020-09-21 18:03:27 +0000336 status_t status = ipc->transact(
Yi Kongfdd8da92018-06-07 17:52:27 -0700337 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
Steven Moreland9514b202020-09-21 18:03:27 +0000338
339 ipc->setCallRestriction(originalCallRestriction);
340
Todd Poynora7b0f042013-06-18 17:25:37 -0700341 if (status == DEAD_OBJECT)
Yi Kongfdd8da92018-06-07 17:52:27 -0700342 return nullptr;
Todd Poynora7b0f042013-06-18 17:25:37 -0700343 }
344
Steven Moreland99157622021-09-13 16:27:34 -0700345 sp<BpBinder> b = BpBinder::PrivateAccessor::create(handle);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000346 e->binder = b.get();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800347 if (b) e->refs = b->getWeakRefs();
348 result = b;
349 } else {
350 // This little bit of nastyness is to allow us to add a primary
351 // reference to the remote proxy when this team doesn't have one
352 // but another team is sending the handle to us.
353 result.force_set(b);
354 e->refs->decWeak(this);
355 }
356 }
357
358 return result;
359}
360
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800361void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
362{
363 AutoMutex _l(mLock);
Jooyung Han1b228f42020-01-30 13:41:12 +0900364
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800365 handle_entry* e = lookupHandleLocked(handle);
366
367 // This handle may have already been replaced with a new BpBinder
368 // (if someone failed the AttemptIncWeak() above); we don't want
369 // to overwrite it.
Yi Kongfdd8da92018-06-07 17:52:27 -0700370 if (e && e->binder == binder) e->binder = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800371}
372
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800373String8 ProcessState::makeBinderThreadName() {
374 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
Philip Cuadraa082fa82016-04-08 10:29:14 -0700375 pid_t pid = getpid();
Steven Moreland281abad2022-02-24 22:06:40 +0000376
377 std::string_view driverName = mDriverName.c_str();
378 android::base::ConsumePrefix(&driverName, "/dev/");
379
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800380 String8 name;
Steven Moreland281abad2022-02-24 22:06:40 +0000381 name.appendFormat("%.*s:%d_%X", static_cast<int>(driverName.length()), driverName.data(), pid,
382 s);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800383 return name;
384}
385
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800386void ProcessState::spawnPooledThread(bool isMain)
387{
388 if (mThreadPoolStarted) {
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800389 String8 name = makeBinderThreadName();
390 ALOGV("Spawning new pooled thread, name=%s\n", name.string());
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000391 sp<Thread> t = sp<PoolThread>::make(isMain);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800392 t->run(name.string());
Elie Kheirallah47431c12022-04-21 23:46:17 +0000393 mKernelStartedThreads++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800394 }
395}
396
Mathias Agopian1b80f792012-04-17 16:11:08 -0700397status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
Steven Moreland1fdb98b2020-03-06 21:42:12 +0000398 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
399 "Binder threadpool cannot be shrunk after starting");
Mathias Agopian1b80f792012-04-17 16:11:08 -0700400 status_t result = NO_ERROR;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700401 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
402 mMaxThreads = maxThreads;
403 } else {
Mathias Agopian1b80f792012-04-17 16:11:08 -0700404 result = -errno;
405 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
406 }
407 return result;
408}
409
Elie Kheirallah47431c12022-04-21 23:46:17 +0000410size_t ProcessState::getThreadPoolMaxTotalThreadCount() const {
Yifan Hong84bedeb2021-04-21 21:37:17 -0700411 // may actually be one more than this, if join is called
Elie Kheirallah47431c12022-04-21 23:46:17 +0000412 if (mThreadPoolStarted) {
413 return mCurrentThreads < mKernelStartedThreads
414 ? mMaxThreads
415 : mMaxThreads + mCurrentThreads - mKernelStartedThreads;
416 }
Yifan Hong84bedeb2021-04-21 21:37:17 -0700417 // must not be initialized or maybe has poll thread setup, we
418 // currently don't track this in libbinder
Elie Kheirallah47431c12022-04-21 23:46:17 +0000419 LOG_ALWAYS_FATAL_IF(mKernelStartedThreads != 0,
420 "Expecting 0 kernel started threads but have"
421 " %zu",
422 mKernelStartedThreads);
423 return mCurrentThreads;
Yifan Hong84bedeb2021-04-21 21:37:17 -0700424}
425
Carlos Llamas4f886702022-03-07 22:07:03 -0800426#define DRIVER_FEATURES_PATH "/dev/binderfs/features/"
427bool ProcessState::isDriverFeatureEnabled(const DriverFeature feature) {
428 static const char* const names[] = {
429 [static_cast<int>(DriverFeature::ONEWAY_SPAM_DETECTION)] =
430 DRIVER_FEATURES_PATH "oneway_spam_detection",
Carlos Llamasb235b122021-12-20 06:38:44 -0800431 [static_cast<int>(DriverFeature::EXTENDED_ERROR)] =
432 DRIVER_FEATURES_PATH "extended_error",
Carlos Llamas4f886702022-03-07 22:07:03 -0800433 };
434 int fd = open(names[static_cast<int>(feature)], O_RDONLY | O_CLOEXEC);
435 char on;
436 if (fd == -1) {
437 ALOGE_IF(errno != ENOENT, "%s: cannot open %s: %s", __func__,
438 names[static_cast<int>(feature)], strerror(errno));
439 return false;
440 }
441 if (read(fd, &on, sizeof(on)) == -1) {
442 ALOGE("%s: error reading to %s: %s", __func__,
443 names[static_cast<int>(feature)], strerror(errno));
444 return false;
445 }
446 close(fd);
447 return on == '1';
448}
449
Hang Lub185ac02021-03-24 13:17:22 +0800450status_t ProcessState::enableOnewaySpamDetection(bool enable) {
451 uint32_t enableDetection = enable ? 1 : 0;
452 if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
Martijn Coenende0a39e2021-04-22 14:38:46 +0200453 ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
Hang Lub185ac02021-03-24 13:17:22 +0800454 return -errno;
455 }
456 return NO_ERROR;
457}
458
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800459void ProcessState::giveThreadPoolName() {
460 androidSetThreadName( makeBinderThreadName().string() );
461}
462
Iliyan Malchev32062242017-04-10 14:06:11 -0700463String8 ProcessState::getDriverName() {
464 return mDriverName;
465}
466
Steven Moreland13a43c92021-08-30 13:21:48 -0700467static base::Result<int> open_driver(const char* driver) {
Martijn Coenen55d871c2017-03-21 15:56:40 -0700468 int fd = open(driver, O_RDWR | O_CLOEXEC);
Steven Moreland13a43c92021-08-30 13:21:48 -0700469 if (fd < 0) {
470 return base::ErrnoError() << "Opening '" << driver << "' failed";
471 }
472 int vers = 0;
473 status_t result = ioctl(fd, BINDER_VERSION, &vers);
474 if (result == -1) {
475 close(fd);
476 return base::ErrnoError() << "Binder ioctl to obtain version failed";
477 }
478 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
479 close(fd);
480 return base::Error() << "Binder driver protocol(" << vers
481 << ") does not match user space protocol("
482 << BINDER_CURRENT_PROTOCOL_VERSION
483 << ")! ioctl() return value: " << result;
484 }
485 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
486 result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
487 if (result == -1) {
488 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
489 }
490 uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
491 result = ioctl(fd, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
492 if (result == -1) {
Carlos Llamas4f886702022-03-07 22:07:03 -0800493 ALOGE_IF(ProcessState::isDriverFeatureEnabled(
494 ProcessState::DriverFeature::ONEWAY_SPAM_DETECTION),
495 "Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800496 }
497 return fd;
498}
499
Steven Moreland13a43c92021-08-30 13:21:48 -0700500ProcessState::ProcessState(const char* driver)
501 : mDriverName(String8(driver)),
502 mDriverFD(-1),
503 mVMStart(MAP_FAILED),
504 mThreadCountLock(PTHREAD_MUTEX_INITIALIZER),
505 mThreadCountDecrement(PTHREAD_COND_INITIALIZER),
506 mExecutingThreadsCount(0),
507 mWaitingForThreads(0),
508 mMaxThreads(DEFAULT_MAX_BINDER_THREADS),
Elie Kheirallah47431c12022-04-21 23:46:17 +0000509 mCurrentThreads(0),
510 mKernelStartedThreads(0),
Steven Moreland13a43c92021-08-30 13:21:48 -0700511 mStarvationStartTimeMs(0),
Steven Morelandee9df902021-10-14 14:00:08 -0700512 mForked(false),
Steven Moreland13a43c92021-08-30 13:21:48 -0700513 mThreadPoolStarted(false),
514 mThreadPoolSeq(1),
515 mCallRestriction(CallRestriction::NONE) {
516 base::Result<int> opened = open_driver(driver);
517
518 if (opened.ok()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800519 // mmap the binder, providing a chunk of virtual address space to receive transactions.
Steven Moreland13a43c92021-08-30 13:21:48 -0700520 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE,
521 opened.value(), 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800522 if (mVMStart == MAP_FAILED) {
Steven Moreland13a43c92021-08-30 13:21:48 -0700523 close(opened.value());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800524 // *sigh*
Steven Moreland13a43c92021-08-30 13:21:48 -0700525 opened = base::Error()
526 << "Using " << driver << " failed: unable to mmap transaction memory.";
Iliyan Malchev32062242017-04-10 14:06:11 -0700527 mDriverName.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800528 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800529 }
Jeff Browne16986c2011-07-08 18:52:57 -0700530
Steven Moreland24bc0d12019-10-11 12:29:20 -0700531#ifdef __ANDROID__
Steven Moreland13a43c92021-08-30 13:21:48 -0700532 LOG_ALWAYS_FATAL_IF(!opened.ok(), "Binder driver '%s' could not be opened. Terminating: %s",
533 driver, opened.error().message().c_str());
Steven Moreland24bc0d12019-10-11 12:29:20 -0700534#endif
Steven Moreland13a43c92021-08-30 13:21:48 -0700535
536 if (opened.ok()) {
537 mDriverFD = opened.value();
538 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800539}
540
541ProcessState::~ProcessState()
542{
zhongjieff405782016-03-09 15:05:04 +0800543 if (mDriverFD >= 0) {
544 if (mVMStart != MAP_FAILED) {
Steven Moreland072cc7e2019-07-12 21:01:54 +0000545 munmap(mVMStart, BINDER_VM_SIZE);
zhongjieff405782016-03-09 15:05:04 +0800546 }
547 close(mDriverFD);
548 }
549 mDriverFD = -1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800550}
Jooyung Han1b228f42020-01-30 13:41:12 +0900551
Steven Moreland61ff8492019-09-26 16:05:45 -0700552} // namespace android