blob: c4dfc13b8824f097e80f581bcb9e83c08cae4cb7 [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>
Andrei Homescu8028ff42022-03-14 22:11:54 +000027#include <utils/AndroidThreads.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080028#include <utils/String8.h>
Andrei Homescu8028ff42022-03-14 22:11:54 +000029#include <utils/Thread.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
Steven Morelanda4853cd2019-07-12 15:44:37 -070031#include "Static.h"
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -070032#include "Utils.h"
Steven Moreland6ba5a252021-05-04 22:49:00 +000033#include "binder_module.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080034
35#include <errno.h>
36#include <fcntl.h>
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +000037#include <pthread.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080038#include <stdio.h>
39#include <stdlib.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080040#include <sys/ioctl.h>
41#include <sys/mman.h>
42#include <sys/stat.h>
Philip Cuadraa082fa82016-04-08 10:29:14 -070043#include <sys/types.h>
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +000044#include <unistd.h>
45#include <mutex>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080046
Steven Moreland072cc7e2019-07-12 21:01:54 +000047#define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
Wale Ogunwale376b8222015-04-13 16:16:10 -070048#define DEFAULT_MAX_BINDER_THREADS 15
Hang Lub185ac02021-03-24 13:17:22 +080049#define DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION 1
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050
Martijn Coenen7bca77a2019-03-13 11:51:08 +000051#ifdef __ANDROID_VNDK__
52const char* kDefaultDriver = "/dev/vndbinder";
53#else
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070054const char* kDefaultDriver = "/dev/binder";
Martijn Coenen7bca77a2019-03-13 11:51:08 +000055#endif
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070056
Philip Cuadraa082fa82016-04-08 10:29:14 -070057// -------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
59namespace android {
Wale Ogunwale376b8222015-04-13 16:16:10 -070060
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000061using namespace android::binder::impl;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070062using android::binder::unique_fd;
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000063
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064class PoolThread : public Thread
65{
66public:
Chih-Hung Hsiehe2347b72016-04-25 15:41:05 -070067 explicit PoolThread(bool isMain)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068 : mIsMain(isMain)
69 {
70 }
Jooyung Han1b228f42020-01-30 13:41:12 +090071
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072protected:
73 virtual bool threadLoop()
74 {
75 IPCThreadState::self()->joinThreadPool(mIsMain);
76 return false;
77 }
Jooyung Han1b228f42020-01-30 13:41:12 +090078
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079 const bool mIsMain;
80};
81
82sp<ProcessState> ProcessState::self()
83{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000084 return init(kDefaultDriver, false /*requireDefault*/);
Martijn Coenen55d871c2017-03-21 15:56:40 -070085}
86
87sp<ProcessState> ProcessState::initWithDriver(const char* driver)
88{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000089 return init(driver, true /*requireDefault*/);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090}
91
Steven Moreland072cc7e2019-07-12 21:01:54 +000092sp<ProcessState> ProcessState::selfOrNull()
93{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000094 return init(nullptr, false /*requireDefault*/);
95}
96
Steven Morelandee9df902021-10-14 14:00:08 -070097[[clang::no_destroy]] static sp<ProcessState> gProcess;
98[[clang::no_destroy]] static std::mutex gProcessMutex;
99
100static void verifyNotForked(bool forked) {
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700101 LOG_ALWAYS_FATAL_IF(forked, "libbinder ProcessState can not be used after fork");
Steven Morelandee9df902021-10-14 14:00:08 -0700102}
103
Steven Moreland9a4278e2023-02-14 01:33:39 +0000104bool ProcessState::isVndservicemanagerEnabled() {
105 return access("/vendor/bin/vndservicemanager", R_OK) == 0;
106}
107
Steven Moreland68275d72023-04-21 22:12:45 +0000108sp<ProcessState> ProcessState::init(const char* driver, bool requireDefault) {
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000109 if (driver == nullptr) {
110 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Morelandee9df902021-10-14 14:00:08 -0700111 if (gProcess) {
112 verifyNotForked(gProcess->mForked);
113 }
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000114 return gProcess;
115 }
116
117 [[clang::no_destroy]] static std::once_flag gProcessOnce;
118 std::call_once(gProcessOnce, [&](){
119 if (access(driver, R_OK) == -1) {
120 ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
121 driver = "/dev/binder";
122 }
123
Steven Moreland9a4278e2023-02-14 01:33:39 +0000124 if (0 == strcmp(driver, "/dev/vndbinder") && !isVndservicemanagerEnabled()) {
125 ALOGE("vndservicemanager is not started on this device, you can save resources/threads "
126 "by not initializing ProcessState with /dev/vndbinder.");
127 }
128
Steven Morelandee9df902021-10-14 14:00:08 -0700129 // we must install these before instantiating the gProcess object,
130 // otherwise this would race with creating it, and there could be the
131 // possibility of an invalid gProcess object forked by another thread
132 // before these are installed
133 int ret = pthread_atfork(ProcessState::onFork, ProcessState::parentPostFork,
134 ProcessState::childPostFork);
135 LOG_ALWAYS_FATAL_IF(ret != 0, "pthread_atfork error %s", strerror(ret));
136
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000137 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000138 gProcess = sp<ProcessState>::make(driver);
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000139 });
140
141 if (requireDefault) {
142 // Detect if we are trying to initialize with a different driver, and
143 // consider that an error. ProcessState will only be initialized once above.
144 LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,
145 "ProcessState was already initialized with %s,"
146 " can't initialize with %s.",
147 gProcess->getDriverName().c_str(), driver);
148 }
149
Steven Morelandee9df902021-10-14 14:00:08 -0700150 verifyNotForked(gProcess->mForked);
Colin Cross9d45ccc2017-06-20 17:48:33 -0700151 return gProcess;
152}
153
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800154sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155{
Steven Morelandc709dd82019-08-05 20:30:14 -0700156 sp<IBinder> context = getStrongProxyForHandle(0);
157
Steven Moreland4da8fb02020-12-29 22:51:32 +0000158 if (context) {
159 // The root object is special since we get it directly from the driver, it is never
160 // written by Parcell::writeStrongBinder.
161 internal::Stability::markCompilationUnit(context.get());
162 } else {
163 ALOGW("Not able to get context object on %s.", mDriverName.c_str());
Steven Moreland8d93a712020-02-19 15:16:15 -0800164 }
165
Steven Morelandc709dd82019-08-05 20:30:14 -0700166 return context;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167}
168
Steven Morelandee9df902021-10-14 14:00:08 -0700169void ProcessState::onFork() {
170 // make sure another thread isn't currently retrieving ProcessState
171 gProcessMutex.lock();
172}
173
174void ProcessState::parentPostFork() {
175 gProcessMutex.unlock();
176}
177
178void ProcessState::childPostFork() {
179 // another thread might call fork before gProcess is instantiated, but after
180 // the thread handler is installed
181 if (gProcess) {
182 gProcess->mForked = true;
Steven Morelanddf732ba2022-05-18 22:04:49 +0000183
184 // "O_CLOFORK"
185 close(gProcess->mDriverFD);
186 gProcess->mDriverFD = -1;
Steven Morelandee9df902021-10-14 14:00:08 -0700187 }
188 gProcessMutex.unlock();
189}
190
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800191void ProcessState::startThreadPool()
192{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700193 std::unique_lock<std::mutex> _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194 if (!mThreadPoolStarted) {
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000195 if (mMaxThreads == 0) {
Steven Moreland3e9debc2023-06-15 00:35:29 +0000196 // see also getThreadPoolMaxTotalThreadCount
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000197 ALOGW("Extra binder thread started, but 0 threads requested. Do not use "
198 "*startThreadPool when zero threads are requested.");
199 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800200 mThreadPoolStarted = true;
201 spawnPooledThread(true);
202 }
203}
204
Steven Moreland61096622020-08-31 23:36:39 +0000205bool ProcessState::becomeContextManager()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700207 std::unique_lock<std::mutex> _l(mLock);
Jeff Browne16986c2011-07-08 18:52:57 -0700208
Steven Moreland4411d712019-07-12 14:02:53 -0700209 flat_binder_object obj {
210 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
211 };
Steven Moreland3085a472018-12-26 13:59:23 -0800212
Steven Moreland4411d712019-07-12 14:02:53 -0700213 int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
Steven Moreland3085a472018-12-26 13:59:23 -0800214
Steven Moreland4411d712019-07-12 14:02:53 -0700215 // fallback to original method
216 if (result != 0) {
217 android_errorWriteLog(0x534e4554, "121035042");
Steven Moreland3085a472018-12-26 13:59:23 -0800218
Hungming Chen28b42522020-08-28 17:29:55 +0800219 int unused = 0;
220 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800221 }
Steven Moreland4411d712019-07-12 14:02:53 -0700222
223 if (result == -1) {
Steven Moreland4411d712019-07-12 14:02:53 -0700224 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
225 }
226
227 return result == 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228}
229
Colin Cross9d45ccc2017-06-20 17:48:33 -0700230// Get references to userspace objects held by the kernel binder driver
231// Writes up to count elements into buf, and returns the total number
232// of references the kernel has, which may be larger than count.
233// buf may be NULL if count is 0. The pointers returned by this method
234// should only be used for debugging and not dereferenced, they may
235// already be invalid.
236ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
237{
Colin Cross9d45ccc2017-06-20 17:48:33 -0700238 binder_node_debug_info info = {};
239
Yi Kongfdd8da92018-06-07 17:52:27 -0700240 uintptr_t* end = buf ? buf + buf_count : nullptr;
Colin Cross9d45ccc2017-06-20 17:48:33 -0700241 size_t count = 0;
242
243 do {
244 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
245 if (result < 0) {
246 return -1;
247 }
248 if (info.ptr != 0) {
249 if (buf && buf < end)
250 *buf++ = info.ptr;
251 count++;
252 if (buf && buf < end)
253 *buf++ = info.cookie;
254 count++;
255 }
256 } while (info.ptr != 0);
257
258 return count;
259}
260
Jon Spivack902e6fc2019-10-18 21:22:37 -0700261// Queries the driver for the current strong reference count of the node
262// that the handle points to. Can only be used by the servicemanager.
263//
264// Returns -1 in case of failure, otherwise the strong reference count.
Steven Morelande8393882020-12-18 02:27:20 +0000265ssize_t ProcessState::getStrongRefCountForNode(const sp<BpBinder>& binder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000266 if (binder->isRpcBinder()) return -1;
267
Jon Spivack902e6fc2019-10-18 21:22:37 -0700268 binder_node_info_for_ref info;
269 memset(&info, 0, sizeof(binder_node_info_for_ref));
270
Steven Moreland99157622021-09-13 16:27:34 -0700271 info.handle = binder->getPrivateAccessor().binderHandle();
Jon Spivack902e6fc2019-10-18 21:22:37 -0700272
273 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
274
275 if (result != OK) {
276 static bool logged = false;
277 if (!logged) {
278 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
279 logged = true;
280 }
281 return -1;
282 }
283
284 return info.strong_count;
285}
286
Steven Moreland7732a092019-01-02 17:54:16 -0800287void ProcessState::setCallRestriction(CallRestriction restriction) {
Steven Moreland28723ae2019-04-01 18:52:30 -0700288 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
289 "Call restrictions must be set before the threadpool is started.");
Steven Moreland7732a092019-01-02 17:54:16 -0800290
291 mCallRestriction = restriction;
292}
293
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800294ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
295{
296 const size_t N=mHandleToObject.size();
297 if (N <= (size_t)handle) {
298 handle_entry e;
Yi Kongfdd8da92018-06-07 17:52:27 -0700299 e.binder = nullptr;
300 e.refs = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800301 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
Yi Kongfdd8da92018-06-07 17:52:27 -0700302 if (err < NO_ERROR) return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800303 }
304 return &mHandleToObject.editItemAt(handle);
305}
306
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000307// see b/166779391: cannot change the VNDK interface, so access like this
308extern sp<BBinder> the_context_object;
309
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800310sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
311{
312 sp<IBinder> result;
313
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700314 std::unique_lock<std::mutex> _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800315
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000316 if (handle == 0 && the_context_object != nullptr) return the_context_object;
317
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800318 handle_entry* e = lookupHandleLocked(handle);
319
Yi Kongfdd8da92018-06-07 17:52:27 -0700320 if (e != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800321 // We need to create a new BpBinder if there isn't currently one, OR we
Steven Morelande171d622019-07-17 16:06:01 -0700322 // are unable to acquire a weak reference on this current one. The
323 // attemptIncWeak() is safe because we know the BpBinder destructor will always
324 // call expungeHandle(), which acquires the same lock we are holding now.
325 // We need to do this because there is a race condition between someone
326 // releasing a reference on this BpBinder, and a new reference on its handle
327 // arriving from the driver.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800328 IBinder* b = e->binder;
Yi Kongfdd8da92018-06-07 17:52:27 -0700329 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
Todd Poynora7b0f042013-06-18 17:25:37 -0700330 if (handle == 0) {
331 // Special case for context manager...
332 // The context manager is the only object for which we create
333 // a BpBinder proxy without already holding a reference.
334 // Perform a dummy transaction to ensure the context manager
335 // is registered before we create the first local reference
336 // to it (which will occur when creating the BpBinder).
337 // If a local reference is created for the BpBinder when the
338 // context manager is not present, the driver will fail to
339 // provide a reference to the context manager, but the
340 // driver API does not return status.
341 //
342 // Note that this is not race-free if the context manager
343 // dies while this code runs.
Todd Poynora7b0f042013-06-18 17:25:37 -0700344
Steven Moreland9514b202020-09-21 18:03:27 +0000345 IPCThreadState* ipc = IPCThreadState::self();
346
347 CallRestriction originalCallRestriction = ipc->getCallRestriction();
348 ipc->setCallRestriction(CallRestriction::NONE);
349
Todd Poynora7b0f042013-06-18 17:25:37 -0700350 Parcel data;
Steven Moreland9514b202020-09-21 18:03:27 +0000351 status_t status = ipc->transact(
Yi Kongfdd8da92018-06-07 17:52:27 -0700352 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
Steven Moreland9514b202020-09-21 18:03:27 +0000353
354 ipc->setCallRestriction(originalCallRestriction);
355
Todd Poynora7b0f042013-06-18 17:25:37 -0700356 if (status == DEAD_OBJECT)
Yi Kongfdd8da92018-06-07 17:52:27 -0700357 return nullptr;
Todd Poynora7b0f042013-06-18 17:25:37 -0700358 }
359
Steven Moreland99157622021-09-13 16:27:34 -0700360 sp<BpBinder> b = BpBinder::PrivateAccessor::create(handle);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000361 e->binder = b.get();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800362 if (b) e->refs = b->getWeakRefs();
363 result = b;
364 } else {
365 // This little bit of nastyness is to allow us to add a primary
366 // reference to the remote proxy when this team doesn't have one
367 // but another team is sending the handle to us.
368 result.force_set(b);
369 e->refs->decWeak(this);
370 }
371 }
372
373 return result;
374}
375
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
377{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700378 std::unique_lock<std::mutex> _l(mLock);
Jooyung Han1b228f42020-01-30 13:41:12 +0900379
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380 handle_entry* e = lookupHandleLocked(handle);
381
382 // This handle may have already been replaced with a new BpBinder
383 // (if someone failed the AttemptIncWeak() above); we don't want
384 // to overwrite it.
Yi Kongfdd8da92018-06-07 17:52:27 -0700385 if (e && e->binder == binder) e->binder = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800386}
387
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800388String8 ProcessState::makeBinderThreadName() {
Frederick Maylea9675a72024-08-05 14:21:53 -0700389 int32_t s = mThreadPoolSeq.fetch_add(1, std::memory_order_release);
Philip Cuadraa082fa82016-04-08 10:29:14 -0700390 pid_t pid = getpid();
Steven Moreland281abad2022-02-24 22:06:40 +0000391
392 std::string_view driverName = mDriverName.c_str();
393 android::base::ConsumePrefix(&driverName, "/dev/");
394
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800395 String8 name;
Steven Moreland281abad2022-02-24 22:06:40 +0000396 name.appendFormat("%.*s:%d_%X", static_cast<int>(driverName.length()), driverName.data(), pid,
397 s);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800398 return name;
399}
400
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401void ProcessState::spawnPooledThread(bool isMain)
402{
403 if (mThreadPoolStarted) {
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800404 String8 name = makeBinderThreadName();
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000405 ALOGV("Spawning new pooled thread, name=%s\n", name.c_str());
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000406 sp<Thread> t = sp<PoolThread>::make(isMain);
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000407 t->run(name.c_str());
Elie Kheirallah47431c12022-04-21 23:46:17 +0000408 mKernelStartedThreads++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409 }
Steven Moreland3e9debc2023-06-15 00:35:29 +0000410 // TODO: if startThreadPool is called on another thread after the process
411 // starts up, the kernel might think that it already requested those
412 // binder threads, and additional won't be started. This is likely to
413 // cause deadlocks, and it will also cause getThreadPoolMaxTotalThreadCount
414 // to return too high of a value.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415}
416
Mathias Agopian1b80f792012-04-17 16:11:08 -0700417status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
Steven Moreland1fdb98b2020-03-06 21:42:12 +0000418 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
419 "Binder threadpool cannot be shrunk after starting");
Mathias Agopian1b80f792012-04-17 16:11:08 -0700420 status_t result = NO_ERROR;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700421 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
422 mMaxThreads = maxThreads;
423 } else {
Mathias Agopian1b80f792012-04-17 16:11:08 -0700424 result = -errno;
425 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
426 }
427 return result;
428}
429
Elie Kheirallah47431c12022-04-21 23:46:17 +0000430size_t ProcessState::getThreadPoolMaxTotalThreadCount() const {
Frederick Mayle908b09c2024-08-05 14:10:40 -0700431 // Need to read `mKernelStartedThreads` before `mThreadPoolStarted` (with
432 // non-relaxed memory ordering) to avoid a race like the following:
433 //
434 // thread A: if (mThreadPoolStarted) { // evaluates false
435 // thread B: mThreadPoolStarted = true;
436 // thread B: mKernelStartedThreads++;
437 // thread A: size_t kernelStarted = mKernelStartedThreads;
438 // thread A: LOG_ALWAYS_FATAL_IF(kernelStarted != 0, ...);
439 size_t kernelStarted = mKernelStartedThreads;
440
Elie Kheirallah47431c12022-04-21 23:46:17 +0000441 if (mThreadPoolStarted) {
Frederick Mayle263507f2024-05-30 14:54:27 -0700442 size_t max = mMaxThreads;
443 size_t current = mCurrentThreads;
444
445 LOG_ALWAYS_FATAL_IF(kernelStarted > max + 1,
446 "too many kernel-started threads: %zu > %zu + 1", kernelStarted, max);
Steven Moreland3e9debc2023-06-15 00:35:29 +0000447
448 // calling startThreadPool starts a thread
449 size_t threads = 1;
450
451 // the kernel is configured to start up to mMaxThreads more threads
Frederick Mayle263507f2024-05-30 14:54:27 -0700452 threads += max;
Steven Moreland3e9debc2023-06-15 00:35:29 +0000453
454 // Users may call IPCThreadState::joinThreadPool directly. We don't
455 // currently have a way to count this directly (it could be added by
456 // adding a separate private joinKernelThread method in IPCThreadState).
457 // So, if we are in a race between the kernel thread variable being
458 // incremented in this file and mCurrentThreads being incremented
459 // in IPCThreadState, temporarily forget about the extra join threads.
460 // This is okay, because most callers of this method only care about
461 // having 0, 1, or more threads.
Frederick Mayle263507f2024-05-30 14:54:27 -0700462 if (current > kernelStarted) {
463 threads += current - kernelStarted;
Steven Moreland3e9debc2023-06-15 00:35:29 +0000464 }
465
466 return threads;
Elie Kheirallah47431c12022-04-21 23:46:17 +0000467 }
Steven Moreland3e9debc2023-06-15 00:35:29 +0000468
Yifan Hong84bedeb2021-04-21 21:37:17 -0700469 // must not be initialized or maybe has poll thread setup, we
470 // currently don't track this in libbinder
Frederick Mayle263507f2024-05-30 14:54:27 -0700471 LOG_ALWAYS_FATAL_IF(kernelStarted != 0, "Expecting 0 kernel started threads but have %zu",
472 kernelStarted);
Elie Kheirallah47431c12022-04-21 23:46:17 +0000473 return mCurrentThreads;
Yifan Hong84bedeb2021-04-21 21:37:17 -0700474}
475
Devin Moore4354f712022-12-08 01:44:46 +0000476bool ProcessState::isThreadPoolStarted() const {
477 return mThreadPoolStarted;
478}
479
Carlos Llamas4f886702022-03-07 22:07:03 -0800480#define DRIVER_FEATURES_PATH "/dev/binderfs/features/"
481bool ProcessState::isDriverFeatureEnabled(const DriverFeature feature) {
482 static const char* const names[] = {
483 [static_cast<int>(DriverFeature::ONEWAY_SPAM_DETECTION)] =
484 DRIVER_FEATURES_PATH "oneway_spam_detection",
Carlos Llamasb235b122021-12-20 06:38:44 -0800485 [static_cast<int>(DriverFeature::EXTENDED_ERROR)] =
486 DRIVER_FEATURES_PATH "extended_error",
Carlos Llamas4f886702022-03-07 22:07:03 -0800487 };
488 int fd = open(names[static_cast<int>(feature)], O_RDONLY | O_CLOEXEC);
489 char on;
490 if (fd == -1) {
491 ALOGE_IF(errno != ENOENT, "%s: cannot open %s: %s", __func__,
492 names[static_cast<int>(feature)], strerror(errno));
493 return false;
494 }
495 if (read(fd, &on, sizeof(on)) == -1) {
496 ALOGE("%s: error reading to %s: %s", __func__,
497 names[static_cast<int>(feature)], strerror(errno));
wangmingming1dec7b1e2024-02-06 10:17:07 +0800498 close(fd);
Carlos Llamas4f886702022-03-07 22:07:03 -0800499 return false;
500 }
501 close(fd);
502 return on == '1';
503}
504
Hang Lub185ac02021-03-24 13:17:22 +0800505status_t ProcessState::enableOnewaySpamDetection(bool enable) {
506 uint32_t enableDetection = enable ? 1 : 0;
507 if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
Martijn Coenende0a39e2021-04-22 14:38:46 +0200508 ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
Hang Lub185ac02021-03-24 13:17:22 +0800509 return -errno;
510 }
511 return NO_ERROR;
512}
513
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800514void ProcessState::giveThreadPoolName() {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000515 androidSetThreadName(makeBinderThreadName().c_str());
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800516}
517
Iliyan Malchev32062242017-04-10 14:06:11 -0700518String8 ProcessState::getDriverName() {
519 return mDriverName;
520}
521
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000522static unique_fd open_driver(const char* driver, String8* error) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700523 auto fd = unique_fd(open(driver, O_RDWR | O_CLOEXEC));
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700524 if (!fd.ok()) {
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000525 error->appendFormat("%d (%s) Opening '%s' failed", errno, strerror(errno), driver);
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700526 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700527 }
528 int vers = 0;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700529 int result = ioctl(fd.get(), BINDER_VERSION, &vers);
Steven Moreland13a43c92021-08-30 13:21:48 -0700530 if (result == -1) {
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000531 error->appendFormat("%d (%s) Binder ioctl to obtain version failed", errno,
532 strerror(errno));
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700533 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700534 }
535 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000536 error->appendFormat("Binder driver protocol(%d) does not match user space protocol(%d)! "
537 "ioctl() return value: %d",
538 vers, BINDER_CURRENT_PROTOCOL_VERSION, result);
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700539 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700540 }
541 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700542 result = ioctl(fd.get(), BINDER_SET_MAX_THREADS, &maxThreads);
Steven Moreland13a43c92021-08-30 13:21:48 -0700543 if (result == -1) {
544 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
545 }
546 uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700547 result = ioctl(fd.get(), BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
Steven Moreland13a43c92021-08-30 13:21:48 -0700548 if (result == -1) {
Carlos Llamas4f886702022-03-07 22:07:03 -0800549 ALOGE_IF(ProcessState::isDriverFeatureEnabled(
550 ProcessState::DriverFeature::ONEWAY_SPAM_DETECTION),
551 "Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800552 }
553 return fd;
554}
555
Steven Moreland13a43c92021-08-30 13:21:48 -0700556ProcessState::ProcessState(const char* driver)
557 : mDriverName(String8(driver)),
558 mDriverFD(-1),
559 mVMStart(MAP_FAILED),
Steven Moreland13a43c92021-08-30 13:21:48 -0700560 mExecutingThreadsCount(0),
Steven Moreland13a43c92021-08-30 13:21:48 -0700561 mMaxThreads(DEFAULT_MAX_BINDER_THREADS),
Elie Kheirallah47431c12022-04-21 23:46:17 +0000562 mCurrentThreads(0),
563 mKernelStartedThreads(0),
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700564 mStarvationStartTime(never()),
Steven Morelandee9df902021-10-14 14:00:08 -0700565 mForked(false),
Steven Moreland13a43c92021-08-30 13:21:48 -0700566 mThreadPoolStarted(false),
567 mThreadPoolSeq(1),
568 mCallRestriction(CallRestriction::NONE) {
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000569 String8 error;
570 unique_fd opened = open_driver(driver, &error);
Steven Moreland13a43c92021-08-30 13:21:48 -0700571
572 if (opened.ok()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800573 // mmap the binder, providing a chunk of virtual address space to receive transactions.
Steven Moreland13a43c92021-08-30 13:21:48 -0700574 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE,
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700575 opened.get(), 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800576 if (mVMStart == MAP_FAILED) {
577 // *sigh*
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700578 ALOGE("Using %s failed: unable to mmap transaction memory.", driver);
579 opened.reset();
Iliyan Malchev32062242017-04-10 14:06:11 -0700580 mDriverName.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800581 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800582 }
Jeff Browne16986c2011-07-08 18:52:57 -0700583
Steven Moreland24bc0d12019-10-11 12:29:20 -0700584#ifdef __ANDROID__
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000585 LOG_ALWAYS_FATAL_IF(!opened.ok(),
586 "Binder driver '%s' could not be opened. Error: %s. Terminating.",
Steven Morelandd3e6cda2024-08-06 20:01:13 +0000587 driver, error.c_str());
Steven Moreland24bc0d12019-10-11 12:29:20 -0700588#endif
Steven Moreland13a43c92021-08-30 13:21:48 -0700589
590 if (opened.ok()) {
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700591 mDriverFD = opened.release();
Steven Moreland13a43c92021-08-30 13:21:48 -0700592 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800593}
594
595ProcessState::~ProcessState()
596{
zhongjieff405782016-03-09 15:05:04 +0800597 if (mDriverFD >= 0) {
598 if (mVMStart != MAP_FAILED) {
Steven Moreland072cc7e2019-07-12 21:01:54 +0000599 munmap(mVMStart, BINDER_VM_SIZE);
zhongjieff405782016-03-09 15:05:04 +0800600 }
601 close(mDriverFD);
602 }
603 mDriverFD = -1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800604}
Jooyung Han1b228f42020-01-30 13:41:12 +0900605
Steven Moreland61ff8492019-09-26 16:05:45 -0700606} // namespace android