blob: 1f311acb200ca256637d9a20676249abf4aaf3e0 [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 Morelandb763b142022-07-13 01:24:24 +000022#include <android-base/scopeguard.h>
Steven Moreland281abad2022-02-24 22:06:40 +000023#include <android-base/strings.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070024#include <binder/BpBinder.h>
25#include <binder/IPCThreadState.h>
Steven Moreland2716e112018-02-23 14:57:20 -080026#include <binder/IServiceManager.h>
Steven Morelandc709dd82019-08-05 20:30:14 -070027#include <binder/Stability.h>
Steven Moreland2716e112018-02-23 14:57:20 -080028#include <cutils/atomic.h>
Andrei Homescu8028ff42022-03-14 22:11:54 +000029#include <utils/AndroidThreads.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030#include <utils/Log.h>
31#include <utils/String8.h>
Andrei Homescu8028ff42022-03-14 22:11:54 +000032#include <utils/Thread.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Steven Morelanda4853cd2019-07-12 15:44:37 -070034#include "Static.h"
Steven Moreland6ba5a252021-05-04 22:49:00 +000035#include "binder_module.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036
37#include <errno.h>
38#include <fcntl.h>
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +000039#include <pthread.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080040#include <stdio.h>
41#include <stdlib.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080042#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>
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +000046#include <unistd.h>
47#include <mutex>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080048
Steven Moreland072cc7e2019-07-12 21:01:54 +000049#define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
Wale Ogunwale376b8222015-04-13 16:16:10 -070050#define DEFAULT_MAX_BINDER_THREADS 15
Hang Lub185ac02021-03-24 13:17:22 +080051#define DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION 1
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080052
Martijn Coenen7bca77a2019-03-13 11:51:08 +000053#ifdef __ANDROID_VNDK__
54const char* kDefaultDriver = "/dev/vndbinder";
55#else
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070056const char* kDefaultDriver = "/dev/binder";
Martijn Coenen7bca77a2019-03-13 11:51:08 +000057#endif
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070058
Philip Cuadraa082fa82016-04-08 10:29:14 -070059// -------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
61namespace android {
Wale Ogunwale376b8222015-04-13 16:16:10 -070062
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063class PoolThread : public Thread
64{
65public:
Chih-Hung Hsiehe2347b72016-04-25 15:41:05 -070066 explicit PoolThread(bool isMain)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067 : mIsMain(isMain)
68 {
69 }
Jooyung Han1b228f42020-01-30 13:41:12 +090070
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071protected:
72 virtual bool threadLoop()
73 {
74 IPCThreadState::self()->joinThreadPool(mIsMain);
75 return false;
76 }
Jooyung Han1b228f42020-01-30 13:41:12 +090077
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078 const bool mIsMain;
79};
80
81sp<ProcessState> ProcessState::self()
82{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000083 return init(kDefaultDriver, false /*requireDefault*/);
Martijn Coenen55d871c2017-03-21 15:56:40 -070084}
85
86sp<ProcessState> ProcessState::initWithDriver(const char* driver)
87{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000088 return init(driver, true /*requireDefault*/);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089}
90
Steven Moreland072cc7e2019-07-12 21:01:54 +000091sp<ProcessState> ProcessState::selfOrNull()
92{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000093 return init(nullptr, false /*requireDefault*/);
94}
95
Steven Morelandee9df902021-10-14 14:00:08 -070096[[clang::no_destroy]] static sp<ProcessState> gProcess;
97[[clang::no_destroy]] static std::mutex gProcessMutex;
98
99static void verifyNotForked(bool forked) {
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700100 LOG_ALWAYS_FATAL_IF(forked, "libbinder ProcessState can not be used after fork");
Steven Morelandee9df902021-10-14 14:00:08 -0700101}
102
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000103sp<ProcessState> ProcessState::init(const char *driver, bool requireDefault)
104{
Steven Moreland49c39362022-05-13 20:10:24 +0000105#ifdef BINDER_IPC_32BIT
106 LOG_ALWAYS_FATAL("32-bit binder IPC is not supported for new devices starting in Android P. If "
107 "you do need to use this mode, please see b/232423610 or file an issue with "
108 "AOSP upstream as otherwise this will be removed soon.");
109#endif
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000110
111 if (driver == nullptr) {
112 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Morelandee9df902021-10-14 14:00:08 -0700113 if (gProcess) {
114 verifyNotForked(gProcess->mForked);
115 }
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000116 return gProcess;
117 }
118
119 [[clang::no_destroy]] static std::once_flag gProcessOnce;
120 std::call_once(gProcessOnce, [&](){
121 if (access(driver, R_OK) == -1) {
122 ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
123 driver = "/dev/binder";
124 }
125
Steven Morelandee9df902021-10-14 14:00:08 -0700126 // we must install these before instantiating the gProcess object,
127 // otherwise this would race with creating it, and there could be the
128 // possibility of an invalid gProcess object forked by another thread
129 // before these are installed
130 int ret = pthread_atfork(ProcessState::onFork, ProcessState::parentPostFork,
131 ProcessState::childPostFork);
132 LOG_ALWAYS_FATAL_IF(ret != 0, "pthread_atfork error %s", strerror(ret));
133
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000134 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000135 gProcess = sp<ProcessState>::make(driver);
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000136 });
137
138 if (requireDefault) {
139 // Detect if we are trying to initialize with a different driver, and
140 // consider that an error. ProcessState will only be initialized once above.
141 LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,
142 "ProcessState was already initialized with %s,"
143 " can't initialize with %s.",
144 gProcess->getDriverName().c_str(), driver);
145 }
146
Steven Morelandee9df902021-10-14 14:00:08 -0700147 verifyNotForked(gProcess->mForked);
Colin Cross9d45ccc2017-06-20 17:48:33 -0700148 return gProcess;
149}
150
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800151sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800152{
Steven Morelandc709dd82019-08-05 20:30:14 -0700153 sp<IBinder> context = getStrongProxyForHandle(0);
154
Steven Moreland4da8fb02020-12-29 22:51:32 +0000155 if (context) {
156 // The root object is special since we get it directly from the driver, it is never
157 // written by Parcell::writeStrongBinder.
158 internal::Stability::markCompilationUnit(context.get());
159 } else {
160 ALOGW("Not able to get context object on %s.", mDriverName.c_str());
Steven Moreland8d93a712020-02-19 15:16:15 -0800161 }
162
Steven Morelandc709dd82019-08-05 20:30:14 -0700163 return context;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800164}
165
Steven Morelandee9df902021-10-14 14:00:08 -0700166void ProcessState::onFork() {
167 // make sure another thread isn't currently retrieving ProcessState
168 gProcessMutex.lock();
169}
170
171void ProcessState::parentPostFork() {
172 gProcessMutex.unlock();
173}
174
175void ProcessState::childPostFork() {
176 // another thread might call fork before gProcess is instantiated, but after
177 // the thread handler is installed
178 if (gProcess) {
179 gProcess->mForked = true;
Steven Morelanddf732ba2022-05-18 22:04:49 +0000180
181 // "O_CLOFORK"
182 close(gProcess->mDriverFD);
183 gProcess->mDriverFD = -1;
Steven Morelandee9df902021-10-14 14:00:08 -0700184 }
185 gProcessMutex.unlock();
186}
187
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800188void ProcessState::startThreadPool()
189{
190 AutoMutex _l(mLock);
191 if (!mThreadPoolStarted) {
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000192 if (mMaxThreads == 0) {
193 ALOGW("Extra binder thread started, but 0 threads requested. Do not use "
194 "*startThreadPool when zero threads are requested.");
195 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196 mThreadPoolStarted = true;
197 spawnPooledThread(true);
198 }
199}
200
Steven Moreland61096622020-08-31 23:36:39 +0000201bool ProcessState::becomeContextManager()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202{
Steven Moreland4411d712019-07-12 14:02:53 -0700203 AutoMutex _l(mLock);
Jeff Browne16986c2011-07-08 18:52:57 -0700204
Steven Moreland4411d712019-07-12 14:02:53 -0700205 flat_binder_object obj {
206 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
207 };
Steven Moreland3085a472018-12-26 13:59:23 -0800208
Steven Moreland4411d712019-07-12 14:02:53 -0700209 int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
Steven Moreland3085a472018-12-26 13:59:23 -0800210
Steven Moreland4411d712019-07-12 14:02:53 -0700211 // fallback to original method
212 if (result != 0) {
213 android_errorWriteLog(0x534e4554, "121035042");
Steven Moreland3085a472018-12-26 13:59:23 -0800214
Hungming Chen28b42522020-08-28 17:29:55 +0800215 int unused = 0;
216 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800217 }
Steven Moreland4411d712019-07-12 14:02:53 -0700218
219 if (result == -1) {
Steven Moreland4411d712019-07-12 14:02:53 -0700220 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
221 }
222
223 return result == 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224}
225
Colin Cross9d45ccc2017-06-20 17:48:33 -0700226// Get references to userspace objects held by the kernel binder driver
227// Writes up to count elements into buf, and returns the total number
228// of references the kernel has, which may be larger than count.
229// buf may be NULL if count is 0. The pointers returned by this method
230// should only be used for debugging and not dereferenced, they may
231// already be invalid.
232ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
233{
Colin Cross9d45ccc2017-06-20 17:48:33 -0700234 binder_node_debug_info info = {};
235
Yi Kongfdd8da92018-06-07 17:52:27 -0700236 uintptr_t* end = buf ? buf + buf_count : nullptr;
Colin Cross9d45ccc2017-06-20 17:48:33 -0700237 size_t count = 0;
238
239 do {
240 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
241 if (result < 0) {
242 return -1;
243 }
244 if (info.ptr != 0) {
245 if (buf && buf < end)
246 *buf++ = info.ptr;
247 count++;
248 if (buf && buf < end)
249 *buf++ = info.cookie;
250 count++;
251 }
252 } while (info.ptr != 0);
253
254 return count;
255}
256
Jon Spivack902e6fc2019-10-18 21:22:37 -0700257// Queries the driver for the current strong reference count of the node
258// that the handle points to. Can only be used by the servicemanager.
259//
260// Returns -1 in case of failure, otherwise the strong reference count.
Steven Morelande8393882020-12-18 02:27:20 +0000261ssize_t ProcessState::getStrongRefCountForNode(const sp<BpBinder>& binder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000262 if (binder->isRpcBinder()) return -1;
263
Jon Spivack902e6fc2019-10-18 21:22:37 -0700264 binder_node_info_for_ref info;
265 memset(&info, 0, sizeof(binder_node_info_for_ref));
266
Steven Moreland99157622021-09-13 16:27:34 -0700267 info.handle = binder->getPrivateAccessor().binderHandle();
Jon Spivack902e6fc2019-10-18 21:22:37 -0700268
269 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
270
271 if (result != OK) {
272 static bool logged = false;
273 if (!logged) {
274 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
275 logged = true;
276 }
277 return -1;
278 }
279
280 return info.strong_count;
281}
282
Steven Moreland7732a092019-01-02 17:54:16 -0800283void ProcessState::setCallRestriction(CallRestriction restriction) {
Steven Moreland28723ae2019-04-01 18:52:30 -0700284 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
285 "Call restrictions must be set before the threadpool is started.");
Steven Moreland7732a092019-01-02 17:54:16 -0800286
287 mCallRestriction = restriction;
288}
289
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
291{
292 const size_t N=mHandleToObject.size();
293 if (N <= (size_t)handle) {
294 handle_entry e;
Yi Kongfdd8da92018-06-07 17:52:27 -0700295 e.binder = nullptr;
296 e.refs = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800297 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
Yi Kongfdd8da92018-06-07 17:52:27 -0700298 if (err < NO_ERROR) return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299 }
300 return &mHandleToObject.editItemAt(handle);
301}
302
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000303// see b/166779391: cannot change the VNDK interface, so access like this
304extern sp<BBinder> the_context_object;
305
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800306sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
307{
308 sp<IBinder> result;
309
310 AutoMutex _l(mLock);
311
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000312 if (handle == 0 && the_context_object != nullptr) return the_context_object;
313
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800314 handle_entry* e = lookupHandleLocked(handle);
315
Yi Kongfdd8da92018-06-07 17:52:27 -0700316 if (e != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800317 // We need to create a new BpBinder if there isn't currently one, OR we
Steven Morelande171d622019-07-17 16:06:01 -0700318 // are unable to acquire a weak reference on this current one. The
319 // attemptIncWeak() is safe because we know the BpBinder destructor will always
320 // call expungeHandle(), which acquires the same lock we are holding now.
321 // We need to do this because there is a race condition between someone
322 // releasing a reference on this BpBinder, and a new reference on its handle
323 // arriving from the driver.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800324 IBinder* b = e->binder;
Yi Kongfdd8da92018-06-07 17:52:27 -0700325 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
Todd Poynora7b0f042013-06-18 17:25:37 -0700326 if (handle == 0) {
327 // Special case for context manager...
328 // The context manager is the only object for which we create
329 // a BpBinder proxy without already holding a reference.
330 // Perform a dummy transaction to ensure the context manager
331 // is registered before we create the first local reference
332 // to it (which will occur when creating the BpBinder).
333 // If a local reference is created for the BpBinder when the
334 // context manager is not present, the driver will fail to
335 // provide a reference to the context manager, but the
336 // driver API does not return status.
337 //
338 // Note that this is not race-free if the context manager
339 // dies while this code runs.
Todd Poynora7b0f042013-06-18 17:25:37 -0700340
Steven Moreland9514b202020-09-21 18:03:27 +0000341 IPCThreadState* ipc = IPCThreadState::self();
342
343 CallRestriction originalCallRestriction = ipc->getCallRestriction();
344 ipc->setCallRestriction(CallRestriction::NONE);
345
Todd Poynora7b0f042013-06-18 17:25:37 -0700346 Parcel data;
Steven Moreland9514b202020-09-21 18:03:27 +0000347 status_t status = ipc->transact(
Yi Kongfdd8da92018-06-07 17:52:27 -0700348 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
Steven Moreland9514b202020-09-21 18:03:27 +0000349
350 ipc->setCallRestriction(originalCallRestriction);
351
Todd Poynora7b0f042013-06-18 17:25:37 -0700352 if (status == DEAD_OBJECT)
Yi Kongfdd8da92018-06-07 17:52:27 -0700353 return nullptr;
Todd Poynora7b0f042013-06-18 17:25:37 -0700354 }
355
Steven Moreland99157622021-09-13 16:27:34 -0700356 sp<BpBinder> b = BpBinder::PrivateAccessor::create(handle);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000357 e->binder = b.get();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800358 if (b) e->refs = b->getWeakRefs();
359 result = b;
360 } else {
361 // This little bit of nastyness is to allow us to add a primary
362 // reference to the remote proxy when this team doesn't have one
363 // but another team is sending the handle to us.
364 result.force_set(b);
365 e->refs->decWeak(this);
366 }
367 }
368
369 return result;
370}
371
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800372void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
373{
374 AutoMutex _l(mLock);
Jooyung Han1b228f42020-01-30 13:41:12 +0900375
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376 handle_entry* e = lookupHandleLocked(handle);
377
378 // This handle may have already been replaced with a new BpBinder
379 // (if someone failed the AttemptIncWeak() above); we don't want
380 // to overwrite it.
Yi Kongfdd8da92018-06-07 17:52:27 -0700381 if (e && e->binder == binder) e->binder = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800382}
383
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800384String8 ProcessState::makeBinderThreadName() {
385 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
Philip Cuadraa082fa82016-04-08 10:29:14 -0700386 pid_t pid = getpid();
Steven Moreland281abad2022-02-24 22:06:40 +0000387
388 std::string_view driverName = mDriverName.c_str();
389 android::base::ConsumePrefix(&driverName, "/dev/");
390
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800391 String8 name;
Steven Moreland281abad2022-02-24 22:06:40 +0000392 name.appendFormat("%.*s:%d_%X", static_cast<int>(driverName.length()), driverName.data(), pid,
393 s);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800394 return name;
395}
396
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800397void ProcessState::spawnPooledThread(bool isMain)
398{
399 if (mThreadPoolStarted) {
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800400 String8 name = makeBinderThreadName();
401 ALOGV("Spawning new pooled thread, name=%s\n", name.string());
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000402 sp<Thread> t = sp<PoolThread>::make(isMain);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800403 t->run(name.string());
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +0000404 pthread_mutex_lock(&mThreadCountLock);
Elie Kheirallah47431c12022-04-21 23:46:17 +0000405 mKernelStartedThreads++;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +0000406 pthread_mutex_unlock(&mThreadCountLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800407 }
408}
409
Mathias Agopian1b80f792012-04-17 16:11:08 -0700410status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
Steven Moreland1fdb98b2020-03-06 21:42:12 +0000411 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
412 "Binder threadpool cannot be shrunk after starting");
Mathias Agopian1b80f792012-04-17 16:11:08 -0700413 status_t result = NO_ERROR;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700414 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
415 mMaxThreads = maxThreads;
416 } else {
Mathias Agopian1b80f792012-04-17 16:11:08 -0700417 result = -errno;
418 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
419 }
420 return result;
421}
422
Elie Kheirallah47431c12022-04-21 23:46:17 +0000423size_t ProcessState::getThreadPoolMaxTotalThreadCount() const {
Steven Morelandb763b142022-07-13 01:24:24 +0000424 pthread_mutex_lock(&mThreadCountLock);
425 base::ScopeGuard detachGuard = [&]() { pthread_mutex_unlock(&mThreadCountLock); };
426
Yifan Hong84bedeb2021-04-21 21:37:17 -0700427 // may actually be one more than this, if join is called
Elie Kheirallah47431c12022-04-21 23:46:17 +0000428 if (mThreadPoolStarted) {
429 return mCurrentThreads < mKernelStartedThreads
430 ? mMaxThreads
431 : mMaxThreads + mCurrentThreads - mKernelStartedThreads;
432 }
Yifan Hong84bedeb2021-04-21 21:37:17 -0700433 // must not be initialized or maybe has poll thread setup, we
434 // currently don't track this in libbinder
Elie Kheirallah47431c12022-04-21 23:46:17 +0000435 LOG_ALWAYS_FATAL_IF(mKernelStartedThreads != 0,
436 "Expecting 0 kernel started threads but have"
437 " %zu",
438 mKernelStartedThreads);
439 return mCurrentThreads;
Yifan Hong84bedeb2021-04-21 21:37:17 -0700440}
441
Carlos Llamas4f886702022-03-07 22:07:03 -0800442#define DRIVER_FEATURES_PATH "/dev/binderfs/features/"
443bool ProcessState::isDriverFeatureEnabled(const DriverFeature feature) {
444 static const char* const names[] = {
445 [static_cast<int>(DriverFeature::ONEWAY_SPAM_DETECTION)] =
446 DRIVER_FEATURES_PATH "oneway_spam_detection",
Carlos Llamasb235b122021-12-20 06:38:44 -0800447 [static_cast<int>(DriverFeature::EXTENDED_ERROR)] =
448 DRIVER_FEATURES_PATH "extended_error",
Carlos Llamas4f886702022-03-07 22:07:03 -0800449 };
450 int fd = open(names[static_cast<int>(feature)], O_RDONLY | O_CLOEXEC);
451 char on;
452 if (fd == -1) {
453 ALOGE_IF(errno != ENOENT, "%s: cannot open %s: %s", __func__,
454 names[static_cast<int>(feature)], strerror(errno));
455 return false;
456 }
457 if (read(fd, &on, sizeof(on)) == -1) {
458 ALOGE("%s: error reading to %s: %s", __func__,
459 names[static_cast<int>(feature)], strerror(errno));
460 return false;
461 }
462 close(fd);
463 return on == '1';
464}
465
Hang Lub185ac02021-03-24 13:17:22 +0800466status_t ProcessState::enableOnewaySpamDetection(bool enable) {
467 uint32_t enableDetection = enable ? 1 : 0;
468 if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
Martijn Coenende0a39e2021-04-22 14:38:46 +0200469 ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
Hang Lub185ac02021-03-24 13:17:22 +0800470 return -errno;
471 }
472 return NO_ERROR;
473}
474
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800475void ProcessState::giveThreadPoolName() {
476 androidSetThreadName( makeBinderThreadName().string() );
477}
478
Iliyan Malchev32062242017-04-10 14:06:11 -0700479String8 ProcessState::getDriverName() {
480 return mDriverName;
481}
482
Steven Moreland13a43c92021-08-30 13:21:48 -0700483static base::Result<int> open_driver(const char* driver) {
Martijn Coenen55d871c2017-03-21 15:56:40 -0700484 int fd = open(driver, O_RDWR | O_CLOEXEC);
Steven Moreland13a43c92021-08-30 13:21:48 -0700485 if (fd < 0) {
486 return base::ErrnoError() << "Opening '" << driver << "' failed";
487 }
488 int vers = 0;
489 status_t result = ioctl(fd, BINDER_VERSION, &vers);
490 if (result == -1) {
491 close(fd);
492 return base::ErrnoError() << "Binder ioctl to obtain version failed";
493 }
494 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
495 close(fd);
496 return base::Error() << "Binder driver protocol(" << vers
497 << ") does not match user space protocol("
498 << BINDER_CURRENT_PROTOCOL_VERSION
499 << ")! ioctl() return value: " << result;
500 }
501 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
502 result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
503 if (result == -1) {
504 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
505 }
506 uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
507 result = ioctl(fd, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
508 if (result == -1) {
Carlos Llamas4f886702022-03-07 22:07:03 -0800509 ALOGE_IF(ProcessState::isDriverFeatureEnabled(
510 ProcessState::DriverFeature::ONEWAY_SPAM_DETECTION),
511 "Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800512 }
513 return fd;
514}
515
Steven Moreland13a43c92021-08-30 13:21:48 -0700516ProcessState::ProcessState(const char* driver)
517 : mDriverName(String8(driver)),
518 mDriverFD(-1),
519 mVMStart(MAP_FAILED),
520 mThreadCountLock(PTHREAD_MUTEX_INITIALIZER),
521 mThreadCountDecrement(PTHREAD_COND_INITIALIZER),
522 mExecutingThreadsCount(0),
523 mWaitingForThreads(0),
524 mMaxThreads(DEFAULT_MAX_BINDER_THREADS),
Elie Kheirallah47431c12022-04-21 23:46:17 +0000525 mCurrentThreads(0),
526 mKernelStartedThreads(0),
Steven Moreland13a43c92021-08-30 13:21:48 -0700527 mStarvationStartTimeMs(0),
Steven Morelandee9df902021-10-14 14:00:08 -0700528 mForked(false),
Steven Moreland13a43c92021-08-30 13:21:48 -0700529 mThreadPoolStarted(false),
530 mThreadPoolSeq(1),
531 mCallRestriction(CallRestriction::NONE) {
532 base::Result<int> opened = open_driver(driver);
533
534 if (opened.ok()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800535 // mmap the binder, providing a chunk of virtual address space to receive transactions.
Steven Moreland13a43c92021-08-30 13:21:48 -0700536 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE,
537 opened.value(), 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800538 if (mVMStart == MAP_FAILED) {
Steven Moreland13a43c92021-08-30 13:21:48 -0700539 close(opened.value());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540 // *sigh*
Steven Moreland13a43c92021-08-30 13:21:48 -0700541 opened = base::Error()
542 << "Using " << driver << " failed: unable to mmap transaction memory.";
Iliyan Malchev32062242017-04-10 14:06:11 -0700543 mDriverName.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800544 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800545 }
Jeff Browne16986c2011-07-08 18:52:57 -0700546
Steven Moreland24bc0d12019-10-11 12:29:20 -0700547#ifdef __ANDROID__
Steven Moreland13a43c92021-08-30 13:21:48 -0700548 LOG_ALWAYS_FATAL_IF(!opened.ok(), "Binder driver '%s' could not be opened. Terminating: %s",
549 driver, opened.error().message().c_str());
Steven Moreland24bc0d12019-10-11 12:29:20 -0700550#endif
Steven Moreland13a43c92021-08-30 13:21:48 -0700551
552 if (opened.ok()) {
553 mDriverFD = opened.value();
554 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800555}
556
557ProcessState::~ProcessState()
558{
zhongjieff405782016-03-09 15:05:04 +0800559 if (mDriverFD >= 0) {
560 if (mVMStart != MAP_FAILED) {
Steven Moreland072cc7e2019-07-12 21:01:54 +0000561 munmap(mVMStart, BINDER_VM_SIZE);
zhongjieff405782016-03-09 15:05:04 +0800562 }
563 close(mDriverFD);
564 }
565 mDriverFD = -1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800566}
Jooyung Han1b228f42020-01-30 13:41:12 +0900567
Steven Moreland61ff8492019-09-26 16:05:45 -0700568} // namespace android