blob: 5f1f50672a6502f8e641f9634be4c45978e5fa89 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "ProcessState"
18
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070019#include <binder/ProcessState.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020
Steven Moreland13a43c92021-08-30 13:21:48 -070021#include <android-base/result.h>
Steven Morelandb763b142022-07-13 01:24:24 +000022#include <android-base/scopeguard.h>
Steven Moreland281abad2022-02-24 22:06:40 +000023#include <android-base/strings.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070024#include <binder/BpBinder.h>
25#include <binder/IPCThreadState.h>
Steven Moreland2716e112018-02-23 14:57:20 -080026#include <binder/IServiceManager.h>
Steven Morelandc709dd82019-08-05 20:30:14 -070027#include <binder/Stability.h>
Steven Moreland2716e112018-02-23 14:57:20 -080028#include <cutils/atomic.h>
Andrei Homescu8028ff42022-03-14 22:11:54 +000029#include <utils/AndroidThreads.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030#include <utils/Log.h>
31#include <utils/String8.h>
Andrei Homescu8028ff42022-03-14 22:11:54 +000032#include <utils/Thread.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Steven Morelanda4853cd2019-07-12 15:44:37 -070034#include "Static.h"
Steven Moreland6ba5a252021-05-04 22:49:00 +000035#include "binder_module.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036
37#include <errno.h>
38#include <fcntl.h>
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +000039#include <pthread.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080040#include <stdio.h>
41#include <stdlib.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080042#include <sys/ioctl.h>
43#include <sys/mman.h>
44#include <sys/stat.h>
Philip Cuadraa082fa82016-04-08 10:29:14 -070045#include <sys/types.h>
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +000046#include <unistd.h>
47#include <mutex>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080048
Steven Moreland072cc7e2019-07-12 21:01:54 +000049#define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
Wale Ogunwale376b8222015-04-13 16:16:10 -070050#define DEFAULT_MAX_BINDER_THREADS 15
Hang Lub185ac02021-03-24 13:17:22 +080051#define DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION 1
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080052
Martijn Coenen7bca77a2019-03-13 11:51:08 +000053#ifdef __ANDROID_VNDK__
54const char* kDefaultDriver = "/dev/vndbinder";
55#else
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070056const char* kDefaultDriver = "/dev/binder";
Martijn Coenen7bca77a2019-03-13 11:51:08 +000057#endif
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070058
Philip Cuadraa082fa82016-04-08 10:29:14 -070059// -------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
61namespace android {
Wale Ogunwale376b8222015-04-13 16:16:10 -070062
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063class PoolThread : public Thread
64{
65public:
Chih-Hung Hsiehe2347b72016-04-25 15:41:05 -070066 explicit PoolThread(bool isMain)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067 : mIsMain(isMain)
68 {
69 }
Jooyung Han1b228f42020-01-30 13:41:12 +090070
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071protected:
72 virtual bool threadLoop()
73 {
74 IPCThreadState::self()->joinThreadPool(mIsMain);
75 return false;
76 }
Jooyung Han1b228f42020-01-30 13:41:12 +090077
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078 const bool mIsMain;
79};
80
81sp<ProcessState> ProcessState::self()
82{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000083 return init(kDefaultDriver, false /*requireDefault*/);
Martijn Coenen55d871c2017-03-21 15:56:40 -070084}
85
86sp<ProcessState> ProcessState::initWithDriver(const char* driver)
87{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000088 return init(driver, true /*requireDefault*/);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089}
90
Steven Moreland072cc7e2019-07-12 21:01:54 +000091sp<ProcessState> ProcessState::selfOrNull()
92{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000093 return init(nullptr, false /*requireDefault*/);
94}
95
Steven Morelandee9df902021-10-14 14:00:08 -070096[[clang::no_destroy]] static sp<ProcessState> gProcess;
97[[clang::no_destroy]] static std::mutex gProcessMutex;
98
99static void verifyNotForked(bool forked) {
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700100 LOG_ALWAYS_FATAL_IF(forked, "libbinder ProcessState can not be used after fork");
Steven Morelandee9df902021-10-14 14:00:08 -0700101}
102
Steven Moreland9a4278e2023-02-14 01:33:39 +0000103bool ProcessState::isVndservicemanagerEnabled() {
104 return access("/vendor/bin/vndservicemanager", R_OK) == 0;
105}
106
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000107sp<ProcessState> ProcessState::init(const char *driver, bool requireDefault)
108{
Steven Moreland49c39362022-05-13 20:10:24 +0000109#ifdef BINDER_IPC_32BIT
110 LOG_ALWAYS_FATAL("32-bit binder IPC is not supported for new devices starting in Android P. If "
111 "you do need to use this mode, please see b/232423610 or file an issue with "
112 "AOSP upstream as otherwise this will be removed soon.");
113#endif
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000114
115 if (driver == nullptr) {
116 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Morelandee9df902021-10-14 14:00:08 -0700117 if (gProcess) {
118 verifyNotForked(gProcess->mForked);
119 }
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000120 return gProcess;
121 }
122
123 [[clang::no_destroy]] static std::once_flag gProcessOnce;
124 std::call_once(gProcessOnce, [&](){
125 if (access(driver, R_OK) == -1) {
126 ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
127 driver = "/dev/binder";
128 }
129
Steven Moreland9a4278e2023-02-14 01:33:39 +0000130 if (0 == strcmp(driver, "/dev/vndbinder") && !isVndservicemanagerEnabled()) {
131 ALOGE("vndservicemanager is not started on this device, you can save resources/threads "
132 "by not initializing ProcessState with /dev/vndbinder.");
133 }
134
Steven Morelandee9df902021-10-14 14:00:08 -0700135 // we must install these before instantiating the gProcess object,
136 // otherwise this would race with creating it, and there could be the
137 // possibility of an invalid gProcess object forked by another thread
138 // before these are installed
139 int ret = pthread_atfork(ProcessState::onFork, ProcessState::parentPostFork,
140 ProcessState::childPostFork);
141 LOG_ALWAYS_FATAL_IF(ret != 0, "pthread_atfork error %s", strerror(ret));
142
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000143 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000144 gProcess = sp<ProcessState>::make(driver);
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000145 });
146
147 if (requireDefault) {
148 // Detect if we are trying to initialize with a different driver, and
149 // consider that an error. ProcessState will only be initialized once above.
150 LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,
151 "ProcessState was already initialized with %s,"
152 " can't initialize with %s.",
153 gProcess->getDriverName().c_str(), driver);
154 }
155
Steven Morelandee9df902021-10-14 14:00:08 -0700156 verifyNotForked(gProcess->mForked);
Colin Cross9d45ccc2017-06-20 17:48:33 -0700157 return gProcess;
158}
159
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800160sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161{
Steven Morelandc709dd82019-08-05 20:30:14 -0700162 sp<IBinder> context = getStrongProxyForHandle(0);
163
Steven Moreland4da8fb02020-12-29 22:51:32 +0000164 if (context) {
165 // The root object is special since we get it directly from the driver, it is never
166 // written by Parcell::writeStrongBinder.
167 internal::Stability::markCompilationUnit(context.get());
168 } else {
169 ALOGW("Not able to get context object on %s.", mDriverName.c_str());
Steven Moreland8d93a712020-02-19 15:16:15 -0800170 }
171
Steven Morelandc709dd82019-08-05 20:30:14 -0700172 return context;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173}
174
Steven Morelandee9df902021-10-14 14:00:08 -0700175void ProcessState::onFork() {
176 // make sure another thread isn't currently retrieving ProcessState
177 gProcessMutex.lock();
178}
179
180void ProcessState::parentPostFork() {
181 gProcessMutex.unlock();
182}
183
184void ProcessState::childPostFork() {
185 // another thread might call fork before gProcess is instantiated, but after
186 // the thread handler is installed
187 if (gProcess) {
188 gProcess->mForked = true;
Steven Morelanddf732ba2022-05-18 22:04:49 +0000189
190 // "O_CLOFORK"
191 close(gProcess->mDriverFD);
192 gProcess->mDriverFD = -1;
Steven Morelandee9df902021-10-14 14:00:08 -0700193 }
194 gProcessMutex.unlock();
195}
196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197void ProcessState::startThreadPool()
198{
199 AutoMutex _l(mLock);
200 if (!mThreadPoolStarted) {
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000201 if (mMaxThreads == 0) {
202 ALOGW("Extra binder thread started, but 0 threads requested. Do not use "
203 "*startThreadPool when zero threads are requested.");
204 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205 mThreadPoolStarted = true;
206 spawnPooledThread(true);
207 }
208}
209
Steven Moreland61096622020-08-31 23:36:39 +0000210bool ProcessState::becomeContextManager()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800211{
Steven Moreland4411d712019-07-12 14:02:53 -0700212 AutoMutex _l(mLock);
Jeff Browne16986c2011-07-08 18:52:57 -0700213
Steven Moreland4411d712019-07-12 14:02:53 -0700214 flat_binder_object obj {
215 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
216 };
Steven Moreland3085a472018-12-26 13:59:23 -0800217
Steven Moreland4411d712019-07-12 14:02:53 -0700218 int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
Steven Moreland3085a472018-12-26 13:59:23 -0800219
Steven Moreland4411d712019-07-12 14:02:53 -0700220 // fallback to original method
221 if (result != 0) {
222 android_errorWriteLog(0x534e4554, "121035042");
Steven Moreland3085a472018-12-26 13:59:23 -0800223
Hungming Chen28b42522020-08-28 17:29:55 +0800224 int unused = 0;
225 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226 }
Steven Moreland4411d712019-07-12 14:02:53 -0700227
228 if (result == -1) {
Steven Moreland4411d712019-07-12 14:02:53 -0700229 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
230 }
231
232 return result == 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233}
234
Colin Cross9d45ccc2017-06-20 17:48:33 -0700235// Get references to userspace objects held by the kernel binder driver
236// Writes up to count elements into buf, and returns the total number
237// of references the kernel has, which may be larger than count.
238// buf may be NULL if count is 0. The pointers returned by this method
239// should only be used for debugging and not dereferenced, they may
240// already be invalid.
241ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
242{
Colin Cross9d45ccc2017-06-20 17:48:33 -0700243 binder_node_debug_info info = {};
244
Yi Kongfdd8da92018-06-07 17:52:27 -0700245 uintptr_t* end = buf ? buf + buf_count : nullptr;
Colin Cross9d45ccc2017-06-20 17:48:33 -0700246 size_t count = 0;
247
248 do {
249 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
250 if (result < 0) {
251 return -1;
252 }
253 if (info.ptr != 0) {
254 if (buf && buf < end)
255 *buf++ = info.ptr;
256 count++;
257 if (buf && buf < end)
258 *buf++ = info.cookie;
259 count++;
260 }
261 } while (info.ptr != 0);
262
263 return count;
264}
265
Jon Spivack902e6fc2019-10-18 21:22:37 -0700266// Queries the driver for the current strong reference count of the node
267// that the handle points to. Can only be used by the servicemanager.
268//
269// Returns -1 in case of failure, otherwise the strong reference count.
Steven Morelande8393882020-12-18 02:27:20 +0000270ssize_t ProcessState::getStrongRefCountForNode(const sp<BpBinder>& binder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000271 if (binder->isRpcBinder()) return -1;
272
Jon Spivack902e6fc2019-10-18 21:22:37 -0700273 binder_node_info_for_ref info;
274 memset(&info, 0, sizeof(binder_node_info_for_ref));
275
Steven Moreland99157622021-09-13 16:27:34 -0700276 info.handle = binder->getPrivateAccessor().binderHandle();
Jon Spivack902e6fc2019-10-18 21:22:37 -0700277
278 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
279
280 if (result != OK) {
281 static bool logged = false;
282 if (!logged) {
283 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
284 logged = true;
285 }
286 return -1;
287 }
288
289 return info.strong_count;
290}
291
Steven Moreland7732a092019-01-02 17:54:16 -0800292void ProcessState::setCallRestriction(CallRestriction restriction) {
Steven Moreland28723ae2019-04-01 18:52:30 -0700293 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
294 "Call restrictions must be set before the threadpool is started.");
Steven Moreland7732a092019-01-02 17:54:16 -0800295
296 mCallRestriction = restriction;
297}
298
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
300{
301 const size_t N=mHandleToObject.size();
302 if (N <= (size_t)handle) {
303 handle_entry e;
Yi Kongfdd8da92018-06-07 17:52:27 -0700304 e.binder = nullptr;
305 e.refs = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800306 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
Yi Kongfdd8da92018-06-07 17:52:27 -0700307 if (err < NO_ERROR) return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800308 }
309 return &mHandleToObject.editItemAt(handle);
310}
311
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000312// see b/166779391: cannot change the VNDK interface, so access like this
313extern sp<BBinder> the_context_object;
314
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800315sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
316{
317 sp<IBinder> result;
318
319 AutoMutex _l(mLock);
320
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000321 if (handle == 0 && the_context_object != nullptr) return the_context_object;
322
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800323 handle_entry* e = lookupHandleLocked(handle);
324
Yi Kongfdd8da92018-06-07 17:52:27 -0700325 if (e != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326 // We need to create a new BpBinder if there isn't currently one, OR we
Steven Morelande171d622019-07-17 16:06:01 -0700327 // are unable to acquire a weak reference on this current one. The
328 // attemptIncWeak() is safe because we know the BpBinder destructor will always
329 // call expungeHandle(), which acquires the same lock we are holding now.
330 // We need to do this because there is a race condition between someone
331 // releasing a reference on this BpBinder, and a new reference on its handle
332 // arriving from the driver.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800333 IBinder* b = e->binder;
Yi Kongfdd8da92018-06-07 17:52:27 -0700334 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
Todd Poynora7b0f042013-06-18 17:25:37 -0700335 if (handle == 0) {
336 // Special case for context manager...
337 // The context manager is the only object for which we create
338 // a BpBinder proxy without already holding a reference.
339 // Perform a dummy transaction to ensure the context manager
340 // is registered before we create the first local reference
341 // to it (which will occur when creating the BpBinder).
342 // If a local reference is created for the BpBinder when the
343 // context manager is not present, the driver will fail to
344 // provide a reference to the context manager, but the
345 // driver API does not return status.
346 //
347 // Note that this is not race-free if the context manager
348 // dies while this code runs.
Todd Poynora7b0f042013-06-18 17:25:37 -0700349
Steven Moreland9514b202020-09-21 18:03:27 +0000350 IPCThreadState* ipc = IPCThreadState::self();
351
352 CallRestriction originalCallRestriction = ipc->getCallRestriction();
353 ipc->setCallRestriction(CallRestriction::NONE);
354
Todd Poynora7b0f042013-06-18 17:25:37 -0700355 Parcel data;
Steven Moreland9514b202020-09-21 18:03:27 +0000356 status_t status = ipc->transact(
Yi Kongfdd8da92018-06-07 17:52:27 -0700357 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
Steven Moreland9514b202020-09-21 18:03:27 +0000358
359 ipc->setCallRestriction(originalCallRestriction);
360
Todd Poynora7b0f042013-06-18 17:25:37 -0700361 if (status == DEAD_OBJECT)
Yi Kongfdd8da92018-06-07 17:52:27 -0700362 return nullptr;
Todd Poynora7b0f042013-06-18 17:25:37 -0700363 }
364
Steven Moreland99157622021-09-13 16:27:34 -0700365 sp<BpBinder> b = BpBinder::PrivateAccessor::create(handle);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000366 e->binder = b.get();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800367 if (b) e->refs = b->getWeakRefs();
368 result = b;
369 } else {
370 // This little bit of nastyness is to allow us to add a primary
371 // reference to the remote proxy when this team doesn't have one
372 // but another team is sending the handle to us.
373 result.force_set(b);
374 e->refs->decWeak(this);
375 }
376 }
377
378 return result;
379}
380
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
382{
383 AutoMutex _l(mLock);
Jooyung Han1b228f42020-01-30 13:41:12 +0900384
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800385 handle_entry* e = lookupHandleLocked(handle);
386
387 // This handle may have already been replaced with a new BpBinder
388 // (if someone failed the AttemptIncWeak() above); we don't want
389 // to overwrite it.
Yi Kongfdd8da92018-06-07 17:52:27 -0700390 if (e && e->binder == binder) e->binder = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800391}
392
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800393String8 ProcessState::makeBinderThreadName() {
394 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
Philip Cuadraa082fa82016-04-08 10:29:14 -0700395 pid_t pid = getpid();
Steven Moreland281abad2022-02-24 22:06:40 +0000396
397 std::string_view driverName = mDriverName.c_str();
398 android::base::ConsumePrefix(&driverName, "/dev/");
399
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800400 String8 name;
Steven Moreland281abad2022-02-24 22:06:40 +0000401 name.appendFormat("%.*s:%d_%X", static_cast<int>(driverName.length()), driverName.data(), pid,
402 s);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800403 return name;
404}
405
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800406void ProcessState::spawnPooledThread(bool isMain)
407{
408 if (mThreadPoolStarted) {
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800409 String8 name = makeBinderThreadName();
410 ALOGV("Spawning new pooled thread, name=%s\n", name.string());
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000411 sp<Thread> t = sp<PoolThread>::make(isMain);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800412 t->run(name.string());
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +0000413 pthread_mutex_lock(&mThreadCountLock);
Elie Kheirallah47431c12022-04-21 23:46:17 +0000414 mKernelStartedThreads++;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +0000415 pthread_mutex_unlock(&mThreadCountLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800416 }
417}
418
Mathias Agopian1b80f792012-04-17 16:11:08 -0700419status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
Steven Moreland1fdb98b2020-03-06 21:42:12 +0000420 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
421 "Binder threadpool cannot be shrunk after starting");
Mathias Agopian1b80f792012-04-17 16:11:08 -0700422 status_t result = NO_ERROR;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700423 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
424 mMaxThreads = maxThreads;
425 } else {
Mathias Agopian1b80f792012-04-17 16:11:08 -0700426 result = -errno;
427 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
428 }
429 return result;
430}
431
Elie Kheirallah47431c12022-04-21 23:46:17 +0000432size_t ProcessState::getThreadPoolMaxTotalThreadCount() const {
Steven Morelandb763b142022-07-13 01:24:24 +0000433 pthread_mutex_lock(&mThreadCountLock);
434 base::ScopeGuard detachGuard = [&]() { pthread_mutex_unlock(&mThreadCountLock); };
435
Yifan Hong84bedeb2021-04-21 21:37:17 -0700436 // may actually be one more than this, if join is called
Elie Kheirallah47431c12022-04-21 23:46:17 +0000437 if (mThreadPoolStarted) {
438 return mCurrentThreads < mKernelStartedThreads
439 ? mMaxThreads
440 : mMaxThreads + mCurrentThreads - mKernelStartedThreads;
441 }
Yifan Hong84bedeb2021-04-21 21:37:17 -0700442 // must not be initialized or maybe has poll thread setup, we
443 // currently don't track this in libbinder
Elie Kheirallah47431c12022-04-21 23:46:17 +0000444 LOG_ALWAYS_FATAL_IF(mKernelStartedThreads != 0,
445 "Expecting 0 kernel started threads but have"
446 " %zu",
447 mKernelStartedThreads);
448 return mCurrentThreads;
Yifan Hong84bedeb2021-04-21 21:37:17 -0700449}
450
Devin Moore4354f712022-12-08 01:44:46 +0000451bool ProcessState::isThreadPoolStarted() const {
452 return mThreadPoolStarted;
453}
454
Carlos Llamas4f886702022-03-07 22:07:03 -0800455#define DRIVER_FEATURES_PATH "/dev/binderfs/features/"
456bool ProcessState::isDriverFeatureEnabled(const DriverFeature feature) {
457 static const char* const names[] = {
458 [static_cast<int>(DriverFeature::ONEWAY_SPAM_DETECTION)] =
459 DRIVER_FEATURES_PATH "oneway_spam_detection",
Carlos Llamasb235b122021-12-20 06:38:44 -0800460 [static_cast<int>(DriverFeature::EXTENDED_ERROR)] =
461 DRIVER_FEATURES_PATH "extended_error",
Carlos Llamas4f886702022-03-07 22:07:03 -0800462 };
463 int fd = open(names[static_cast<int>(feature)], O_RDONLY | O_CLOEXEC);
464 char on;
465 if (fd == -1) {
466 ALOGE_IF(errno != ENOENT, "%s: cannot open %s: %s", __func__,
467 names[static_cast<int>(feature)], strerror(errno));
468 return false;
469 }
470 if (read(fd, &on, sizeof(on)) == -1) {
471 ALOGE("%s: error reading to %s: %s", __func__,
472 names[static_cast<int>(feature)], strerror(errno));
473 return false;
474 }
475 close(fd);
476 return on == '1';
477}
478
Hang Lub185ac02021-03-24 13:17:22 +0800479status_t ProcessState::enableOnewaySpamDetection(bool enable) {
480 uint32_t enableDetection = enable ? 1 : 0;
481 if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
Martijn Coenende0a39e2021-04-22 14:38:46 +0200482 ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
Hang Lub185ac02021-03-24 13:17:22 +0800483 return -errno;
484 }
485 return NO_ERROR;
486}
487
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800488void ProcessState::giveThreadPoolName() {
489 androidSetThreadName( makeBinderThreadName().string() );
490}
491
Iliyan Malchev32062242017-04-10 14:06:11 -0700492String8 ProcessState::getDriverName() {
493 return mDriverName;
494}
495
Steven Moreland13a43c92021-08-30 13:21:48 -0700496static base::Result<int> open_driver(const char* driver) {
Martijn Coenen55d871c2017-03-21 15:56:40 -0700497 int fd = open(driver, O_RDWR | O_CLOEXEC);
Steven Moreland13a43c92021-08-30 13:21:48 -0700498 if (fd < 0) {
499 return base::ErrnoError() << "Opening '" << driver << "' failed";
500 }
501 int vers = 0;
502 status_t result = ioctl(fd, BINDER_VERSION, &vers);
503 if (result == -1) {
504 close(fd);
505 return base::ErrnoError() << "Binder ioctl to obtain version failed";
506 }
507 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
508 close(fd);
509 return base::Error() << "Binder driver protocol(" << vers
510 << ") does not match user space protocol("
511 << BINDER_CURRENT_PROTOCOL_VERSION
512 << ")! ioctl() return value: " << result;
513 }
514 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
515 result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
516 if (result == -1) {
517 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
518 }
519 uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
520 result = ioctl(fd, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
521 if (result == -1) {
Carlos Llamas4f886702022-03-07 22:07:03 -0800522 ALOGE_IF(ProcessState::isDriverFeatureEnabled(
523 ProcessState::DriverFeature::ONEWAY_SPAM_DETECTION),
524 "Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800525 }
526 return fd;
527}
528
Steven Moreland13a43c92021-08-30 13:21:48 -0700529ProcessState::ProcessState(const char* driver)
530 : mDriverName(String8(driver)),
531 mDriverFD(-1),
532 mVMStart(MAP_FAILED),
533 mThreadCountLock(PTHREAD_MUTEX_INITIALIZER),
534 mThreadCountDecrement(PTHREAD_COND_INITIALIZER),
535 mExecutingThreadsCount(0),
536 mWaitingForThreads(0),
537 mMaxThreads(DEFAULT_MAX_BINDER_THREADS),
Elie Kheirallah47431c12022-04-21 23:46:17 +0000538 mCurrentThreads(0),
539 mKernelStartedThreads(0),
Steven Moreland13a43c92021-08-30 13:21:48 -0700540 mStarvationStartTimeMs(0),
Steven Morelandee9df902021-10-14 14:00:08 -0700541 mForked(false),
Steven Moreland13a43c92021-08-30 13:21:48 -0700542 mThreadPoolStarted(false),
543 mThreadPoolSeq(1),
544 mCallRestriction(CallRestriction::NONE) {
545 base::Result<int> opened = open_driver(driver);
546
547 if (opened.ok()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548 // mmap the binder, providing a chunk of virtual address space to receive transactions.
Steven Moreland13a43c92021-08-30 13:21:48 -0700549 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE,
550 opened.value(), 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800551 if (mVMStart == MAP_FAILED) {
Steven Moreland13a43c92021-08-30 13:21:48 -0700552 close(opened.value());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800553 // *sigh*
Steven Moreland13a43c92021-08-30 13:21:48 -0700554 opened = base::Error()
555 << "Using " << driver << " failed: unable to mmap transaction memory.";
Iliyan Malchev32062242017-04-10 14:06:11 -0700556 mDriverName.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800557 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800558 }
Jeff Browne16986c2011-07-08 18:52:57 -0700559
Steven Moreland24bc0d12019-10-11 12:29:20 -0700560#ifdef __ANDROID__
Steven Moreland13a43c92021-08-30 13:21:48 -0700561 LOG_ALWAYS_FATAL_IF(!opened.ok(), "Binder driver '%s' could not be opened. Terminating: %s",
562 driver, opened.error().message().c_str());
Steven Moreland24bc0d12019-10-11 12:29:20 -0700563#endif
Steven Moreland13a43c92021-08-30 13:21:48 -0700564
565 if (opened.ok()) {
566 mDriverFD = opened.value();
567 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800568}
569
570ProcessState::~ProcessState()
571{
zhongjieff405782016-03-09 15:05:04 +0800572 if (mDriverFD >= 0) {
573 if (mVMStart != MAP_FAILED) {
Steven Moreland072cc7e2019-07-12 21:01:54 +0000574 munmap(mVMStart, BINDER_VM_SIZE);
zhongjieff405782016-03-09 15:05:04 +0800575 }
576 close(mDriverFD);
577 }
578 mDriverFD = -1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800579}
Jooyung Han1b228f42020-01-30 13:41:12 +0900580
Steven Moreland61ff8492019-09-26 16:05:45 -0700581} // namespace android