blob: 5e7f1510bcb497d6d3efff7ecc734504f45fccfd [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
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -070059namespace {
60bool readDriverFeatureFile(const char* filename) {
61 int fd = open(filename, O_RDONLY | O_CLOEXEC);
62 char on;
63 if (fd == -1) {
64 ALOGE_IF(errno != ENOENT, "%s: cannot open %s: %s", __func__, filename, strerror(errno));
65 return false;
66 }
67 if (read(fd, &on, sizeof(on)) == -1) {
68 ALOGE("%s: error reading to %s: %s", __func__, filename, strerror(errno));
69 close(fd);
70 return false;
71 }
72 close(fd);
73 return on == '1';
74}
75
76} // namespace
77
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078namespace android {
Wale Ogunwale376b8222015-04-13 16:16:10 -070079
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000080using namespace android::binder::impl;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070081using android::binder::unique_fd;
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000082
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083class PoolThread : public Thread
84{
85public:
Chih-Hung Hsiehe2347b72016-04-25 15:41:05 -070086 explicit PoolThread(bool isMain)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087 : mIsMain(isMain)
88 {
89 }
Jooyung Han1b228f42020-01-30 13:41:12 +090090
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091protected:
92 virtual bool threadLoop()
93 {
94 IPCThreadState::self()->joinThreadPool(mIsMain);
95 return false;
96 }
Jooyung Han1b228f42020-01-30 13:41:12 +090097
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080098 const bool mIsMain;
99};
100
101sp<ProcessState> ProcessState::self()
102{
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000103 return init(kDefaultDriver, false /*requireDefault*/);
Martijn Coenen55d871c2017-03-21 15:56:40 -0700104}
105
106sp<ProcessState> ProcessState::initWithDriver(const char* driver)
107{
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000108 return init(driver, true /*requireDefault*/);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800109}
110
Steven Moreland072cc7e2019-07-12 21:01:54 +0000111sp<ProcessState> ProcessState::selfOrNull()
112{
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000113 return init(nullptr, false /*requireDefault*/);
114}
115
Steven Morelandee9df902021-10-14 14:00:08 -0700116[[clang::no_destroy]] static sp<ProcessState> gProcess;
117[[clang::no_destroy]] static std::mutex gProcessMutex;
118
119static void verifyNotForked(bool forked) {
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700120 LOG_ALWAYS_FATAL_IF(forked, "libbinder ProcessState can not be used after fork");
Steven Morelandee9df902021-10-14 14:00:08 -0700121}
122
Steven Moreland9a4278e2023-02-14 01:33:39 +0000123bool ProcessState::isVndservicemanagerEnabled() {
124 return access("/vendor/bin/vndservicemanager", R_OK) == 0;
125}
126
Steven Moreland68275d72023-04-21 22:12:45 +0000127sp<ProcessState> ProcessState::init(const char* driver, bool requireDefault) {
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000128 if (driver == nullptr) {
129 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Morelandee9df902021-10-14 14:00:08 -0700130 if (gProcess) {
131 verifyNotForked(gProcess->mForked);
132 }
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000133 return gProcess;
134 }
135
136 [[clang::no_destroy]] static std::once_flag gProcessOnce;
137 std::call_once(gProcessOnce, [&](){
138 if (access(driver, R_OK) == -1) {
139 ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
140 driver = "/dev/binder";
141 }
142
Steven Moreland9a4278e2023-02-14 01:33:39 +0000143 if (0 == strcmp(driver, "/dev/vndbinder") && !isVndservicemanagerEnabled()) {
144 ALOGE("vndservicemanager is not started on this device, you can save resources/threads "
145 "by not initializing ProcessState with /dev/vndbinder.");
146 }
147
Steven Morelandee9df902021-10-14 14:00:08 -0700148 // we must install these before instantiating the gProcess object,
149 // otherwise this would race with creating it, and there could be the
150 // possibility of an invalid gProcess object forked by another thread
151 // before these are installed
152 int ret = pthread_atfork(ProcessState::onFork, ProcessState::parentPostFork,
153 ProcessState::childPostFork);
154 LOG_ALWAYS_FATAL_IF(ret != 0, "pthread_atfork error %s", strerror(ret));
155
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000156 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000157 gProcess = sp<ProcessState>::make(driver);
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000158 });
159
160 if (requireDefault) {
161 // Detect if we are trying to initialize with a different driver, and
162 // consider that an error. ProcessState will only be initialized once above.
163 LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,
164 "ProcessState was already initialized with %s,"
165 " can't initialize with %s.",
166 gProcess->getDriverName().c_str(), driver);
167 }
168
Steven Morelandee9df902021-10-14 14:00:08 -0700169 verifyNotForked(gProcess->mForked);
Colin Cross9d45ccc2017-06-20 17:48:33 -0700170 return gProcess;
171}
172
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800173sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174{
Steven Morelandc709dd82019-08-05 20:30:14 -0700175 sp<IBinder> context = getStrongProxyForHandle(0);
176
Steven Moreland4da8fb02020-12-29 22:51:32 +0000177 if (context) {
178 // The root object is special since we get it directly from the driver, it is never
179 // written by Parcell::writeStrongBinder.
180 internal::Stability::markCompilationUnit(context.get());
181 } else {
182 ALOGW("Not able to get context object on %s.", mDriverName.c_str());
Steven Moreland8d93a712020-02-19 15:16:15 -0800183 }
184
Steven Morelandc709dd82019-08-05 20:30:14 -0700185 return context;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800186}
187
Steven Morelandee9df902021-10-14 14:00:08 -0700188void ProcessState::onFork() {
189 // make sure another thread isn't currently retrieving ProcessState
190 gProcessMutex.lock();
191}
192
193void ProcessState::parentPostFork() {
194 gProcessMutex.unlock();
195}
196
197void ProcessState::childPostFork() {
198 // another thread might call fork before gProcess is instantiated, but after
199 // the thread handler is installed
200 if (gProcess) {
201 gProcess->mForked = true;
Steven Morelanddf732ba2022-05-18 22:04:49 +0000202
203 // "O_CLOFORK"
204 close(gProcess->mDriverFD);
205 gProcess->mDriverFD = -1;
Steven Morelandee9df902021-10-14 14:00:08 -0700206 }
207 gProcessMutex.unlock();
208}
209
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800210void ProcessState::startThreadPool()
211{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700212 std::unique_lock<std::mutex> _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800213 if (!mThreadPoolStarted) {
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000214 if (mMaxThreads == 0) {
Steven Moreland3e9debc2023-06-15 00:35:29 +0000215 // see also getThreadPoolMaxTotalThreadCount
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000216 ALOGW("Extra binder thread started, but 0 threads requested. Do not use "
217 "*startThreadPool when zero threads are requested.");
218 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219 mThreadPoolStarted = true;
220 spawnPooledThread(true);
221 }
222}
223
Steven Moreland61096622020-08-31 23:36:39 +0000224bool ProcessState::becomeContextManager()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700226 std::unique_lock<std::mutex> _l(mLock);
Jeff Browne16986c2011-07-08 18:52:57 -0700227
Steven Moreland4411d712019-07-12 14:02:53 -0700228 flat_binder_object obj {
229 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
230 };
Steven Moreland3085a472018-12-26 13:59:23 -0800231
Steven Moreland4411d712019-07-12 14:02:53 -0700232 int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
Steven Moreland3085a472018-12-26 13:59:23 -0800233
Steven Moreland4411d712019-07-12 14:02:53 -0700234 // fallback to original method
235 if (result != 0) {
236 android_errorWriteLog(0x534e4554, "121035042");
Steven Moreland3085a472018-12-26 13:59:23 -0800237
Hungming Chen28b42522020-08-28 17:29:55 +0800238 int unused = 0;
239 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800240 }
Steven Moreland4411d712019-07-12 14:02:53 -0700241
242 if (result == -1) {
Steven Moreland4411d712019-07-12 14:02:53 -0700243 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
244 }
245
246 return result == 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247}
248
Colin Cross9d45ccc2017-06-20 17:48:33 -0700249// Get references to userspace objects held by the kernel binder driver
250// Writes up to count elements into buf, and returns the total number
251// of references the kernel has, which may be larger than count.
252// buf may be NULL if count is 0. The pointers returned by this method
253// should only be used for debugging and not dereferenced, they may
254// already be invalid.
255ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
256{
Colin Cross9d45ccc2017-06-20 17:48:33 -0700257 binder_node_debug_info info = {};
258
Yi Kongfdd8da92018-06-07 17:52:27 -0700259 uintptr_t* end = buf ? buf + buf_count : nullptr;
Colin Cross9d45ccc2017-06-20 17:48:33 -0700260 size_t count = 0;
261
262 do {
263 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
264 if (result < 0) {
265 return -1;
266 }
267 if (info.ptr != 0) {
268 if (buf && buf < end)
269 *buf++ = info.ptr;
270 count++;
271 if (buf && buf < end)
272 *buf++ = info.cookie;
273 count++;
274 }
275 } while (info.ptr != 0);
276
277 return count;
278}
279
Jon Spivack902e6fc2019-10-18 21:22:37 -0700280// Queries the driver for the current strong reference count of the node
281// that the handle points to. Can only be used by the servicemanager.
282//
283// Returns -1 in case of failure, otherwise the strong reference count.
Steven Morelande8393882020-12-18 02:27:20 +0000284ssize_t ProcessState::getStrongRefCountForNode(const sp<BpBinder>& binder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000285 if (binder->isRpcBinder()) return -1;
286
Jon Spivack902e6fc2019-10-18 21:22:37 -0700287 binder_node_info_for_ref info;
288 memset(&info, 0, sizeof(binder_node_info_for_ref));
289
Steven Moreland99157622021-09-13 16:27:34 -0700290 info.handle = binder->getPrivateAccessor().binderHandle();
Jon Spivack902e6fc2019-10-18 21:22:37 -0700291
292 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
293
294 if (result != OK) {
295 static bool logged = false;
296 if (!logged) {
297 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
298 logged = true;
299 }
300 return -1;
301 }
302
303 return info.strong_count;
304}
305
Steven Moreland7732a092019-01-02 17:54:16 -0800306void ProcessState::setCallRestriction(CallRestriction restriction) {
Steven Moreland28723ae2019-04-01 18:52:30 -0700307 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
308 "Call restrictions must be set before the threadpool is started.");
Steven Moreland7732a092019-01-02 17:54:16 -0800309
310 mCallRestriction = restriction;
311}
312
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800313ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
314{
315 const size_t N=mHandleToObject.size();
316 if (N <= (size_t)handle) {
317 handle_entry e;
Yi Kongfdd8da92018-06-07 17:52:27 -0700318 e.binder = nullptr;
319 e.refs = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
Yi Kongfdd8da92018-06-07 17:52:27 -0700321 if (err < NO_ERROR) return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800322 }
323 return &mHandleToObject.editItemAt(handle);
324}
325
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000326// see b/166779391: cannot change the VNDK interface, so access like this
327extern sp<BBinder> the_context_object;
328
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800329sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
330{
331 sp<IBinder> result;
Steven Moreland7c166e12024-07-20 00:40:56 +0000332 std::function<void()> postTask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800333
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700334 std::unique_lock<std::mutex> _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800335
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000336 if (handle == 0 && the_context_object != nullptr) return the_context_object;
337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 handle_entry* e = lookupHandleLocked(handle);
339
Yi Kongfdd8da92018-06-07 17:52:27 -0700340 if (e != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800341 // We need to create a new BpBinder if there isn't currently one, OR we
Steven Morelande171d622019-07-17 16:06:01 -0700342 // are unable to acquire a weak reference on this current one. The
343 // attemptIncWeak() is safe because we know the BpBinder destructor will always
344 // call expungeHandle(), which acquires the same lock we are holding now.
345 // We need to do this because there is a race condition between someone
346 // releasing a reference on this BpBinder, and a new reference on its handle
347 // arriving from the driver.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800348 IBinder* b = e->binder;
Yi Kongfdd8da92018-06-07 17:52:27 -0700349 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
Todd Poynora7b0f042013-06-18 17:25:37 -0700350 if (handle == 0) {
351 // Special case for context manager...
352 // The context manager is the only object for which we create
353 // a BpBinder proxy without already holding a reference.
354 // Perform a dummy transaction to ensure the context manager
355 // is registered before we create the first local reference
356 // to it (which will occur when creating the BpBinder).
357 // If a local reference is created for the BpBinder when the
358 // context manager is not present, the driver will fail to
359 // provide a reference to the context manager, but the
360 // driver API does not return status.
361 //
362 // Note that this is not race-free if the context manager
363 // dies while this code runs.
Todd Poynora7b0f042013-06-18 17:25:37 -0700364
Steven Moreland9514b202020-09-21 18:03:27 +0000365 IPCThreadState* ipc = IPCThreadState::self();
366
367 CallRestriction originalCallRestriction = ipc->getCallRestriction();
368 ipc->setCallRestriction(CallRestriction::NONE);
369
Todd Poynora7b0f042013-06-18 17:25:37 -0700370 Parcel data;
Steven Moreland9514b202020-09-21 18:03:27 +0000371 status_t status = ipc->transact(
Yi Kongfdd8da92018-06-07 17:52:27 -0700372 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
Steven Moreland9514b202020-09-21 18:03:27 +0000373
374 ipc->setCallRestriction(originalCallRestriction);
375
Todd Poynora7b0f042013-06-18 17:25:37 -0700376 if (status == DEAD_OBJECT)
Yi Kongfdd8da92018-06-07 17:52:27 -0700377 return nullptr;
Todd Poynora7b0f042013-06-18 17:25:37 -0700378 }
379
Steven Moreland7c166e12024-07-20 00:40:56 +0000380 sp<BpBinder> b = BpBinder::PrivateAccessor::create(handle, &postTask);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000381 e->binder = b.get();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800382 if (b) e->refs = b->getWeakRefs();
383 result = b;
384 } else {
385 // This little bit of nastyness is to allow us to add a primary
386 // reference to the remote proxy when this team doesn't have one
387 // but another team is sending the handle to us.
388 result.force_set(b);
389 e->refs->decWeak(this);
390 }
391 }
392
Steven Moreland7c166e12024-07-20 00:40:56 +0000393 _l.unlock();
394
395 if (postTask) postTask();
396
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800397 return result;
398}
399
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800400void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
401{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700402 std::unique_lock<std::mutex> _l(mLock);
Jooyung Han1b228f42020-01-30 13:41:12 +0900403
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800404 handle_entry* e = lookupHandleLocked(handle);
405
406 // This handle may have already been replaced with a new BpBinder
407 // (if someone failed the AttemptIncWeak() above); we don't want
408 // to overwrite it.
Yi Kongfdd8da92018-06-07 17:52:27 -0700409 if (e && e->binder == binder) e->binder = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800410}
411
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800412String8 ProcessState::makeBinderThreadName() {
Frederick Maylea9675a72024-08-05 14:21:53 -0700413 int32_t s = mThreadPoolSeq.fetch_add(1, std::memory_order_release);
Philip Cuadraa082fa82016-04-08 10:29:14 -0700414 pid_t pid = getpid();
Steven Moreland281abad2022-02-24 22:06:40 +0000415
416 std::string_view driverName = mDriverName.c_str();
417 android::base::ConsumePrefix(&driverName, "/dev/");
418
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800419 String8 name;
Steven Moreland281abad2022-02-24 22:06:40 +0000420 name.appendFormat("%.*s:%d_%X", static_cast<int>(driverName.length()), driverName.data(), pid,
421 s);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800422 return name;
423}
424
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425void ProcessState::spawnPooledThread(bool isMain)
426{
427 if (mThreadPoolStarted) {
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800428 String8 name = makeBinderThreadName();
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000429 ALOGV("Spawning new pooled thread, name=%s\n", name.c_str());
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000430 sp<Thread> t = sp<PoolThread>::make(isMain);
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000431 t->run(name.c_str());
Elie Kheirallah47431c12022-04-21 23:46:17 +0000432 mKernelStartedThreads++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800433 }
Steven Moreland3e9debc2023-06-15 00:35:29 +0000434 // TODO: if startThreadPool is called on another thread after the process
435 // starts up, the kernel might think that it already requested those
436 // binder threads, and additional won't be started. This is likely to
437 // cause deadlocks, and it will also cause getThreadPoolMaxTotalThreadCount
438 // to return too high of a value.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800439}
440
Mathias Agopian1b80f792012-04-17 16:11:08 -0700441status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
Steven Moreland1fdb98b2020-03-06 21:42:12 +0000442 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
443 "Binder threadpool cannot be shrunk after starting");
Mathias Agopian1b80f792012-04-17 16:11:08 -0700444 status_t result = NO_ERROR;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700445 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
446 mMaxThreads = maxThreads;
447 } else {
Mathias Agopian1b80f792012-04-17 16:11:08 -0700448 result = -errno;
449 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
450 }
451 return result;
452}
453
Elie Kheirallah47431c12022-04-21 23:46:17 +0000454size_t ProcessState::getThreadPoolMaxTotalThreadCount() const {
Frederick Mayle908b09c2024-08-05 14:10:40 -0700455 // Need to read `mKernelStartedThreads` before `mThreadPoolStarted` (with
456 // non-relaxed memory ordering) to avoid a race like the following:
457 //
458 // thread A: if (mThreadPoolStarted) { // evaluates false
459 // thread B: mThreadPoolStarted = true;
460 // thread B: mKernelStartedThreads++;
461 // thread A: size_t kernelStarted = mKernelStartedThreads;
462 // thread A: LOG_ALWAYS_FATAL_IF(kernelStarted != 0, ...);
463 size_t kernelStarted = mKernelStartedThreads;
464
Elie Kheirallah47431c12022-04-21 23:46:17 +0000465 if (mThreadPoolStarted) {
Frederick Mayle263507f2024-05-30 14:54:27 -0700466 size_t max = mMaxThreads;
467 size_t current = mCurrentThreads;
468
469 LOG_ALWAYS_FATAL_IF(kernelStarted > max + 1,
470 "too many kernel-started threads: %zu > %zu + 1", kernelStarted, max);
Steven Moreland3e9debc2023-06-15 00:35:29 +0000471
472 // calling startThreadPool starts a thread
473 size_t threads = 1;
474
475 // the kernel is configured to start up to mMaxThreads more threads
Frederick Mayle263507f2024-05-30 14:54:27 -0700476 threads += max;
Steven Moreland3e9debc2023-06-15 00:35:29 +0000477
478 // Users may call IPCThreadState::joinThreadPool directly. We don't
479 // currently have a way to count this directly (it could be added by
480 // adding a separate private joinKernelThread method in IPCThreadState).
481 // So, if we are in a race between the kernel thread variable being
482 // incremented in this file and mCurrentThreads being incremented
483 // in IPCThreadState, temporarily forget about the extra join threads.
484 // This is okay, because most callers of this method only care about
485 // having 0, 1, or more threads.
Frederick Mayle263507f2024-05-30 14:54:27 -0700486 if (current > kernelStarted) {
487 threads += current - kernelStarted;
Steven Moreland3e9debc2023-06-15 00:35:29 +0000488 }
489
490 return threads;
Elie Kheirallah47431c12022-04-21 23:46:17 +0000491 }
Steven Moreland3e9debc2023-06-15 00:35:29 +0000492
Yifan Hong84bedeb2021-04-21 21:37:17 -0700493 // must not be initialized or maybe has poll thread setup, we
494 // currently don't track this in libbinder
Frederick Mayle263507f2024-05-30 14:54:27 -0700495 LOG_ALWAYS_FATAL_IF(kernelStarted != 0, "Expecting 0 kernel started threads but have %zu",
496 kernelStarted);
Elie Kheirallah47431c12022-04-21 23:46:17 +0000497 return mCurrentThreads;
Yifan Hong84bedeb2021-04-21 21:37:17 -0700498}
499
Devin Moore4354f712022-12-08 01:44:46 +0000500bool ProcessState::isThreadPoolStarted() const {
501 return mThreadPoolStarted;
502}
503
Carlos Llamas4f886702022-03-07 22:07:03 -0800504#define DRIVER_FEATURES_PATH "/dev/binderfs/features/"
505bool ProcessState::isDriverFeatureEnabled(const DriverFeature feature) {
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700506 // Use static variable to cache the results.
507 if (feature == DriverFeature::ONEWAY_SPAM_DETECTION) {
508 static bool enabled = readDriverFeatureFile(DRIVER_FEATURES_PATH "oneway_spam_detection");
509 return enabled;
Carlos Llamas4f886702022-03-07 22:07:03 -0800510 }
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700511 if (feature == DriverFeature::EXTENDED_ERROR) {
512 static bool enabled = readDriverFeatureFile(DRIVER_FEATURES_PATH "extended_error");
513 return enabled;
Carlos Llamas4f886702022-03-07 22:07:03 -0800514 }
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700515 if (feature == DriverFeature::FREEZE_NOTIFICATION) {
516 static bool enabled = readDriverFeatureFile(DRIVER_FEATURES_PATH "freeze_notification");
517 return enabled;
518 }
519 return false;
Carlos Llamas4f886702022-03-07 22:07:03 -0800520}
521
Hang Lub185ac02021-03-24 13:17:22 +0800522status_t ProcessState::enableOnewaySpamDetection(bool enable) {
523 uint32_t enableDetection = enable ? 1 : 0;
524 if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
Martijn Coenende0a39e2021-04-22 14:38:46 +0200525 ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
Hang Lub185ac02021-03-24 13:17:22 +0800526 return -errno;
527 }
528 return NO_ERROR;
529}
530
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800531void ProcessState::giveThreadPoolName() {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000532 androidSetThreadName(makeBinderThreadName().c_str());
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800533}
534
Iliyan Malchev32062242017-04-10 14:06:11 -0700535String8 ProcessState::getDriverName() {
536 return mDriverName;
537}
538
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000539static unique_fd open_driver(const char* driver, String8* error) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700540 auto fd = unique_fd(open(driver, O_RDWR | O_CLOEXEC));
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700541 if (!fd.ok()) {
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000542 error->appendFormat("%d (%s) Opening '%s' failed", errno, strerror(errno), driver);
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700543 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700544 }
545 int vers = 0;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700546 int result = ioctl(fd.get(), BINDER_VERSION, &vers);
Steven Moreland13a43c92021-08-30 13:21:48 -0700547 if (result == -1) {
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000548 error->appendFormat("%d (%s) Binder ioctl to obtain version failed", errno,
549 strerror(errno));
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700550 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700551 }
552 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000553 error->appendFormat("Binder driver protocol(%d) does not match user space protocol(%d)! "
554 "ioctl() return value: %d",
555 vers, BINDER_CURRENT_PROTOCOL_VERSION, result);
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700556 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700557 }
558 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700559 result = ioctl(fd.get(), BINDER_SET_MAX_THREADS, &maxThreads);
Steven Moreland13a43c92021-08-30 13:21:48 -0700560 if (result == -1) {
561 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
562 }
563 uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700564 result = ioctl(fd.get(), BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
Steven Moreland13a43c92021-08-30 13:21:48 -0700565 if (result == -1) {
Carlos Llamas4f886702022-03-07 22:07:03 -0800566 ALOGE_IF(ProcessState::isDriverFeatureEnabled(
567 ProcessState::DriverFeature::ONEWAY_SPAM_DETECTION),
568 "Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800569 }
570 return fd;
571}
572
Steven Moreland13a43c92021-08-30 13:21:48 -0700573ProcessState::ProcessState(const char* driver)
574 : mDriverName(String8(driver)),
575 mDriverFD(-1),
576 mVMStart(MAP_FAILED),
Steven Moreland13a43c92021-08-30 13:21:48 -0700577 mExecutingThreadsCount(0),
Steven Moreland13a43c92021-08-30 13:21:48 -0700578 mMaxThreads(DEFAULT_MAX_BINDER_THREADS),
Elie Kheirallah47431c12022-04-21 23:46:17 +0000579 mCurrentThreads(0),
580 mKernelStartedThreads(0),
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700581 mStarvationStartTime(never()),
Steven Morelandee9df902021-10-14 14:00:08 -0700582 mForked(false),
Steven Moreland13a43c92021-08-30 13:21:48 -0700583 mThreadPoolStarted(false),
584 mThreadPoolSeq(1),
585 mCallRestriction(CallRestriction::NONE) {
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000586 String8 error;
587 unique_fd opened = open_driver(driver, &error);
Steven Moreland13a43c92021-08-30 13:21:48 -0700588
589 if (opened.ok()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800590 // mmap the binder, providing a chunk of virtual address space to receive transactions.
Steven Moreland13a43c92021-08-30 13:21:48 -0700591 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE,
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700592 opened.get(), 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800593 if (mVMStart == MAP_FAILED) {
594 // *sigh*
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700595 ALOGE("Using %s failed: unable to mmap transaction memory.", driver);
596 opened.reset();
Iliyan Malchev32062242017-04-10 14:06:11 -0700597 mDriverName.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800598 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800599 }
Jeff Browne16986c2011-07-08 18:52:57 -0700600
Steven Moreland24bc0d12019-10-11 12:29:20 -0700601#ifdef __ANDROID__
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000602 LOG_ALWAYS_FATAL_IF(!opened.ok(),
603 "Binder driver '%s' could not be opened. Error: %s. Terminating.",
Steven Morelandd3e6cda2024-08-06 20:01:13 +0000604 driver, error.c_str());
Steven Moreland24bc0d12019-10-11 12:29:20 -0700605#endif
Steven Moreland13a43c92021-08-30 13:21:48 -0700606
607 if (opened.ok()) {
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700608 mDriverFD = opened.release();
Steven Moreland13a43c92021-08-30 13:21:48 -0700609 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800610}
611
612ProcessState::~ProcessState()
613{
zhongjieff405782016-03-09 15:05:04 +0800614 if (mDriverFD >= 0) {
615 if (mVMStart != MAP_FAILED) {
Steven Moreland072cc7e2019-07-12 21:01:54 +0000616 munmap(mVMStart, BINDER_VM_SIZE);
zhongjieff405782016-03-09 15:05:04 +0800617 }
618 close(mDriverFD);
619 }
620 mDriverFD = -1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800621}
Jooyung Han1b228f42020-01-30 13:41:12 +0900622
Steven Moreland61ff8492019-09-26 16:05:45 -0700623} // namespace android