blob: 7af2845f5d3245952f6e666ae8b9a11b8f1e24aa [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
Sebastian Pickl25c1a3b2023-10-30 08:02:24 +000021#include <android-base/scopeguard.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"
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
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 Moreland9a4278e2023-02-14 01:33:39 +0000103bool ProcessState::isVndservicemanagerEnabled() {
104 return access("/vendor/bin/vndservicemanager", R_OK) == 0;
105}
106
Steven Moreland68275d72023-04-21 22:12:45 +0000107sp<ProcessState> ProcessState::init(const char* driver, bool requireDefault) {
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000108 if (driver == nullptr) {
109 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Morelandee9df902021-10-14 14:00:08 -0700110 if (gProcess) {
111 verifyNotForked(gProcess->mForked);
112 }
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000113 return gProcess;
114 }
115
116 [[clang::no_destroy]] static std::once_flag gProcessOnce;
117 std::call_once(gProcessOnce, [&](){
118 if (access(driver, R_OK) == -1) {
119 ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
120 driver = "/dev/binder";
121 }
122
Steven Moreland9a4278e2023-02-14 01:33:39 +0000123 if (0 == strcmp(driver, "/dev/vndbinder") && !isVndservicemanagerEnabled()) {
124 ALOGE("vndservicemanager is not started on this device, you can save resources/threads "
125 "by not initializing ProcessState with /dev/vndbinder.");
126 }
127
Steven Morelandee9df902021-10-14 14:00:08 -0700128 // we must install these before instantiating the gProcess object,
129 // otherwise this would race with creating it, and there could be the
130 // possibility of an invalid gProcess object forked by another thread
131 // before these are installed
132 int ret = pthread_atfork(ProcessState::onFork, ProcessState::parentPostFork,
133 ProcessState::childPostFork);
134 LOG_ALWAYS_FATAL_IF(ret != 0, "pthread_atfork error %s", strerror(ret));
135
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000136 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000137 gProcess = sp<ProcessState>::make(driver);
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000138 });
139
140 if (requireDefault) {
141 // Detect if we are trying to initialize with a different driver, and
142 // consider that an error. ProcessState will only be initialized once above.
143 LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,
144 "ProcessState was already initialized with %s,"
145 " can't initialize with %s.",
146 gProcess->getDriverName().c_str(), driver);
147 }
148
Steven Morelandee9df902021-10-14 14:00:08 -0700149 verifyNotForked(gProcess->mForked);
Colin Cross9d45ccc2017-06-20 17:48:33 -0700150 return gProcess;
151}
152
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800153sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800154{
Steven Morelandc709dd82019-08-05 20:30:14 -0700155 sp<IBinder> context = getStrongProxyForHandle(0);
156
Steven Moreland4da8fb02020-12-29 22:51:32 +0000157 if (context) {
158 // The root object is special since we get it directly from the driver, it is never
159 // written by Parcell::writeStrongBinder.
160 internal::Stability::markCompilationUnit(context.get());
161 } else {
162 ALOGW("Not able to get context object on %s.", mDriverName.c_str());
Steven Moreland8d93a712020-02-19 15:16:15 -0800163 }
164
Steven Morelandc709dd82019-08-05 20:30:14 -0700165 return context;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800166}
167
Steven Morelandee9df902021-10-14 14:00:08 -0700168void ProcessState::onFork() {
169 // make sure another thread isn't currently retrieving ProcessState
170 gProcessMutex.lock();
171}
172
173void ProcessState::parentPostFork() {
174 gProcessMutex.unlock();
175}
176
177void ProcessState::childPostFork() {
178 // another thread might call fork before gProcess is instantiated, but after
179 // the thread handler is installed
180 if (gProcess) {
181 gProcess->mForked = true;
Steven Morelanddf732ba2022-05-18 22:04:49 +0000182
183 // "O_CLOFORK"
184 close(gProcess->mDriverFD);
185 gProcess->mDriverFD = -1;
Steven Morelandee9df902021-10-14 14:00:08 -0700186 }
187 gProcessMutex.unlock();
188}
189
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800190void ProcessState::startThreadPool()
191{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700192 std::unique_lock<std::mutex> _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800193 if (!mThreadPoolStarted) {
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000194 if (mMaxThreads == 0) {
Steven Moreland3e9debc2023-06-15 00:35:29 +0000195 // see also getThreadPoolMaxTotalThreadCount
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000196 ALOGW("Extra binder thread started, but 0 threads requested. Do not use "
197 "*startThreadPool when zero threads are requested.");
198 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800199 mThreadPoolStarted = true;
200 spawnPooledThread(true);
201 }
202}
203
Steven Moreland61096622020-08-31 23:36:39 +0000204bool ProcessState::becomeContextManager()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700206 std::unique_lock<std::mutex> _l(mLock);
Jeff Browne16986c2011-07-08 18:52:57 -0700207
Steven Moreland4411d712019-07-12 14:02:53 -0700208 flat_binder_object obj {
209 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
210 };
Steven Moreland3085a472018-12-26 13:59:23 -0800211
Steven Moreland4411d712019-07-12 14:02:53 -0700212 int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
Steven Moreland3085a472018-12-26 13:59:23 -0800213
Steven Moreland4411d712019-07-12 14:02:53 -0700214 // fallback to original method
215 if (result != 0) {
216 android_errorWriteLog(0x534e4554, "121035042");
Steven Moreland3085a472018-12-26 13:59:23 -0800217
Hungming Chen28b42522020-08-28 17:29:55 +0800218 int unused = 0;
219 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220 }
Steven Moreland4411d712019-07-12 14:02:53 -0700221
222 if (result == -1) {
Steven Moreland4411d712019-07-12 14:02:53 -0700223 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
224 }
225
226 return result == 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800227}
228
Colin Cross9d45ccc2017-06-20 17:48:33 -0700229// Get references to userspace objects held by the kernel binder driver
230// Writes up to count elements into buf, and returns the total number
231// of references the kernel has, which may be larger than count.
232// buf may be NULL if count is 0. The pointers returned by this method
233// should only be used for debugging and not dereferenced, they may
234// already be invalid.
235ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
236{
Colin Cross9d45ccc2017-06-20 17:48:33 -0700237 binder_node_debug_info info = {};
238
Yi Kongfdd8da92018-06-07 17:52:27 -0700239 uintptr_t* end = buf ? buf + buf_count : nullptr;
Colin Cross9d45ccc2017-06-20 17:48:33 -0700240 size_t count = 0;
241
242 do {
243 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
244 if (result < 0) {
245 return -1;
246 }
247 if (info.ptr != 0) {
248 if (buf && buf < end)
249 *buf++ = info.ptr;
250 count++;
251 if (buf && buf < end)
252 *buf++ = info.cookie;
253 count++;
254 }
255 } while (info.ptr != 0);
256
257 return count;
258}
259
Jon Spivack902e6fc2019-10-18 21:22:37 -0700260// Queries the driver for the current strong reference count of the node
261// that the handle points to. Can only be used by the servicemanager.
262//
263// Returns -1 in case of failure, otherwise the strong reference count.
Steven Morelande8393882020-12-18 02:27:20 +0000264ssize_t ProcessState::getStrongRefCountForNode(const sp<BpBinder>& binder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000265 if (binder->isRpcBinder()) return -1;
266
Jon Spivack902e6fc2019-10-18 21:22:37 -0700267 binder_node_info_for_ref info;
268 memset(&info, 0, sizeof(binder_node_info_for_ref));
269
Steven Moreland99157622021-09-13 16:27:34 -0700270 info.handle = binder->getPrivateAccessor().binderHandle();
Jon Spivack902e6fc2019-10-18 21:22:37 -0700271
272 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
273
274 if (result != OK) {
275 static bool logged = false;
276 if (!logged) {
277 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
278 logged = true;
279 }
280 return -1;
281 }
282
283 return info.strong_count;
284}
285
Steven Moreland7732a092019-01-02 17:54:16 -0800286void ProcessState::setCallRestriction(CallRestriction restriction) {
Steven Moreland28723ae2019-04-01 18:52:30 -0700287 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
288 "Call restrictions must be set before the threadpool is started.");
Steven Moreland7732a092019-01-02 17:54:16 -0800289
290 mCallRestriction = restriction;
291}
292
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800293ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
294{
295 const size_t N=mHandleToObject.size();
296 if (N <= (size_t)handle) {
297 handle_entry e;
Yi Kongfdd8da92018-06-07 17:52:27 -0700298 e.binder = nullptr;
299 e.refs = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800300 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
Yi Kongfdd8da92018-06-07 17:52:27 -0700301 if (err < NO_ERROR) return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800302 }
303 return &mHandleToObject.editItemAt(handle);
304}
305
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000306// see b/166779391: cannot change the VNDK interface, so access like this
307extern sp<BBinder> the_context_object;
308
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800309sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
310{
311 sp<IBinder> result;
312
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700313 std::unique_lock<std::mutex> _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800314
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000315 if (handle == 0 && the_context_object != nullptr) return the_context_object;
316
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800317 handle_entry* e = lookupHandleLocked(handle);
318
Yi Kongfdd8da92018-06-07 17:52:27 -0700319 if (e != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320 // We need to create a new BpBinder if there isn't currently one, OR we
Steven Morelande171d622019-07-17 16:06:01 -0700321 // are unable to acquire a weak reference on this current one. The
322 // attemptIncWeak() is safe because we know the BpBinder destructor will always
323 // call expungeHandle(), which acquires the same lock we are holding now.
324 // We need to do this because there is a race condition between someone
325 // releasing a reference on this BpBinder, and a new reference on its handle
326 // arriving from the driver.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800327 IBinder* b = e->binder;
Yi Kongfdd8da92018-06-07 17:52:27 -0700328 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
Todd Poynora7b0f042013-06-18 17:25:37 -0700329 if (handle == 0) {
330 // Special case for context manager...
331 // The context manager is the only object for which we create
332 // a BpBinder proxy without already holding a reference.
333 // Perform a dummy transaction to ensure the context manager
334 // is registered before we create the first local reference
335 // to it (which will occur when creating the BpBinder).
336 // If a local reference is created for the BpBinder when the
337 // context manager is not present, the driver will fail to
338 // provide a reference to the context manager, but the
339 // driver API does not return status.
340 //
341 // Note that this is not race-free if the context manager
342 // dies while this code runs.
Todd Poynora7b0f042013-06-18 17:25:37 -0700343
Steven Moreland9514b202020-09-21 18:03:27 +0000344 IPCThreadState* ipc = IPCThreadState::self();
345
346 CallRestriction originalCallRestriction = ipc->getCallRestriction();
347 ipc->setCallRestriction(CallRestriction::NONE);
348
Todd Poynora7b0f042013-06-18 17:25:37 -0700349 Parcel data;
Steven Moreland9514b202020-09-21 18:03:27 +0000350 status_t status = ipc->transact(
Yi Kongfdd8da92018-06-07 17:52:27 -0700351 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
Steven Moreland9514b202020-09-21 18:03:27 +0000352
353 ipc->setCallRestriction(originalCallRestriction);
354
Todd Poynora7b0f042013-06-18 17:25:37 -0700355 if (status == DEAD_OBJECT)
Yi Kongfdd8da92018-06-07 17:52:27 -0700356 return nullptr;
Todd Poynora7b0f042013-06-18 17:25:37 -0700357 }
358
Steven Moreland99157622021-09-13 16:27:34 -0700359 sp<BpBinder> b = BpBinder::PrivateAccessor::create(handle);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000360 e->binder = b.get();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800361 if (b) e->refs = b->getWeakRefs();
362 result = b;
363 } else {
364 // This little bit of nastyness is to allow us to add a primary
365 // reference to the remote proxy when this team doesn't have one
366 // but another team is sending the handle to us.
367 result.force_set(b);
368 e->refs->decWeak(this);
369 }
370 }
371
372 return result;
373}
374
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800375void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
376{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700377 std::unique_lock<std::mutex> _l(mLock);
Jooyung Han1b228f42020-01-30 13:41:12 +0900378
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800379 handle_entry* e = lookupHandleLocked(handle);
380
381 // This handle may have already been replaced with a new BpBinder
382 // (if someone failed the AttemptIncWeak() above); we don't want
383 // to overwrite it.
Yi Kongfdd8da92018-06-07 17:52:27 -0700384 if (e && e->binder == binder) e->binder = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800385}
386
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800387String8 ProcessState::makeBinderThreadName() {
388 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
Philip Cuadraa082fa82016-04-08 10:29:14 -0700389 pid_t pid = getpid();
Steven Moreland281abad2022-02-24 22:06:40 +0000390
391 std::string_view driverName = mDriverName.c_str();
392 android::base::ConsumePrefix(&driverName, "/dev/");
393
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800394 String8 name;
Steven Moreland281abad2022-02-24 22:06:40 +0000395 name.appendFormat("%.*s:%d_%X", static_cast<int>(driverName.length()), driverName.data(), pid,
396 s);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800397 return name;
398}
399
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800400void ProcessState::spawnPooledThread(bool isMain)
401{
402 if (mThreadPoolStarted) {
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800403 String8 name = makeBinderThreadName();
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000404 ALOGV("Spawning new pooled thread, name=%s\n", name.c_str());
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000405 sp<Thread> t = sp<PoolThread>::make(isMain);
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000406 t->run(name.c_str());
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +0000407 pthread_mutex_lock(&mThreadCountLock);
Elie Kheirallah47431c12022-04-21 23:46:17 +0000408 mKernelStartedThreads++;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +0000409 pthread_mutex_unlock(&mThreadCountLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800410 }
Steven Moreland3e9debc2023-06-15 00:35:29 +0000411 // TODO: if startThreadPool is called on another thread after the process
412 // starts up, the kernel might think that it already requested those
413 // binder threads, and additional won't be started. This is likely to
414 // cause deadlocks, and it will also cause getThreadPoolMaxTotalThreadCount
415 // to return too high of a value.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800416}
417
Mathias Agopian1b80f792012-04-17 16:11:08 -0700418status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
Steven Moreland1fdb98b2020-03-06 21:42:12 +0000419 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
420 "Binder threadpool cannot be shrunk after starting");
Mathias Agopian1b80f792012-04-17 16:11:08 -0700421 status_t result = NO_ERROR;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700422 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
423 mMaxThreads = maxThreads;
424 } else {
Mathias Agopian1b80f792012-04-17 16:11:08 -0700425 result = -errno;
426 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
427 }
428 return result;
429}
430
Elie Kheirallah47431c12022-04-21 23:46:17 +0000431size_t ProcessState::getThreadPoolMaxTotalThreadCount() const {
Steven Morelandb763b142022-07-13 01:24:24 +0000432 pthread_mutex_lock(&mThreadCountLock);
Sebastian Pickl25c1a3b2023-10-30 08:02:24 +0000433 base::ScopeGuard detachGuard = [&]() { pthread_mutex_unlock(&mThreadCountLock); };
Steven Morelandb763b142022-07-13 01:24:24 +0000434
Elie Kheirallah47431c12022-04-21 23:46:17 +0000435 if (mThreadPoolStarted) {
Steven Moreland3e9debc2023-06-15 00:35:29 +0000436 LOG_ALWAYS_FATAL_IF(mKernelStartedThreads > mMaxThreads + 1,
437 "too many kernel-started threads: %zu > %zu + 1", mKernelStartedThreads,
438 mMaxThreads);
439
440 // calling startThreadPool starts a thread
441 size_t threads = 1;
442
443 // the kernel is configured to start up to mMaxThreads more threads
444 threads += mMaxThreads;
445
446 // Users may call IPCThreadState::joinThreadPool directly. We don't
447 // currently have a way to count this directly (it could be added by
448 // adding a separate private joinKernelThread method in IPCThreadState).
449 // So, if we are in a race between the kernel thread variable being
450 // incremented in this file and mCurrentThreads being incremented
451 // in IPCThreadState, temporarily forget about the extra join threads.
452 // This is okay, because most callers of this method only care about
453 // having 0, 1, or more threads.
454 if (mCurrentThreads > mKernelStartedThreads) {
455 threads += mCurrentThreads - mKernelStartedThreads;
456 }
457
458 return threads;
Elie Kheirallah47431c12022-04-21 23:46:17 +0000459 }
Steven Moreland3e9debc2023-06-15 00:35:29 +0000460
Yifan Hong84bedeb2021-04-21 21:37:17 -0700461 // must not be initialized or maybe has poll thread setup, we
462 // currently don't track this in libbinder
Elie Kheirallah47431c12022-04-21 23:46:17 +0000463 LOG_ALWAYS_FATAL_IF(mKernelStartedThreads != 0,
464 "Expecting 0 kernel started threads but have"
465 " %zu",
466 mKernelStartedThreads);
467 return mCurrentThreads;
Yifan Hong84bedeb2021-04-21 21:37:17 -0700468}
469
Devin Moore4354f712022-12-08 01:44:46 +0000470bool ProcessState::isThreadPoolStarted() const {
471 return mThreadPoolStarted;
472}
473
Carlos Llamas4f886702022-03-07 22:07:03 -0800474#define DRIVER_FEATURES_PATH "/dev/binderfs/features/"
475bool ProcessState::isDriverFeatureEnabled(const DriverFeature feature) {
476 static const char* const names[] = {
477 [static_cast<int>(DriverFeature::ONEWAY_SPAM_DETECTION)] =
478 DRIVER_FEATURES_PATH "oneway_spam_detection",
Carlos Llamasb235b122021-12-20 06:38:44 -0800479 [static_cast<int>(DriverFeature::EXTENDED_ERROR)] =
480 DRIVER_FEATURES_PATH "extended_error",
Carlos Llamas4f886702022-03-07 22:07:03 -0800481 };
482 int fd = open(names[static_cast<int>(feature)], O_RDONLY | O_CLOEXEC);
483 char on;
484 if (fd == -1) {
485 ALOGE_IF(errno != ENOENT, "%s: cannot open %s: %s", __func__,
486 names[static_cast<int>(feature)], strerror(errno));
487 return false;
488 }
489 if (read(fd, &on, sizeof(on)) == -1) {
490 ALOGE("%s: error reading to %s: %s", __func__,
491 names[static_cast<int>(feature)], strerror(errno));
492 return false;
493 }
494 close(fd);
495 return on == '1';
496}
497
Hang Lub185ac02021-03-24 13:17:22 +0800498status_t ProcessState::enableOnewaySpamDetection(bool enable) {
499 uint32_t enableDetection = enable ? 1 : 0;
500 if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
Martijn Coenende0a39e2021-04-22 14:38:46 +0200501 ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
Hang Lub185ac02021-03-24 13:17:22 +0800502 return -errno;
503 }
504 return NO_ERROR;
505}
506
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800507void ProcessState::giveThreadPoolName() {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000508 androidSetThreadName(makeBinderThreadName().c_str());
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800509}
510
Iliyan Malchev32062242017-04-10 14:06:11 -0700511String8 ProcessState::getDriverName() {
512 return mDriverName;
513}
514
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700515static base::unique_fd open_driver(const char* driver) {
516 auto fd = base::unique_fd(open(driver, O_RDWR | O_CLOEXEC));
517 if (!fd.ok()) {
518 PLOGE("Opening '%s' failed", driver);
519 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700520 }
521 int vers = 0;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700522 int result = ioctl(fd.get(), BINDER_VERSION, &vers);
Steven Moreland13a43c92021-08-30 13:21:48 -0700523 if (result == -1) {
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700524 PLOGE("Binder ioctl to obtain version failed");
525 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700526 }
527 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700528 ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)! "
529 "ioctl() return value: %d",
530 vers, BINDER_CURRENT_PROTOCOL_VERSION, result);
531 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700532 }
533 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700534 result = ioctl(fd.get(), BINDER_SET_MAX_THREADS, &maxThreads);
Steven Moreland13a43c92021-08-30 13:21:48 -0700535 if (result == -1) {
536 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
537 }
538 uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700539 result = ioctl(fd.get(), BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
Steven Moreland13a43c92021-08-30 13:21:48 -0700540 if (result == -1) {
Carlos Llamas4f886702022-03-07 22:07:03 -0800541 ALOGE_IF(ProcessState::isDriverFeatureEnabled(
542 ProcessState::DriverFeature::ONEWAY_SPAM_DETECTION),
543 "Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800544 }
545 return fd;
546}
547
Steven Moreland13a43c92021-08-30 13:21:48 -0700548ProcessState::ProcessState(const char* driver)
549 : mDriverName(String8(driver)),
550 mDriverFD(-1),
551 mVMStart(MAP_FAILED),
552 mThreadCountLock(PTHREAD_MUTEX_INITIALIZER),
553 mThreadCountDecrement(PTHREAD_COND_INITIALIZER),
554 mExecutingThreadsCount(0),
555 mWaitingForThreads(0),
556 mMaxThreads(DEFAULT_MAX_BINDER_THREADS),
Elie Kheirallah47431c12022-04-21 23:46:17 +0000557 mCurrentThreads(0),
558 mKernelStartedThreads(0),
Steven Moreland13a43c92021-08-30 13:21:48 -0700559 mStarvationStartTimeMs(0),
Steven Morelandee9df902021-10-14 14:00:08 -0700560 mForked(false),
Steven Moreland13a43c92021-08-30 13:21:48 -0700561 mThreadPoolStarted(false),
562 mThreadPoolSeq(1),
563 mCallRestriction(CallRestriction::NONE) {
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700564 base::unique_fd opened = open_driver(driver);
Steven Moreland13a43c92021-08-30 13:21:48 -0700565
566 if (opened.ok()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800567 // mmap the binder, providing a chunk of virtual address space to receive transactions.
Steven Moreland13a43c92021-08-30 13:21:48 -0700568 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE,
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700569 opened.get(), 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800570 if (mVMStart == MAP_FAILED) {
571 // *sigh*
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700572 ALOGE("Using %s failed: unable to mmap transaction memory.", driver);
573 opened.reset();
Iliyan Malchev32062242017-04-10 14:06:11 -0700574 mDriverName.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800575 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800576 }
Jeff Browne16986c2011-07-08 18:52:57 -0700577
Steven Moreland24bc0d12019-10-11 12:29:20 -0700578#ifdef __ANDROID__
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700579 LOG_ALWAYS_FATAL_IF(!opened.ok(), "Binder driver '%s' could not be opened. Terminating.",
580 driver);
Steven Moreland24bc0d12019-10-11 12:29:20 -0700581#endif
Steven Moreland13a43c92021-08-30 13:21:48 -0700582
583 if (opened.ok()) {
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700584 mDriverFD = opened.release();
Steven Moreland13a43c92021-08-30 13:21:48 -0700585 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800586}
587
588ProcessState::~ProcessState()
589{
zhongjieff405782016-03-09 15:05:04 +0800590 if (mDriverFD >= 0) {
591 if (mVMStart != MAP_FAILED) {
Steven Moreland072cc7e2019-07-12 21:01:54 +0000592 munmap(mVMStart, BINDER_VM_SIZE);
zhongjieff405782016-03-09 15:05:04 +0800593 }
594 close(mDriverFD);
595 }
596 mDriverFD = -1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800597}
Jooyung Han1b228f42020-01-30 13:41:12 +0900598
Steven Moreland61ff8492019-09-26 16:05:45 -0700599} // namespace android