blob: 0bec37999b55a5be51ec7422df1e723b6fb82860 [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
Kevin Lindkviste8e12432022-11-23 13:23:42 +010051#if defined(__ANDROID__) || defined(__Fuchsia__)
52#define EXPECT_BINDER_OPEN_SUCCESS
53#endif
54
Martijn Coenen7bca77a2019-03-13 11:51:08 +000055#ifdef __ANDROID_VNDK__
56const char* kDefaultDriver = "/dev/vndbinder";
57#else
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070058const char* kDefaultDriver = "/dev/binder";
Martijn Coenen7bca77a2019-03-13 11:51:08 +000059#endif
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070060
Philip Cuadraa082fa82016-04-08 10:29:14 -070061// -------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -070063namespace {
64bool readDriverFeatureFile(const char* filename) {
65 int fd = open(filename, O_RDONLY | O_CLOEXEC);
66 char on;
67 if (fd == -1) {
68 ALOGE_IF(errno != ENOENT, "%s: cannot open %s: %s", __func__, filename, strerror(errno));
69 return false;
70 }
71 if (read(fd, &on, sizeof(on)) == -1) {
72 ALOGE("%s: error reading to %s: %s", __func__, filename, strerror(errno));
73 close(fd);
74 return false;
75 }
76 close(fd);
77 return on == '1';
78}
79
80} // namespace
81
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082namespace android {
Wale Ogunwale376b8222015-04-13 16:16:10 -070083
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000084using namespace android::binder::impl;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070085using android::binder::unique_fd;
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000086
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087class PoolThread : public Thread
88{
89public:
Chih-Hung Hsiehe2347b72016-04-25 15:41:05 -070090 explicit PoolThread(bool isMain)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091 : mIsMain(isMain)
92 {
93 }
Jooyung Han1b228f42020-01-30 13:41:12 +090094
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095protected:
96 virtual bool threadLoop()
97 {
98 IPCThreadState::self()->joinThreadPool(mIsMain);
99 return false;
100 }
Jooyung Han1b228f42020-01-30 13:41:12 +0900101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102 const bool mIsMain;
103};
104
105sp<ProcessState> ProcessState::self()
106{
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000107 return init(kDefaultDriver, false /*requireDefault*/);
Martijn Coenen55d871c2017-03-21 15:56:40 -0700108}
109
110sp<ProcessState> ProcessState::initWithDriver(const char* driver)
111{
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000112 return init(driver, true /*requireDefault*/);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800113}
114
Steven Moreland072cc7e2019-07-12 21:01:54 +0000115sp<ProcessState> ProcessState::selfOrNull()
116{
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000117 return init(nullptr, false /*requireDefault*/);
118}
119
Steven Morelandee9df902021-10-14 14:00:08 -0700120[[clang::no_destroy]] static sp<ProcessState> gProcess;
121[[clang::no_destroy]] static std::mutex gProcessMutex;
122
123static void verifyNotForked(bool forked) {
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700124 LOG_ALWAYS_FATAL_IF(forked, "libbinder ProcessState can not be used after fork");
Steven Morelandee9df902021-10-14 14:00:08 -0700125}
126
Steven Moreland9a4278e2023-02-14 01:33:39 +0000127bool ProcessState::isVndservicemanagerEnabled() {
128 return access("/vendor/bin/vndservicemanager", R_OK) == 0;
129}
130
Steven Moreland68275d72023-04-21 22:12:45 +0000131sp<ProcessState> ProcessState::init(const char* driver, bool requireDefault) {
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000132 if (driver == nullptr) {
133 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Morelandee9df902021-10-14 14:00:08 -0700134 if (gProcess) {
135 verifyNotForked(gProcess->mForked);
136 }
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000137 return gProcess;
138 }
139
140 [[clang::no_destroy]] static std::once_flag gProcessOnce;
141 std::call_once(gProcessOnce, [&](){
142 if (access(driver, R_OK) == -1) {
143 ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
144 driver = "/dev/binder";
145 }
146
Steven Moreland9a4278e2023-02-14 01:33:39 +0000147 if (0 == strcmp(driver, "/dev/vndbinder") && !isVndservicemanagerEnabled()) {
148 ALOGE("vndservicemanager is not started on this device, you can save resources/threads "
149 "by not initializing ProcessState with /dev/vndbinder.");
150 }
151
Steven Morelandee9df902021-10-14 14:00:08 -0700152 // we must install these before instantiating the gProcess object,
153 // otherwise this would race with creating it, and there could be the
154 // possibility of an invalid gProcess object forked by another thread
155 // before these are installed
156 int ret = pthread_atfork(ProcessState::onFork, ProcessState::parentPostFork,
157 ProcessState::childPostFork);
158 LOG_ALWAYS_FATAL_IF(ret != 0, "pthread_atfork error %s", strerror(ret));
159
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000160 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000161 gProcess = sp<ProcessState>::make(driver);
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000162 });
163
164 if (requireDefault) {
165 // Detect if we are trying to initialize with a different driver, and
166 // consider that an error. ProcessState will only be initialized once above.
167 LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,
168 "ProcessState was already initialized with %s,"
169 " can't initialize with %s.",
170 gProcess->getDriverName().c_str(), driver);
171 }
172
Steven Morelandee9df902021-10-14 14:00:08 -0700173 verifyNotForked(gProcess->mForked);
Colin Cross9d45ccc2017-06-20 17:48:33 -0700174 return gProcess;
175}
176
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800177sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178{
Steven Morelandc709dd82019-08-05 20:30:14 -0700179 sp<IBinder> context = getStrongProxyForHandle(0);
180
Steven Moreland4da8fb02020-12-29 22:51:32 +0000181 if (context) {
182 // The root object is special since we get it directly from the driver, it is never
183 // written by Parcell::writeStrongBinder.
184 internal::Stability::markCompilationUnit(context.get());
185 } else {
186 ALOGW("Not able to get context object on %s.", mDriverName.c_str());
Steven Moreland8d93a712020-02-19 15:16:15 -0800187 }
188
Steven Morelandc709dd82019-08-05 20:30:14 -0700189 return context;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800190}
191
Steven Morelandee9df902021-10-14 14:00:08 -0700192void ProcessState::onFork() {
193 // make sure another thread isn't currently retrieving ProcessState
194 gProcessMutex.lock();
195}
196
197void ProcessState::parentPostFork() {
198 gProcessMutex.unlock();
199}
200
201void ProcessState::childPostFork() {
202 // another thread might call fork before gProcess is instantiated, but after
203 // the thread handler is installed
204 if (gProcess) {
205 gProcess->mForked = true;
Steven Morelanddf732ba2022-05-18 22:04:49 +0000206
207 // "O_CLOFORK"
208 close(gProcess->mDriverFD);
209 gProcess->mDriverFD = -1;
Steven Morelandee9df902021-10-14 14:00:08 -0700210 }
211 gProcessMutex.unlock();
212}
213
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214void ProcessState::startThreadPool()
215{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700216 std::unique_lock<std::mutex> _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800217 if (!mThreadPoolStarted) {
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000218 if (mMaxThreads == 0) {
Steven Moreland3e9debc2023-06-15 00:35:29 +0000219 // see also getThreadPoolMaxTotalThreadCount
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000220 ALOGW("Extra binder thread started, but 0 threads requested. Do not use "
221 "*startThreadPool when zero threads are requested.");
222 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 mThreadPoolStarted = true;
224 spawnPooledThread(true);
225 }
226}
227
Steven Moreland61096622020-08-31 23:36:39 +0000228bool ProcessState::becomeContextManager()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700230 std::unique_lock<std::mutex> _l(mLock);
Jeff Browne16986c2011-07-08 18:52:57 -0700231
Steven Moreland4411d712019-07-12 14:02:53 -0700232 flat_binder_object obj {
233 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
234 };
Steven Moreland3085a472018-12-26 13:59:23 -0800235
Steven Moreland4411d712019-07-12 14:02:53 -0700236 int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
Steven Moreland3085a472018-12-26 13:59:23 -0800237
Steven Moreland4411d712019-07-12 14:02:53 -0700238 // fallback to original method
239 if (result != 0) {
240 android_errorWriteLog(0x534e4554, "121035042");
Steven Moreland3085a472018-12-26 13:59:23 -0800241
Hungming Chen28b42522020-08-28 17:29:55 +0800242 int unused = 0;
243 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244 }
Steven Moreland4411d712019-07-12 14:02:53 -0700245
246 if (result == -1) {
Steven Moreland4411d712019-07-12 14:02:53 -0700247 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
248 }
249
250 return result == 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800251}
252
Colin Cross9d45ccc2017-06-20 17:48:33 -0700253// Get references to userspace objects held by the kernel binder driver
254// Writes up to count elements into buf, and returns the total number
255// of references the kernel has, which may be larger than count.
256// buf may be NULL if count is 0. The pointers returned by this method
257// should only be used for debugging and not dereferenced, they may
258// already be invalid.
259ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
260{
Colin Cross9d45ccc2017-06-20 17:48:33 -0700261 binder_node_debug_info info = {};
262
Yi Kongfdd8da92018-06-07 17:52:27 -0700263 uintptr_t* end = buf ? buf + buf_count : nullptr;
Colin Cross9d45ccc2017-06-20 17:48:33 -0700264 size_t count = 0;
265
266 do {
267 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
268 if (result < 0) {
269 return -1;
270 }
271 if (info.ptr != 0) {
272 if (buf && buf < end)
273 *buf++ = info.ptr;
274 count++;
275 if (buf && buf < end)
276 *buf++ = info.cookie;
277 count++;
278 }
279 } while (info.ptr != 0);
280
281 return count;
282}
283
Jon Spivack902e6fc2019-10-18 21:22:37 -0700284// Queries the driver for the current strong reference count of the node
285// that the handle points to. Can only be used by the servicemanager.
286//
287// Returns -1 in case of failure, otherwise the strong reference count.
Steven Morelande8393882020-12-18 02:27:20 +0000288ssize_t ProcessState::getStrongRefCountForNode(const sp<BpBinder>& binder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000289 if (binder->isRpcBinder()) return -1;
290
Jon Spivack902e6fc2019-10-18 21:22:37 -0700291 binder_node_info_for_ref info;
292 memset(&info, 0, sizeof(binder_node_info_for_ref));
293
Steven Moreland99157622021-09-13 16:27:34 -0700294 info.handle = binder->getPrivateAccessor().binderHandle();
Jon Spivack902e6fc2019-10-18 21:22:37 -0700295
296 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
297
298 if (result != OK) {
299 static bool logged = false;
300 if (!logged) {
301 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
302 logged = true;
303 }
304 return -1;
305 }
306
307 return info.strong_count;
308}
309
Steven Moreland7732a092019-01-02 17:54:16 -0800310void ProcessState::setCallRestriction(CallRestriction restriction) {
Steven Moreland28723ae2019-04-01 18:52:30 -0700311 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
312 "Call restrictions must be set before the threadpool is started.");
Steven Moreland7732a092019-01-02 17:54:16 -0800313
314 mCallRestriction = restriction;
315}
316
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800317ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
318{
319 const size_t N=mHandleToObject.size();
320 if (N <= (size_t)handle) {
321 handle_entry e;
Yi Kongfdd8da92018-06-07 17:52:27 -0700322 e.binder = nullptr;
323 e.refs = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800324 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
Yi Kongfdd8da92018-06-07 17:52:27 -0700325 if (err < NO_ERROR) return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326 }
327 return &mHandleToObject.editItemAt(handle);
328}
329
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000330// see b/166779391: cannot change the VNDK interface, so access like this
331extern sp<BBinder> the_context_object;
332
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800333sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
334{
335 sp<IBinder> result;
Steven Moreland7c166e12024-07-20 00:40:56 +0000336 std::function<void()> postTask;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800337
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700338 std::unique_lock<std::mutex> _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800339
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000340 if (handle == 0 && the_context_object != nullptr) return the_context_object;
341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342 handle_entry* e = lookupHandleLocked(handle);
343
Yi Kongfdd8da92018-06-07 17:52:27 -0700344 if (e != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345 // We need to create a new BpBinder if there isn't currently one, OR we
Steven Morelande171d622019-07-17 16:06:01 -0700346 // are unable to acquire a weak reference on this current one. The
347 // attemptIncWeak() is safe because we know the BpBinder destructor will always
348 // call expungeHandle(), which acquires the same lock we are holding now.
349 // We need to do this because there is a race condition between someone
350 // releasing a reference on this BpBinder, and a new reference on its handle
351 // arriving from the driver.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352 IBinder* b = e->binder;
Yi Kongfdd8da92018-06-07 17:52:27 -0700353 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
Todd Poynora7b0f042013-06-18 17:25:37 -0700354 if (handle == 0) {
355 // Special case for context manager...
356 // The context manager is the only object for which we create
357 // a BpBinder proxy without already holding a reference.
358 // Perform a dummy transaction to ensure the context manager
359 // is registered before we create the first local reference
360 // to it (which will occur when creating the BpBinder).
361 // If a local reference is created for the BpBinder when the
362 // context manager is not present, the driver will fail to
363 // provide a reference to the context manager, but the
364 // driver API does not return status.
365 //
366 // Note that this is not race-free if the context manager
367 // dies while this code runs.
Todd Poynora7b0f042013-06-18 17:25:37 -0700368
Steven Moreland9514b202020-09-21 18:03:27 +0000369 IPCThreadState* ipc = IPCThreadState::self();
370
371 CallRestriction originalCallRestriction = ipc->getCallRestriction();
372 ipc->setCallRestriction(CallRestriction::NONE);
373
Todd Poynora7b0f042013-06-18 17:25:37 -0700374 Parcel data;
Steven Moreland9514b202020-09-21 18:03:27 +0000375 status_t status = ipc->transact(
Yi Kongfdd8da92018-06-07 17:52:27 -0700376 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
Steven Moreland9514b202020-09-21 18:03:27 +0000377
378 ipc->setCallRestriction(originalCallRestriction);
379
Todd Poynora7b0f042013-06-18 17:25:37 -0700380 if (status == DEAD_OBJECT)
Yi Kongfdd8da92018-06-07 17:52:27 -0700381 return nullptr;
Todd Poynora7b0f042013-06-18 17:25:37 -0700382 }
383
Steven Moreland7c166e12024-07-20 00:40:56 +0000384 sp<BpBinder> b = BpBinder::PrivateAccessor::create(handle, &postTask);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000385 e->binder = b.get();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800386 if (b) e->refs = b->getWeakRefs();
387 result = b;
388 } else {
389 // This little bit of nastyness is to allow us to add a primary
390 // reference to the remote proxy when this team doesn't have one
391 // but another team is sending the handle to us.
392 result.force_set(b);
393 e->refs->decWeak(this);
394 }
395 }
396
Steven Moreland7c166e12024-07-20 00:40:56 +0000397 _l.unlock();
398
399 if (postTask) postTask();
400
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401 return result;
402}
403
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800404void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
405{
Tomasz Wasilczyk66ee1922023-10-26 14:53:49 -0700406 std::unique_lock<std::mutex> _l(mLock);
Jooyung Han1b228f42020-01-30 13:41:12 +0900407
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408 handle_entry* e = lookupHandleLocked(handle);
409
410 // This handle may have already been replaced with a new BpBinder
411 // (if someone failed the AttemptIncWeak() above); we don't want
412 // to overwrite it.
Yi Kongfdd8da92018-06-07 17:52:27 -0700413 if (e && e->binder == binder) e->binder = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414}
415
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800416String8 ProcessState::makeBinderThreadName() {
Frederick Maylea9675a72024-08-05 14:21:53 -0700417 int32_t s = mThreadPoolSeq.fetch_add(1, std::memory_order_release);
Philip Cuadraa082fa82016-04-08 10:29:14 -0700418 pid_t pid = getpid();
Steven Moreland281abad2022-02-24 22:06:40 +0000419
420 std::string_view driverName = mDriverName.c_str();
421 android::base::ConsumePrefix(&driverName, "/dev/");
422
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800423 String8 name;
Steven Moreland281abad2022-02-24 22:06:40 +0000424 name.appendFormat("%.*s:%d_%X", static_cast<int>(driverName.length()), driverName.data(), pid,
425 s);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800426 return name;
427}
428
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800429void ProcessState::spawnPooledThread(bool isMain)
430{
431 if (mThreadPoolStarted) {
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800432 String8 name = makeBinderThreadName();
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000433 ALOGV("Spawning new pooled thread, name=%s\n", name.c_str());
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000434 sp<Thread> t = sp<PoolThread>::make(isMain);
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000435 t->run(name.c_str());
Elie Kheirallah47431c12022-04-21 23:46:17 +0000436 mKernelStartedThreads++;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800437 }
Steven Moreland3e9debc2023-06-15 00:35:29 +0000438 // TODO: if startThreadPool is called on another thread after the process
439 // starts up, the kernel might think that it already requested those
440 // binder threads, and additional won't be started. This is likely to
441 // cause deadlocks, and it will also cause getThreadPoolMaxTotalThreadCount
442 // to return too high of a value.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800443}
444
Mathias Agopian1b80f792012-04-17 16:11:08 -0700445status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
Steven Moreland1fdb98b2020-03-06 21:42:12 +0000446 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
447 "Binder threadpool cannot be shrunk after starting");
Mathias Agopian1b80f792012-04-17 16:11:08 -0700448 status_t result = NO_ERROR;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700449 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
450 mMaxThreads = maxThreads;
451 } else {
Mathias Agopian1b80f792012-04-17 16:11:08 -0700452 result = -errno;
453 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
454 }
455 return result;
456}
457
Elie Kheirallah47431c12022-04-21 23:46:17 +0000458size_t ProcessState::getThreadPoolMaxTotalThreadCount() const {
Frederick Mayle908b09c2024-08-05 14:10:40 -0700459 // Need to read `mKernelStartedThreads` before `mThreadPoolStarted` (with
460 // non-relaxed memory ordering) to avoid a race like the following:
461 //
462 // thread A: if (mThreadPoolStarted) { // evaluates false
463 // thread B: mThreadPoolStarted = true;
464 // thread B: mKernelStartedThreads++;
465 // thread A: size_t kernelStarted = mKernelStartedThreads;
466 // thread A: LOG_ALWAYS_FATAL_IF(kernelStarted != 0, ...);
467 size_t kernelStarted = mKernelStartedThreads;
468
Elie Kheirallah47431c12022-04-21 23:46:17 +0000469 if (mThreadPoolStarted) {
Frederick Mayle263507f2024-05-30 14:54:27 -0700470 size_t max = mMaxThreads;
471 size_t current = mCurrentThreads;
472
473 LOG_ALWAYS_FATAL_IF(kernelStarted > max + 1,
474 "too many kernel-started threads: %zu > %zu + 1", kernelStarted, max);
Steven Moreland3e9debc2023-06-15 00:35:29 +0000475
476 // calling startThreadPool starts a thread
477 size_t threads = 1;
478
479 // the kernel is configured to start up to mMaxThreads more threads
Frederick Mayle263507f2024-05-30 14:54:27 -0700480 threads += max;
Steven Moreland3e9debc2023-06-15 00:35:29 +0000481
482 // Users may call IPCThreadState::joinThreadPool directly. We don't
483 // currently have a way to count this directly (it could be added by
484 // adding a separate private joinKernelThread method in IPCThreadState).
485 // So, if we are in a race between the kernel thread variable being
486 // incremented in this file and mCurrentThreads being incremented
487 // in IPCThreadState, temporarily forget about the extra join threads.
488 // This is okay, because most callers of this method only care about
489 // having 0, 1, or more threads.
Frederick Mayle263507f2024-05-30 14:54:27 -0700490 if (current > kernelStarted) {
491 threads += current - kernelStarted;
Steven Moreland3e9debc2023-06-15 00:35:29 +0000492 }
493
494 return threads;
Elie Kheirallah47431c12022-04-21 23:46:17 +0000495 }
Steven Moreland3e9debc2023-06-15 00:35:29 +0000496
Yifan Hong84bedeb2021-04-21 21:37:17 -0700497 // must not be initialized or maybe has poll thread setup, we
498 // currently don't track this in libbinder
Frederick Mayle263507f2024-05-30 14:54:27 -0700499 LOG_ALWAYS_FATAL_IF(kernelStarted != 0, "Expecting 0 kernel started threads but have %zu",
500 kernelStarted);
Elie Kheirallah47431c12022-04-21 23:46:17 +0000501 return mCurrentThreads;
Yifan Hong84bedeb2021-04-21 21:37:17 -0700502}
503
Devin Moore4354f712022-12-08 01:44:46 +0000504bool ProcessState::isThreadPoolStarted() const {
505 return mThreadPoolStarted;
506}
507
Steven Morelandc86333d2024-12-13 20:03:37 +0000508void ProcessState::checkExpectingThreadPoolStart() const {
509 if (mThreadPoolStarted) return;
510
511 // this is also racey, but you should setup the threadpool in the main thread. If that is an
512 // issue, we can check if we are the process leader, but haven't seen the issue in practice.
513 size_t requestedThreads = mMaxThreads.load();
514
515 // if it's manually set to the default, we do ignore it here...
516 if (requestedThreads == DEFAULT_MAX_BINDER_THREADS) return;
517 if (requestedThreads == 0) return;
518
519 ALOGW("Thread pool configuration of size %zu requested, but startThreadPool was not called.",
520 requestedThreads);
521}
522
Carlos Llamas4f886702022-03-07 22:07:03 -0800523#define DRIVER_FEATURES_PATH "/dev/binderfs/features/"
524bool ProcessState::isDriverFeatureEnabled(const DriverFeature feature) {
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700525 // Use static variable to cache the results.
526 if (feature == DriverFeature::ONEWAY_SPAM_DETECTION) {
527 static bool enabled = readDriverFeatureFile(DRIVER_FEATURES_PATH "oneway_spam_detection");
528 return enabled;
Carlos Llamas4f886702022-03-07 22:07:03 -0800529 }
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700530 if (feature == DriverFeature::EXTENDED_ERROR) {
531 static bool enabled = readDriverFeatureFile(DRIVER_FEATURES_PATH "extended_error");
532 return enabled;
Carlos Llamas4f886702022-03-07 22:07:03 -0800533 }
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700534 if (feature == DriverFeature::FREEZE_NOTIFICATION) {
535 static bool enabled = readDriverFeatureFile(DRIVER_FEATURES_PATH "freeze_notification");
536 return enabled;
537 }
538 return false;
Carlos Llamas4f886702022-03-07 22:07:03 -0800539}
540
Hang Lub185ac02021-03-24 13:17:22 +0800541status_t ProcessState::enableOnewaySpamDetection(bool enable) {
542 uint32_t enableDetection = enable ? 1 : 0;
543 if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
Martijn Coenende0a39e2021-04-22 14:38:46 +0200544 ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
Hang Lub185ac02021-03-24 13:17:22 +0800545 return -errno;
546 }
547 return NO_ERROR;
548}
549
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800550void ProcessState::giveThreadPoolName() {
Tomasz Wasilczyk0bfea2d2023-08-11 00:06:51 +0000551 androidSetThreadName(makeBinderThreadName().c_str());
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800552}
553
Iliyan Malchev32062242017-04-10 14:06:11 -0700554String8 ProcessState::getDriverName() {
555 return mDriverName;
556}
557
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000558static unique_fd open_driver(const char* driver, String8* error) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700559 auto fd = unique_fd(open(driver, O_RDWR | O_CLOEXEC));
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700560 if (!fd.ok()) {
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000561 error->appendFormat("%d (%s) Opening '%s' failed", errno, strerror(errno), driver);
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700562 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700563 }
564 int vers = 0;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700565 int result = ioctl(fd.get(), BINDER_VERSION, &vers);
Steven Moreland13a43c92021-08-30 13:21:48 -0700566 if (result == -1) {
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000567 error->appendFormat("%d (%s) Binder ioctl to obtain version failed", errno,
568 strerror(errno));
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700569 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700570 }
571 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000572 error->appendFormat("Binder driver protocol(%d) does not match user space protocol(%d)! "
573 "ioctl() return value: %d",
574 vers, BINDER_CURRENT_PROTOCOL_VERSION, result);
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700575 return {};
Steven Moreland13a43c92021-08-30 13:21:48 -0700576 }
577 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700578 result = ioctl(fd.get(), BINDER_SET_MAX_THREADS, &maxThreads);
Steven Moreland13a43c92021-08-30 13:21:48 -0700579 if (result == -1) {
580 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
581 }
582 uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700583 result = ioctl(fd.get(), BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
Steven Moreland13a43c92021-08-30 13:21:48 -0700584 if (result == -1) {
Carlos Llamas4f886702022-03-07 22:07:03 -0800585 ALOGE_IF(ProcessState::isDriverFeatureEnabled(
586 ProcessState::DriverFeature::ONEWAY_SPAM_DETECTION),
587 "Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800588 }
589 return fd;
590}
591
Steven Moreland13a43c92021-08-30 13:21:48 -0700592ProcessState::ProcessState(const char* driver)
593 : mDriverName(String8(driver)),
594 mDriverFD(-1),
595 mVMStart(MAP_FAILED),
Steven Moreland13a43c92021-08-30 13:21:48 -0700596 mExecutingThreadsCount(0),
Steven Moreland13a43c92021-08-30 13:21:48 -0700597 mMaxThreads(DEFAULT_MAX_BINDER_THREADS),
Elie Kheirallah47431c12022-04-21 23:46:17 +0000598 mCurrentThreads(0),
599 mKernelStartedThreads(0),
Tomasz Wasilczyk1d46f582024-05-21 15:06:29 -0700600 mStarvationStartTime(never()),
Steven Morelandee9df902021-10-14 14:00:08 -0700601 mForked(false),
Steven Moreland13a43c92021-08-30 13:21:48 -0700602 mThreadPoolStarted(false),
603 mThreadPoolSeq(1),
604 mCallRestriction(CallRestriction::NONE) {
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000605 String8 error;
606 unique_fd opened = open_driver(driver, &error);
Steven Moreland13a43c92021-08-30 13:21:48 -0700607
608 if (opened.ok()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800609 // mmap the binder, providing a chunk of virtual address space to receive transactions.
Steven Moreland13a43c92021-08-30 13:21:48 -0700610 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE,
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700611 opened.get(), 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800612 if (mVMStart == MAP_FAILED) {
613 // *sigh*
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700614 ALOGE("Using %s failed: unable to mmap transaction memory.", driver);
615 opened.reset();
Iliyan Malchev32062242017-04-10 14:06:11 -0700616 mDriverName.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800617 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800618 }
Jeff Browne16986c2011-07-08 18:52:57 -0700619
Kevin Lindkviste8e12432022-11-23 13:23:42 +0100620#if defined(EXPECT_BINDER_OPEN_SUCCESS)
Steven Moreland2fd1feb2024-05-25 00:13:10 +0000621 LOG_ALWAYS_FATAL_IF(!opened.ok(),
622 "Binder driver '%s' could not be opened. Error: %s. Terminating.",
Steven Morelandd3e6cda2024-08-06 20:01:13 +0000623 driver, error.c_str());
Steven Moreland24bc0d12019-10-11 12:29:20 -0700624#endif
Steven Moreland13a43c92021-08-30 13:21:48 -0700625
626 if (opened.ok()) {
Tomasz Wasilczyk88aa8c32023-11-01 09:46:07 -0700627 mDriverFD = opened.release();
Steven Moreland13a43c92021-08-30 13:21:48 -0700628 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800629}
630
631ProcessState::~ProcessState()
632{
zhongjieff405782016-03-09 15:05:04 +0800633 if (mDriverFD >= 0) {
634 if (mVMStart != MAP_FAILED) {
Steven Moreland072cc7e2019-07-12 21:01:54 +0000635 munmap(mVMStart, BINDER_VM_SIZE);
zhongjieff405782016-03-09 15:05:04 +0800636 }
637 close(mDriverFD);
638 }
639 mDriverFD = -1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800640}
Jooyung Han1b228f42020-01-30 13:41:12 +0900641
Steven Moreland61ff8492019-09-26 16:05:45 -0700642} // namespace android