blob: 7faff476274aceda3d1ac272c645c8b8e170ae7b [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>
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +000038#include <pthread.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080039#include <stdio.h>
40#include <stdlib.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080041#include <sys/ioctl.h>
42#include <sys/mman.h>
43#include <sys/stat.h>
Philip Cuadraa082fa82016-04-08 10:29:14 -070044#include <sys/types.h>
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +000045#include <unistd.h>
46#include <mutex>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080047
Steven Moreland072cc7e2019-07-12 21:01:54 +000048#define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
Wale Ogunwale376b8222015-04-13 16:16:10 -070049#define DEFAULT_MAX_BINDER_THREADS 15
Hang Lub185ac02021-03-24 13:17:22 +080050#define DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION 1
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080051
Martijn Coenen7bca77a2019-03-13 11:51:08 +000052#ifdef __ANDROID_VNDK__
53const char* kDefaultDriver = "/dev/vndbinder";
54#else
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070055const char* kDefaultDriver = "/dev/binder";
Martijn Coenen7bca77a2019-03-13 11:51:08 +000056#endif
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070057
Philip Cuadraa082fa82016-04-08 10:29:14 -070058// -------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
60namespace android {
Wale Ogunwale376b8222015-04-13 16:16:10 -070061
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062class PoolThread : public Thread
63{
64public:
Chih-Hung Hsiehe2347b72016-04-25 15:41:05 -070065 explicit PoolThread(bool isMain)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066 : mIsMain(isMain)
67 {
68 }
Jooyung Han1b228f42020-01-30 13:41:12 +090069
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070protected:
71 virtual bool threadLoop()
72 {
73 IPCThreadState::self()->joinThreadPool(mIsMain);
74 return false;
75 }
Jooyung Han1b228f42020-01-30 13:41:12 +090076
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077 const bool mIsMain;
78};
79
80sp<ProcessState> ProcessState::self()
81{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000082 return init(kDefaultDriver, false /*requireDefault*/);
Martijn Coenen55d871c2017-03-21 15:56:40 -070083}
84
85sp<ProcessState> ProcessState::initWithDriver(const char* driver)
86{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000087 return init(driver, true /*requireDefault*/);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088}
89
Steven Moreland072cc7e2019-07-12 21:01:54 +000090sp<ProcessState> ProcessState::selfOrNull()
91{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000092 return init(nullptr, false /*requireDefault*/);
93}
94
Steven Morelandee9df902021-10-14 14:00:08 -070095[[clang::no_destroy]] static sp<ProcessState> gProcess;
96[[clang::no_destroy]] static std::mutex gProcessMutex;
97
98static void verifyNotForked(bool forked) {
Steven Morelandbd98e0f2021-10-14 14:24:15 -070099 LOG_ALWAYS_FATAL_IF(forked, "libbinder ProcessState can not be used after fork");
Steven Morelandee9df902021-10-14 14:00:08 -0700100}
101
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000102sp<ProcessState> ProcessState::init(const char *driver, bool requireDefault)
103{
Steven Moreland49c39362022-05-13 20:10:24 +0000104#ifdef BINDER_IPC_32BIT
105 LOG_ALWAYS_FATAL("32-bit binder IPC is not supported for new devices starting in Android P. If "
106 "you do need to use this mode, please see b/232423610 or file an issue with "
107 "AOSP upstream as otherwise this will be removed soon.");
108#endif
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000109
110 if (driver == nullptr) {
111 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Morelandee9df902021-10-14 14:00:08 -0700112 if (gProcess) {
113 verifyNotForked(gProcess->mForked);
114 }
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000115 return gProcess;
116 }
117
118 [[clang::no_destroy]] static std::once_flag gProcessOnce;
119 std::call_once(gProcessOnce, [&](){
120 if (access(driver, R_OK) == -1) {
121 ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
122 driver = "/dev/binder";
123 }
124
Steven Morelandee9df902021-10-14 14:00:08 -0700125 // we must install these before instantiating the gProcess object,
126 // otherwise this would race with creating it, and there could be the
127 // possibility of an invalid gProcess object forked by another thread
128 // before these are installed
129 int ret = pthread_atfork(ProcessState::onFork, ProcessState::parentPostFork,
130 ProcessState::childPostFork);
131 LOG_ALWAYS_FATAL_IF(ret != 0, "pthread_atfork error %s", strerror(ret));
132
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000133 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000134 gProcess = sp<ProcessState>::make(driver);
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000135 });
136
137 if (requireDefault) {
138 // Detect if we are trying to initialize with a different driver, and
139 // consider that an error. ProcessState will only be initialized once above.
140 LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,
141 "ProcessState was already initialized with %s,"
142 " can't initialize with %s.",
143 gProcess->getDriverName().c_str(), driver);
144 }
145
Steven Morelandee9df902021-10-14 14:00:08 -0700146 verifyNotForked(gProcess->mForked);
Colin Cross9d45ccc2017-06-20 17:48:33 -0700147 return gProcess;
148}
149
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800150sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800151{
Steven Morelandc709dd82019-08-05 20:30:14 -0700152 sp<IBinder> context = getStrongProxyForHandle(0);
153
Steven Moreland4da8fb02020-12-29 22:51:32 +0000154 if (context) {
155 // The root object is special since we get it directly from the driver, it is never
156 // written by Parcell::writeStrongBinder.
157 internal::Stability::markCompilationUnit(context.get());
158 } else {
159 ALOGW("Not able to get context object on %s.", mDriverName.c_str());
Steven Moreland8d93a712020-02-19 15:16:15 -0800160 }
161
Steven Morelandc709dd82019-08-05 20:30:14 -0700162 return context;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163}
164
Steven Morelandee9df902021-10-14 14:00:08 -0700165void ProcessState::onFork() {
166 // make sure another thread isn't currently retrieving ProcessState
167 gProcessMutex.lock();
168}
169
170void ProcessState::parentPostFork() {
171 gProcessMutex.unlock();
172}
173
174void ProcessState::childPostFork() {
175 // another thread might call fork before gProcess is instantiated, but after
176 // the thread handler is installed
177 if (gProcess) {
178 gProcess->mForked = true;
Steven Morelanddf732ba2022-05-18 22:04:49 +0000179
180 // "O_CLOFORK"
181 close(gProcess->mDriverFD);
182 gProcess->mDriverFD = -1;
Steven Morelandee9df902021-10-14 14:00:08 -0700183 }
184 gProcessMutex.unlock();
185}
186
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800187void ProcessState::startThreadPool()
188{
189 AutoMutex _l(mLock);
190 if (!mThreadPoolStarted) {
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000191 if (mMaxThreads == 0) {
192 ALOGW("Extra binder thread started, but 0 threads requested. Do not use "
193 "*startThreadPool when zero threads are requested.");
194 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195 mThreadPoolStarted = true;
196 spawnPooledThread(true);
197 }
198}
199
Steven Moreland61096622020-08-31 23:36:39 +0000200bool ProcessState::becomeContextManager()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201{
Steven Moreland4411d712019-07-12 14:02:53 -0700202 AutoMutex _l(mLock);
Jeff Browne16986c2011-07-08 18:52:57 -0700203
Steven Moreland4411d712019-07-12 14:02:53 -0700204 flat_binder_object obj {
205 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
206 };
Steven Moreland3085a472018-12-26 13:59:23 -0800207
Steven Moreland4411d712019-07-12 14:02:53 -0700208 int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
Steven Moreland3085a472018-12-26 13:59:23 -0800209
Steven Moreland4411d712019-07-12 14:02:53 -0700210 // fallback to original method
211 if (result != 0) {
212 android_errorWriteLog(0x534e4554, "121035042");
Steven Moreland3085a472018-12-26 13:59:23 -0800213
Hungming Chen28b42522020-08-28 17:29:55 +0800214 int unused = 0;
215 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800216 }
Steven Moreland4411d712019-07-12 14:02:53 -0700217
218 if (result == -1) {
Steven Moreland4411d712019-07-12 14:02:53 -0700219 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
220 }
221
222 return result == 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223}
224
Colin Cross9d45ccc2017-06-20 17:48:33 -0700225// Get references to userspace objects held by the kernel binder driver
226// Writes up to count elements into buf, and returns the total number
227// of references the kernel has, which may be larger than count.
228// buf may be NULL if count is 0. The pointers returned by this method
229// should only be used for debugging and not dereferenced, they may
230// already be invalid.
231ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
232{
Colin Cross9d45ccc2017-06-20 17:48:33 -0700233 binder_node_debug_info info = {};
234
Yi Kongfdd8da92018-06-07 17:52:27 -0700235 uintptr_t* end = buf ? buf + buf_count : nullptr;
Colin Cross9d45ccc2017-06-20 17:48:33 -0700236 size_t count = 0;
237
238 do {
239 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
240 if (result < 0) {
241 return -1;
242 }
243 if (info.ptr != 0) {
244 if (buf && buf < end)
245 *buf++ = info.ptr;
246 count++;
247 if (buf && buf < end)
248 *buf++ = info.cookie;
249 count++;
250 }
251 } while (info.ptr != 0);
252
253 return count;
254}
255
Jon Spivack902e6fc2019-10-18 21:22:37 -0700256// Queries the driver for the current strong reference count of the node
257// that the handle points to. Can only be used by the servicemanager.
258//
259// Returns -1 in case of failure, otherwise the strong reference count.
Steven Morelande8393882020-12-18 02:27:20 +0000260ssize_t ProcessState::getStrongRefCountForNode(const sp<BpBinder>& binder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000261 if (binder->isRpcBinder()) return -1;
262
Jon Spivack902e6fc2019-10-18 21:22:37 -0700263 binder_node_info_for_ref info;
264 memset(&info, 0, sizeof(binder_node_info_for_ref));
265
Steven Moreland99157622021-09-13 16:27:34 -0700266 info.handle = binder->getPrivateAccessor().binderHandle();
Jon Spivack902e6fc2019-10-18 21:22:37 -0700267
268 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
269
270 if (result != OK) {
271 static bool logged = false;
272 if (!logged) {
273 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
274 logged = true;
275 }
276 return -1;
277 }
278
279 return info.strong_count;
280}
281
Steven Moreland7732a092019-01-02 17:54:16 -0800282void ProcessState::setCallRestriction(CallRestriction restriction) {
Steven Moreland28723ae2019-04-01 18:52:30 -0700283 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
284 "Call restrictions must be set before the threadpool is started.");
Steven Moreland7732a092019-01-02 17:54:16 -0800285
286 mCallRestriction = restriction;
287}
288
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800289ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
290{
291 const size_t N=mHandleToObject.size();
292 if (N <= (size_t)handle) {
293 handle_entry e;
Yi Kongfdd8da92018-06-07 17:52:27 -0700294 e.binder = nullptr;
295 e.refs = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800296 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
Yi Kongfdd8da92018-06-07 17:52:27 -0700297 if (err < NO_ERROR) return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800298 }
299 return &mHandleToObject.editItemAt(handle);
300}
301
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000302// see b/166779391: cannot change the VNDK interface, so access like this
303extern sp<BBinder> the_context_object;
304
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
306{
307 sp<IBinder> result;
308
309 AutoMutex _l(mLock);
310
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000311 if (handle == 0 && the_context_object != nullptr) return the_context_object;
312
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800313 handle_entry* e = lookupHandleLocked(handle);
314
Yi Kongfdd8da92018-06-07 17:52:27 -0700315 if (e != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800316 // We need to create a new BpBinder if there isn't currently one, OR we
Steven Morelande171d622019-07-17 16:06:01 -0700317 // are unable to acquire a weak reference on this current one. The
318 // attemptIncWeak() is safe because we know the BpBinder destructor will always
319 // call expungeHandle(), which acquires the same lock we are holding now.
320 // We need to do this because there is a race condition between someone
321 // releasing a reference on this BpBinder, and a new reference on its handle
322 // arriving from the driver.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800323 IBinder* b = e->binder;
Yi Kongfdd8da92018-06-07 17:52:27 -0700324 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
Todd Poynora7b0f042013-06-18 17:25:37 -0700325 if (handle == 0) {
326 // Special case for context manager...
327 // The context manager is the only object for which we create
328 // a BpBinder proxy without already holding a reference.
329 // Perform a dummy transaction to ensure the context manager
330 // is registered before we create the first local reference
331 // to it (which will occur when creating the BpBinder).
332 // If a local reference is created for the BpBinder when the
333 // context manager is not present, the driver will fail to
334 // provide a reference to the context manager, but the
335 // driver API does not return status.
336 //
337 // Note that this is not race-free if the context manager
338 // dies while this code runs.
Todd Poynora7b0f042013-06-18 17:25:37 -0700339
Steven Moreland9514b202020-09-21 18:03:27 +0000340 IPCThreadState* ipc = IPCThreadState::self();
341
342 CallRestriction originalCallRestriction = ipc->getCallRestriction();
343 ipc->setCallRestriction(CallRestriction::NONE);
344
Todd Poynora7b0f042013-06-18 17:25:37 -0700345 Parcel data;
Steven Moreland9514b202020-09-21 18:03:27 +0000346 status_t status = ipc->transact(
Yi Kongfdd8da92018-06-07 17:52:27 -0700347 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
Steven Moreland9514b202020-09-21 18:03:27 +0000348
349 ipc->setCallRestriction(originalCallRestriction);
350
Todd Poynora7b0f042013-06-18 17:25:37 -0700351 if (status == DEAD_OBJECT)
Yi Kongfdd8da92018-06-07 17:52:27 -0700352 return nullptr;
Todd Poynora7b0f042013-06-18 17:25:37 -0700353 }
354
Steven Moreland99157622021-09-13 16:27:34 -0700355 sp<BpBinder> b = BpBinder::PrivateAccessor::create(handle);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000356 e->binder = b.get();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800357 if (b) e->refs = b->getWeakRefs();
358 result = b;
359 } else {
360 // This little bit of nastyness is to allow us to add a primary
361 // reference to the remote proxy when this team doesn't have one
362 // but another team is sending the handle to us.
363 result.force_set(b);
364 e->refs->decWeak(this);
365 }
366 }
367
368 return result;
369}
370
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800371void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
372{
373 AutoMutex _l(mLock);
Jooyung Han1b228f42020-01-30 13:41:12 +0900374
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800375 handle_entry* e = lookupHandleLocked(handle);
376
377 // This handle may have already been replaced with a new BpBinder
378 // (if someone failed the AttemptIncWeak() above); we don't want
379 // to overwrite it.
Yi Kongfdd8da92018-06-07 17:52:27 -0700380 if (e && e->binder == binder) e->binder = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381}
382
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800383String8 ProcessState::makeBinderThreadName() {
384 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
Philip Cuadraa082fa82016-04-08 10:29:14 -0700385 pid_t pid = getpid();
Steven Moreland281abad2022-02-24 22:06:40 +0000386
387 std::string_view driverName = mDriverName.c_str();
388 android::base::ConsumePrefix(&driverName, "/dev/");
389
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800390 String8 name;
Steven Moreland281abad2022-02-24 22:06:40 +0000391 name.appendFormat("%.*s:%d_%X", static_cast<int>(driverName.length()), driverName.data(), pid,
392 s);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800393 return name;
394}
395
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800396void ProcessState::spawnPooledThread(bool isMain)
397{
398 if (mThreadPoolStarted) {
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800399 String8 name = makeBinderThreadName();
400 ALOGV("Spawning new pooled thread, name=%s\n", name.string());
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000401 sp<Thread> t = sp<PoolThread>::make(isMain);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800402 t->run(name.string());
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +0000403 pthread_mutex_lock(&mThreadCountLock);
Elie Kheirallah47431c12022-04-21 23:46:17 +0000404 mKernelStartedThreads++;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +0000405 pthread_mutex_unlock(&mThreadCountLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800406 }
407}
408
Mathias Agopian1b80f792012-04-17 16:11:08 -0700409status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
Steven Moreland1fdb98b2020-03-06 21:42:12 +0000410 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
411 "Binder threadpool cannot be shrunk after starting");
Mathias Agopian1b80f792012-04-17 16:11:08 -0700412 status_t result = NO_ERROR;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700413 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
414 mMaxThreads = maxThreads;
415 } else {
Mathias Agopian1b80f792012-04-17 16:11:08 -0700416 result = -errno;
417 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
418 }
419 return result;
420}
421
Elie Kheirallah47431c12022-04-21 23:46:17 +0000422size_t ProcessState::getThreadPoolMaxTotalThreadCount() const {
Yifan Hong84bedeb2021-04-21 21:37:17 -0700423 // may actually be one more than this, if join is called
Elie Kheirallah47431c12022-04-21 23:46:17 +0000424 if (mThreadPoolStarted) {
425 return mCurrentThreads < mKernelStartedThreads
426 ? mMaxThreads
427 : mMaxThreads + mCurrentThreads - mKernelStartedThreads;
428 }
Yifan Hong84bedeb2021-04-21 21:37:17 -0700429 // must not be initialized or maybe has poll thread setup, we
430 // currently don't track this in libbinder
Elie Kheirallah47431c12022-04-21 23:46:17 +0000431 LOG_ALWAYS_FATAL_IF(mKernelStartedThreads != 0,
432 "Expecting 0 kernel started threads but have"
433 " %zu",
434 mKernelStartedThreads);
435 return mCurrentThreads;
Yifan Hong84bedeb2021-04-21 21:37:17 -0700436}
437
Carlos Llamas4f886702022-03-07 22:07:03 -0800438#define DRIVER_FEATURES_PATH "/dev/binderfs/features/"
439bool ProcessState::isDriverFeatureEnabled(const DriverFeature feature) {
440 static const char* const names[] = {
441 [static_cast<int>(DriverFeature::ONEWAY_SPAM_DETECTION)] =
442 DRIVER_FEATURES_PATH "oneway_spam_detection",
Carlos Llamasb235b122021-12-20 06:38:44 -0800443 [static_cast<int>(DriverFeature::EXTENDED_ERROR)] =
444 DRIVER_FEATURES_PATH "extended_error",
Carlos Llamas4f886702022-03-07 22:07:03 -0800445 };
446 int fd = open(names[static_cast<int>(feature)], O_RDONLY | O_CLOEXEC);
447 char on;
448 if (fd == -1) {
449 ALOGE_IF(errno != ENOENT, "%s: cannot open %s: %s", __func__,
450 names[static_cast<int>(feature)], strerror(errno));
451 return false;
452 }
453 if (read(fd, &on, sizeof(on)) == -1) {
454 ALOGE("%s: error reading to %s: %s", __func__,
455 names[static_cast<int>(feature)], strerror(errno));
456 return false;
457 }
458 close(fd);
459 return on == '1';
460}
461
Hang Lub185ac02021-03-24 13:17:22 +0800462status_t ProcessState::enableOnewaySpamDetection(bool enable) {
463 uint32_t enableDetection = enable ? 1 : 0;
464 if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
Martijn Coenende0a39e2021-04-22 14:38:46 +0200465 ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
Hang Lub185ac02021-03-24 13:17:22 +0800466 return -errno;
467 }
468 return NO_ERROR;
469}
470
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800471void ProcessState::giveThreadPoolName() {
472 androidSetThreadName( makeBinderThreadName().string() );
473}
474
Iliyan Malchev32062242017-04-10 14:06:11 -0700475String8 ProcessState::getDriverName() {
476 return mDriverName;
477}
478
Steven Moreland13a43c92021-08-30 13:21:48 -0700479static base::Result<int> open_driver(const char* driver) {
Martijn Coenen55d871c2017-03-21 15:56:40 -0700480 int fd = open(driver, O_RDWR | O_CLOEXEC);
Steven Moreland13a43c92021-08-30 13:21:48 -0700481 if (fd < 0) {
482 return base::ErrnoError() << "Opening '" << driver << "' failed";
483 }
484 int vers = 0;
485 status_t result = ioctl(fd, BINDER_VERSION, &vers);
486 if (result == -1) {
487 close(fd);
488 return base::ErrnoError() << "Binder ioctl to obtain version failed";
489 }
490 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
491 close(fd);
492 return base::Error() << "Binder driver protocol(" << vers
493 << ") does not match user space protocol("
494 << BINDER_CURRENT_PROTOCOL_VERSION
495 << ")! ioctl() return value: " << result;
496 }
497 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
498 result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
499 if (result == -1) {
500 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
501 }
502 uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
503 result = ioctl(fd, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
504 if (result == -1) {
Carlos Llamas4f886702022-03-07 22:07:03 -0800505 ALOGE_IF(ProcessState::isDriverFeatureEnabled(
506 ProcessState::DriverFeature::ONEWAY_SPAM_DETECTION),
507 "Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800508 }
509 return fd;
510}
511
Steven Moreland13a43c92021-08-30 13:21:48 -0700512ProcessState::ProcessState(const char* driver)
513 : mDriverName(String8(driver)),
514 mDriverFD(-1),
515 mVMStart(MAP_FAILED),
516 mThreadCountLock(PTHREAD_MUTEX_INITIALIZER),
517 mThreadCountDecrement(PTHREAD_COND_INITIALIZER),
518 mExecutingThreadsCount(0),
519 mWaitingForThreads(0),
520 mMaxThreads(DEFAULT_MAX_BINDER_THREADS),
Elie Kheirallah47431c12022-04-21 23:46:17 +0000521 mCurrentThreads(0),
522 mKernelStartedThreads(0),
Steven Moreland13a43c92021-08-30 13:21:48 -0700523 mStarvationStartTimeMs(0),
Steven Morelandee9df902021-10-14 14:00:08 -0700524 mForked(false),
Steven Moreland13a43c92021-08-30 13:21:48 -0700525 mThreadPoolStarted(false),
526 mThreadPoolSeq(1),
527 mCallRestriction(CallRestriction::NONE) {
528 base::Result<int> opened = open_driver(driver);
529
530 if (opened.ok()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800531 // mmap the binder, providing a chunk of virtual address space to receive transactions.
Steven Moreland13a43c92021-08-30 13:21:48 -0700532 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE,
533 opened.value(), 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534 if (mVMStart == MAP_FAILED) {
Steven Moreland13a43c92021-08-30 13:21:48 -0700535 close(opened.value());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800536 // *sigh*
Steven Moreland13a43c92021-08-30 13:21:48 -0700537 opened = base::Error()
538 << "Using " << driver << " failed: unable to mmap transaction memory.";
Iliyan Malchev32062242017-04-10 14:06:11 -0700539 mDriverName.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541 }
Jeff Browne16986c2011-07-08 18:52:57 -0700542
Steven Moreland24bc0d12019-10-11 12:29:20 -0700543#ifdef __ANDROID__
Steven Moreland13a43c92021-08-30 13:21:48 -0700544 LOG_ALWAYS_FATAL_IF(!opened.ok(), "Binder driver '%s' could not be opened. Terminating: %s",
545 driver, opened.error().message().c_str());
Steven Moreland24bc0d12019-10-11 12:29:20 -0700546#endif
Steven Moreland13a43c92021-08-30 13:21:48 -0700547
548 if (opened.ok()) {
549 mDriverFD = opened.value();
550 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800551}
552
553ProcessState::~ProcessState()
554{
zhongjieff405782016-03-09 15:05:04 +0800555 if (mDriverFD >= 0) {
556 if (mVMStart != MAP_FAILED) {
Steven Moreland072cc7e2019-07-12 21:01:54 +0000557 munmap(mVMStart, BINDER_VM_SIZE);
zhongjieff405782016-03-09 15:05:04 +0800558 }
559 close(mDriverFD);
560 }
561 mDriverFD = -1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800562}
Jooyung Han1b228f42020-01-30 13:41:12 +0900563
Steven Moreland61ff8492019-09-26 16:05:45 -0700564} // namespace android