blob: 0344eb04d65e61ffc08cab8891e5c76ac93d6441 [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 Moreland281abad2022-02-24 22:06:40 +000021#include <android-base/strings.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070022#include <binder/BpBinder.h>
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000023#include <binder/Functional.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070024#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"
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -070034#include "Utils.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
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000063using namespace android::binder::impl;
64
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065class PoolThread : public Thread
66{
67public:
Chih-Hung Hsiehe2347b72016-04-25 15:41:05 -070068 explicit PoolThread(bool isMain)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080069 : mIsMain(isMain)
70 {
71 }
Jooyung Han1b228f42020-01-30 13:41:12 +090072
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073protected:
74 virtual bool threadLoop()
75 {
76 IPCThreadState::self()->joinThreadPool(mIsMain);
77 return false;
78 }
Jooyung Han1b228f42020-01-30 13:41:12 +090079
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080 const bool mIsMain;
81};
82
83sp<ProcessState> ProcessState::self()
84{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000085 return init(kDefaultDriver, false /*requireDefault*/);
Martijn Coenen55d871c2017-03-21 15:56:40 -070086}
87
88sp<ProcessState> ProcessState::initWithDriver(const char* driver)
89{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000090 return init(driver, true /*requireDefault*/);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091}
92
Steven Moreland072cc7e2019-07-12 21:01:54 +000093sp<ProcessState> ProcessState::selfOrNull()
94{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000095 return init(nullptr, false /*requireDefault*/);
96}
97
Steven Morelandee9df902021-10-14 14:00:08 -070098[[clang::no_destroy]] static sp<ProcessState> gProcess;
99[[clang::no_destroy]] static std::mutex gProcessMutex;
100
101static void verifyNotForked(bool forked) {
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700102 LOG_ALWAYS_FATAL_IF(forked, "libbinder ProcessState can not be used after fork");
Steven Morelandee9df902021-10-14 14:00:08 -0700103}
104
Steven Moreland9a4278e2023-02-14 01:33:39 +0000105bool ProcessState::isVndservicemanagerEnabled() {
106 return access("/vendor/bin/vndservicemanager", R_OK) == 0;
107}
108
Steven Moreland68275d72023-04-21 22:12:45 +0000109sp<ProcessState> ProcessState::init(const char* driver, bool requireDefault) {
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000110 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 Moreland9a4278e2023-02-14 01:33:39 +0000125 if (0 == strcmp(driver, "/dev/vndbinder") && !isVndservicemanagerEnabled()) {
126 ALOGE("vndservicemanager is not started on this device, you can save resources/threads "
127 "by not initializing ProcessState with /dev/vndbinder.");
128 }
129
Steven Morelandee9df902021-10-14 14:00:08 -0700130 // we must install these before instantiating the gProcess object,
131 // otherwise this would race with creating it, and there could be the
132 // possibility of an invalid gProcess object forked by another thread
133 // before these are installed
134 int ret = pthread_atfork(ProcessState::onFork, ProcessState::parentPostFork,
135 ProcessState::childPostFork);
136 LOG_ALWAYS_FATAL_IF(ret != 0, "pthread_atfork error %s", strerror(ret));
137
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000138 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000139 gProcess = sp<ProcessState>::make(driver);
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000140 });
141
142 if (requireDefault) {
143 // Detect if we are trying to initialize with a different driver, and
144 // consider that an error. ProcessState will only be initialized once above.
145 LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,
146 "ProcessState was already initialized with %s,"
147 " can't initialize with %s.",
148 gProcess->getDriverName().c_str(), driver);
149 }
150
Steven Morelandee9df902021-10-14 14:00:08 -0700151 verifyNotForked(gProcess->mForked);
Colin Cross9d45ccc2017-06-20 17:48:33 -0700152 return gProcess;
153}
154
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800155sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800156{
Steven Morelandc709dd82019-08-05 20:30:14 -0700157 sp<IBinder> context = getStrongProxyForHandle(0);
158
Steven Moreland4da8fb02020-12-29 22:51:32 +0000159 if (context) {
160 // The root object is special since we get it directly from the driver, it is never
161 // written by Parcell::writeStrongBinder.
162 internal::Stability::markCompilationUnit(context.get());
163 } else {
164 ALOGW("Not able to get context object on %s.", mDriverName.c_str());
Steven Moreland8d93a712020-02-19 15:16:15 -0800165 }
166
Steven Morelandc709dd82019-08-05 20:30:14 -0700167 return context;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800168}
169
Steven Morelandee9df902021-10-14 14:00:08 -0700170void ProcessState::onFork() {
171 // make sure another thread isn't currently retrieving ProcessState
172 gProcessMutex.lock();
173}
174
175void ProcessState::parentPostFork() {
176 gProcessMutex.unlock();
177}
178
179void ProcessState::childPostFork() {
180 // another thread might call fork before gProcess is instantiated, but after
181 // the thread handler is installed
182 if (gProcess) {
183 gProcess->mForked = true;
Steven Morelanddf732ba2022-05-18 22:04:49 +0000184
185 // "O_CLOFORK"
186 close(gProcess->mDriverFD);
187 gProcess->mDriverFD = -1;
Steven Morelandee9df902021-10-14 14:00:08 -0700188 }
189 gProcessMutex.unlock();
190}
191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192void ProcessState::startThreadPool()
193{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700194 std::unique_lock<std::mutex> _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195 if (!mThreadPoolStarted) {
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000196 if (mMaxThreads == 0) {
Steven Moreland3e9debc2023-06-15 00:35:29 +0000197 // see also getThreadPoolMaxTotalThreadCount
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000198 ALOGW("Extra binder thread started, but 0 threads requested. Do not use "
199 "*startThreadPool when zero threads are requested.");
200 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201 mThreadPoolStarted = true;
202 spawnPooledThread(true);
203 }
204}
205
Steven Moreland61096622020-08-31 23:36:39 +0000206bool ProcessState::becomeContextManager()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800207{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700208 std::unique_lock<std::mutex> _l(mLock);
Jeff Browne16986c2011-07-08 18:52:57 -0700209
Steven Moreland4411d712019-07-12 14:02:53 -0700210 flat_binder_object obj {
211 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
212 };
Steven Moreland3085a472018-12-26 13:59:23 -0800213
Steven Moreland4411d712019-07-12 14:02:53 -0700214 int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
Steven Moreland3085a472018-12-26 13:59:23 -0800215
Steven Moreland4411d712019-07-12 14:02:53 -0700216 // fallback to original method
217 if (result != 0) {
218 android_errorWriteLog(0x534e4554, "121035042");
Steven Moreland3085a472018-12-26 13:59:23 -0800219
Hungming Chen28b42522020-08-28 17:29:55 +0800220 int unused = 0;
221 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222 }
Steven Moreland4411d712019-07-12 14:02:53 -0700223
224 if (result == -1) {
Steven Moreland4411d712019-07-12 14:02:53 -0700225 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
226 }
227
228 return result == 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229}
230
Colin Cross9d45ccc2017-06-20 17:48:33 -0700231// Get references to userspace objects held by the kernel binder driver
232// Writes up to count elements into buf, and returns the total number
233// of references the kernel has, which may be larger than count.
234// buf may be NULL if count is 0. The pointers returned by this method
235// should only be used for debugging and not dereferenced, they may
236// already be invalid.
237ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
238{
Colin Cross9d45ccc2017-06-20 17:48:33 -0700239 binder_node_debug_info info = {};
240
Yi Kongfdd8da92018-06-07 17:52:27 -0700241 uintptr_t* end = buf ? buf + buf_count : nullptr;
Colin Cross9d45ccc2017-06-20 17:48:33 -0700242 size_t count = 0;
243
244 do {
245 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
246 if (result < 0) {
247 return -1;
248 }
249 if (info.ptr != 0) {
250 if (buf && buf < end)
251 *buf++ = info.ptr;
252 count++;
253 if (buf && buf < end)
254 *buf++ = info.cookie;
255 count++;
256 }
257 } while (info.ptr != 0);
258
259 return count;
260}
261
Jon Spivack902e6fc2019-10-18 21:22:37 -0700262// Queries the driver for the current strong reference count of the node
263// that the handle points to. Can only be used by the servicemanager.
264//
265// Returns -1 in case of failure, otherwise the strong reference count.
Steven Morelande8393882020-12-18 02:27:20 +0000266ssize_t ProcessState::getStrongRefCountForNode(const sp<BpBinder>& binder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000267 if (binder->isRpcBinder()) return -1;
268
Jon Spivack902e6fc2019-10-18 21:22:37 -0700269 binder_node_info_for_ref info;
270 memset(&info, 0, sizeof(binder_node_info_for_ref));
271
Steven Moreland99157622021-09-13 16:27:34 -0700272 info.handle = binder->getPrivateAccessor().binderHandle();
Jon Spivack902e6fc2019-10-18 21:22:37 -0700273
274 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
275
276 if (result != OK) {
277 static bool logged = false;
278 if (!logged) {
279 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
280 logged = true;
281 }
282 return -1;
283 }
284
285 return info.strong_count;
286}
287
Steven Moreland7732a092019-01-02 17:54:16 -0800288void ProcessState::setCallRestriction(CallRestriction restriction) {
Steven Moreland28723ae2019-04-01 18:52:30 -0700289 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
290 "Call restrictions must be set before the threadpool is started.");
Steven Moreland7732a092019-01-02 17:54:16 -0800291
292 mCallRestriction = restriction;
293}
294
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800295ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
296{
297 const size_t N=mHandleToObject.size();
298 if (N <= (size_t)handle) {
299 handle_entry e;
Yi Kongfdd8da92018-06-07 17:52:27 -0700300 e.binder = nullptr;
301 e.refs = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800302 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
Yi Kongfdd8da92018-06-07 17:52:27 -0700303 if (err < NO_ERROR) return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800304 }
305 return &mHandleToObject.editItemAt(handle);
306}
307
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000308// see b/166779391: cannot change the VNDK interface, so access like this
309extern sp<BBinder> the_context_object;
310
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800311sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
312{
313 sp<IBinder> result;
314
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700315 std::unique_lock<std::mutex> _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800316
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000317 if (handle == 0 && the_context_object != nullptr) return the_context_object;
318
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800319 handle_entry* e = lookupHandleLocked(handle);
320
Yi Kongfdd8da92018-06-07 17:52:27 -0700321 if (e != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800322 // We need to create a new BpBinder if there isn't currently one, OR we
Steven Morelande171d622019-07-17 16:06:01 -0700323 // are unable to acquire a weak reference on this current one. The
324 // attemptIncWeak() is safe because we know the BpBinder destructor will always
325 // call expungeHandle(), which acquires the same lock we are holding now.
326 // We need to do this because there is a race condition between someone
327 // releasing a reference on this BpBinder, and a new reference on its handle
328 // arriving from the driver.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800329 IBinder* b = e->binder;
Yi Kongfdd8da92018-06-07 17:52:27 -0700330 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
Todd Poynora7b0f042013-06-18 17:25:37 -0700331 if (handle == 0) {
332 // Special case for context manager...
333 // The context manager is the only object for which we create
334 // a BpBinder proxy without already holding a reference.
335 // Perform a dummy transaction to ensure the context manager
336 // is registered before we create the first local reference
337 // to it (which will occur when creating the BpBinder).
338 // If a local reference is created for the BpBinder when the
339 // context manager is not present, the driver will fail to
340 // provide a reference to the context manager, but the
341 // driver API does not return status.
342 //
343 // Note that this is not race-free if the context manager
344 // dies while this code runs.
Todd Poynora7b0f042013-06-18 17:25:37 -0700345
Steven Moreland9514b202020-09-21 18:03:27 +0000346 IPCThreadState* ipc = IPCThreadState::self();
347
348 CallRestriction originalCallRestriction = ipc->getCallRestriction();
349 ipc->setCallRestriction(CallRestriction::NONE);
350
Todd Poynora7b0f042013-06-18 17:25:37 -0700351 Parcel data;
Steven Moreland9514b202020-09-21 18:03:27 +0000352 status_t status = ipc->transact(
Yi Kongfdd8da92018-06-07 17:52:27 -0700353 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
Steven Moreland9514b202020-09-21 18:03:27 +0000354
355 ipc->setCallRestriction(originalCallRestriction);
356
Todd Poynora7b0f042013-06-18 17:25:37 -0700357 if (status == DEAD_OBJECT)
Yi Kongfdd8da92018-06-07 17:52:27 -0700358 return nullptr;
Todd Poynora7b0f042013-06-18 17:25:37 -0700359 }
360
Steven Moreland99157622021-09-13 16:27:34 -0700361 sp<BpBinder> b = BpBinder::PrivateAccessor::create(handle);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000362 e->binder = b.get();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800363 if (b) e->refs = b->getWeakRefs();
364 result = b;
365 } else {
366 // This little bit of nastyness is to allow us to add a primary
367 // reference to the remote proxy when this team doesn't have one
368 // but another team is sending the handle to us.
369 result.force_set(b);
370 e->refs->decWeak(this);
371 }
372 }
373
374 return result;
375}
376
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800377void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
378{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700379 std::unique_lock<std::mutex> _l(mLock);
Jooyung Han1b228f42020-01-30 13:41:12 +0900380
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381 handle_entry* e = lookupHandleLocked(handle);
382
383 // This handle may have already been replaced with a new BpBinder
384 // (if someone failed the AttemptIncWeak() above); we don't want
385 // to overwrite it.
Yi Kongfdd8da92018-06-07 17:52:27 -0700386 if (e && e->binder == binder) e->binder = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800387}
388
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800389String8 ProcessState::makeBinderThreadName() {
390 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
Philip Cuadraa082fa82016-04-08 10:29:14 -0700391 pid_t pid = getpid();
Steven Moreland281abad2022-02-24 22:06:40 +0000392
393 std::string_view driverName = mDriverName.c_str();
394 android::base::ConsumePrefix(&driverName, "/dev/");
395
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800396 String8 name;
Steven Moreland281abad2022-02-24 22:06:40 +0000397 name.appendFormat("%.*s:%d_%X", static_cast<int>(driverName.length()), driverName.data(), pid,
398 s);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800399 return name;
400}
401
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800402void ProcessState::spawnPooledThread(bool isMain)
403{
404 if (mThreadPoolStarted) {
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800405 String8 name = makeBinderThreadName();
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000406 ALOGV("Spawning new pooled thread, name=%s\n", name.c_str());
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000407 sp<Thread> t = sp<PoolThread>::make(isMain);
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000408 t->run(name.c_str());
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +0000409 pthread_mutex_lock(&mThreadCountLock);
Elie Kheirallah47431c12022-04-21 23:46:17 +0000410 mKernelStartedThreads++;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +0000411 pthread_mutex_unlock(&mThreadCountLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800412 }
Steven Moreland3e9debc2023-06-15 00:35:29 +0000413 // TODO: if startThreadPool is called on another thread after the process
414 // starts up, the kernel might think that it already requested those
415 // binder threads, and additional won't be started. This is likely to
416 // cause deadlocks, and it will also cause getThreadPoolMaxTotalThreadCount
417 // to return too high of a value.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800418}
419
Mathias Agopian1b80f792012-04-17 16:11:08 -0700420status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
Steven Moreland1fdb98b2020-03-06 21:42:12 +0000421 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
422 "Binder threadpool cannot be shrunk after starting");
Mathias Agopian1b80f792012-04-17 16:11:08 -0700423 status_t result = NO_ERROR;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700424 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
425 mMaxThreads = maxThreads;
426 } else {
Mathias Agopian1b80f792012-04-17 16:11:08 -0700427 result = -errno;
428 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
429 }
430 return result;
431}
432
Elie Kheirallah47431c12022-04-21 23:46:17 +0000433size_t ProcessState::getThreadPoolMaxTotalThreadCount() const {
Steven Morelandb763b142022-07-13 01:24:24 +0000434 pthread_mutex_lock(&mThreadCountLock);
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +0000435 auto detachGuard = make_scope_guard([&]() { pthread_mutex_unlock(&mThreadCountLock); });
Steven Morelandb763b142022-07-13 01:24:24 +0000436
Elie Kheirallah47431c12022-04-21 23:46:17 +0000437 if (mThreadPoolStarted) {
Steven Moreland3e9debc2023-06-15 00:35:29 +0000438 LOG_ALWAYS_FATAL_IF(mKernelStartedThreads > mMaxThreads + 1,
439 "too many kernel-started threads: %zu > %zu + 1", mKernelStartedThreads,
440 mMaxThreads);
441
442 // calling startThreadPool starts a thread
443 size_t threads = 1;
444
445 // the kernel is configured to start up to mMaxThreads more threads
446 threads += mMaxThreads;
447
448 // Users may call IPCThreadState::joinThreadPool directly. We don't
449 // currently have a way to count this directly (it could be added by
450 // adding a separate private joinKernelThread method in IPCThreadState).
451 // So, if we are in a race between the kernel thread variable being
452 // incremented in this file and mCurrentThreads being incremented
453 // in IPCThreadState, temporarily forget about the extra join threads.
454 // This is okay, because most callers of this method only care about
455 // having 0, 1, or more threads.
456 if (mCurrentThreads > mKernelStartedThreads) {
457 threads += mCurrentThreads - mKernelStartedThreads;
458 }
459
460 return threads;
Elie Kheirallah47431c12022-04-21 23:46:17 +0000461 }
Steven Moreland3e9debc2023-06-15 00:35:29 +0000462
Yifan Hong84bedeb2021-04-21 21:37:17 -0700463 // must not be initialized or maybe has poll thread setup, we
464 // currently don't track this in libbinder
Elie Kheirallah47431c12022-04-21 23:46:17 +0000465 LOG_ALWAYS_FATAL_IF(mKernelStartedThreads != 0,
466 "Expecting 0 kernel started threads but have"
467 " %zu",
468 mKernelStartedThreads);
469 return mCurrentThreads;
Yifan Hong84bedeb2021-04-21 21:37:17 -0700470}
471
Devin Moore4354f712022-12-08 01:44:46 +0000472bool ProcessState::isThreadPoolStarted() const {
473 return mThreadPoolStarted;
474}
475
Carlos Llamas4f886702022-03-07 22:07:03 -0800476#define DRIVER_FEATURES_PATH "/dev/binderfs/features/"
477bool ProcessState::isDriverFeatureEnabled(const DriverFeature feature) {
478 static const char* const names[] = {
479 [static_cast<int>(DriverFeature::ONEWAY_SPAM_DETECTION)] =
480 DRIVER_FEATURES_PATH "oneway_spam_detection",
Carlos Llamasb235b122021-12-20 06:38:44 -0800481 [static_cast<int>(DriverFeature::EXTENDED_ERROR)] =
482 DRIVER_FEATURES_PATH "extended_error",
Carlos Llamas4f886702022-03-07 22:07:03 -0800483 };
484 int fd = open(names[static_cast<int>(feature)], O_RDONLY | O_CLOEXEC);
485 char on;
486 if (fd == -1) {
487 ALOGE_IF(errno != ENOENT, "%s: cannot open %s: %s", __func__,
488 names[static_cast<int>(feature)], strerror(errno));
489 return false;
490 }
491 if (read(fd, &on, sizeof(on)) == -1) {
492 ALOGE("%s: error reading to %s: %s", __func__,
493 names[static_cast<int>(feature)], strerror(errno));
494 return false;
495 }
496 close(fd);
497 return on == '1';
498}
499
Hang Lub185ac02021-03-24 13:17:22 +0800500status_t ProcessState::enableOnewaySpamDetection(bool enable) {
501 uint32_t enableDetection = enable ? 1 : 0;
502 if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
Martijn Coenende0a39e2021-04-22 14:38:46 +0200503 ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
Hang Lub185ac02021-03-24 13:17:22 +0800504 return -errno;
505 }
506 return NO_ERROR;
507}
508
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800509void ProcessState::giveThreadPoolName() {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000510 androidSetThreadName(makeBinderThreadName().c_str());
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800511}
512
Iliyan Malchev32062242017-04-10 14:06:11 -0700513String8 ProcessState::getDriverName() {
514 return mDriverName;
515}
516
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700517static base::unique_fd open_driver(const char* driver) {
518 auto fd = base::unique_fd(open(driver, O_RDWR | O_CLOEXEC));
519 if (!fd.ok()) {
520 PLOGE("Opening '%s' failed", driver);
521 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700522 }
523 int vers = 0;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700524 int result = ioctl(fd.get(), BINDER_VERSION, &vers);
Steven Moreland13a43c92021-08-30 13:21:48 -0700525 if (result == -1) {
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700526 PLOGE("Binder ioctl to obtain version failed");
527 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700528 }
529 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700530 ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)! "
531 "ioctl() return value: %d",
532 vers, BINDER_CURRENT_PROTOCOL_VERSION, result);
533 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700534 }
535 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700536 result = ioctl(fd.get(), BINDER_SET_MAX_THREADS, &maxThreads);
Steven Moreland13a43c92021-08-30 13:21:48 -0700537 if (result == -1) {
538 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
539 }
540 uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700541 result = ioctl(fd.get(), BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
Steven Moreland13a43c92021-08-30 13:21:48 -0700542 if (result == -1) {
Carlos Llamas4f886702022-03-07 22:07:03 -0800543 ALOGE_IF(ProcessState::isDriverFeatureEnabled(
544 ProcessState::DriverFeature::ONEWAY_SPAM_DETECTION),
545 "Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800546 }
547 return fd;
548}
549
Steven Moreland13a43c92021-08-30 13:21:48 -0700550ProcessState::ProcessState(const char* driver)
551 : mDriverName(String8(driver)),
552 mDriverFD(-1),
553 mVMStart(MAP_FAILED),
554 mThreadCountLock(PTHREAD_MUTEX_INITIALIZER),
555 mThreadCountDecrement(PTHREAD_COND_INITIALIZER),
556 mExecutingThreadsCount(0),
557 mWaitingForThreads(0),
558 mMaxThreads(DEFAULT_MAX_BINDER_THREADS),
Elie Kheirallah47431c12022-04-21 23:46:17 +0000559 mCurrentThreads(0),
560 mKernelStartedThreads(0),
Steven Moreland13a43c92021-08-30 13:21:48 -0700561 mStarvationStartTimeMs(0),
Steven Morelandee9df902021-10-14 14:00:08 -0700562 mForked(false),
Steven Moreland13a43c92021-08-30 13:21:48 -0700563 mThreadPoolStarted(false),
564 mThreadPoolSeq(1),
565 mCallRestriction(CallRestriction::NONE) {
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700566 base::unique_fd opened = open_driver(driver);
Steven Moreland13a43c92021-08-30 13:21:48 -0700567
568 if (opened.ok()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800569 // mmap the binder, providing a chunk of virtual address space to receive transactions.
Steven Moreland13a43c92021-08-30 13:21:48 -0700570 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE,
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700571 opened.get(), 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800572 if (mVMStart == MAP_FAILED) {
573 // *sigh*
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700574 ALOGE("Using %s failed: unable to mmap transaction memory.", driver);
575 opened.reset();
Iliyan Malchev32062242017-04-10 14:06:11 -0700576 mDriverName.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800577 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800578 }
Jeff Browne16986c2011-07-08 18:52:57 -0700579
Steven Moreland24bc0d12019-10-11 12:29:20 -0700580#ifdef __ANDROID__
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700581 LOG_ALWAYS_FATAL_IF(!opened.ok(), "Binder driver '%s' could not be opened. Terminating.",
582 driver);
Steven Moreland24bc0d12019-10-11 12:29:20 -0700583#endif
Steven Moreland13a43c92021-08-30 13:21:48 -0700584
585 if (opened.ok()) {
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700586 mDriverFD = opened.release();
Steven Moreland13a43c92021-08-30 13:21:48 -0700587 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800588}
589
590ProcessState::~ProcessState()
591{
zhongjieff405782016-03-09 15:05:04 +0800592 if (mDriverFD >= 0) {
593 if (mVMStart != MAP_FAILED) {
Steven Moreland072cc7e2019-07-12 21:01:54 +0000594 munmap(mVMStart, BINDER_VM_SIZE);
zhongjieff405782016-03-09 15:05:04 +0800595 }
596 close(mDriverFD);
597 }
598 mDriverFD = -1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800599}
Jooyung Han1b228f42020-01-30 13:41:12 +0900600
Steven Moreland61ff8492019-09-26 16:05:45 -0700601} // namespace android