blob: c4cf3e68b247d756cac9b33f4354c8308c17b4f2 [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 Moreland281abad2022-02-24 22:06:40 +000022#include <android-base/strings.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070023#include <binder/BpBinder.h>
24#include <binder/IPCThreadState.h>
Steven Moreland2716e112018-02-23 14:57:20 -080025#include <binder/IServiceManager.h>
Steven Morelandc709dd82019-08-05 20:30:14 -070026#include <binder/Stability.h>
Steven Moreland2716e112018-02-23 14:57:20 -080027#include <cutils/atomic.h>
Andrei Homescu8028ff42022-03-14 22:11:54 +000028#include <utils/AndroidThreads.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080029#include <utils/Log.h>
30#include <utils/String8.h>
Andrei Homescu8028ff42022-03-14 22:11:54 +000031#include <utils/Thread.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
Steven Morelanda4853cd2019-07-12 15:44:37 -070033#include "Static.h"
Steven Moreland6ba5a252021-05-04 22:49:00 +000034#include "binder_module.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
36#include <errno.h>
37#include <fcntl.h>
Steven Moreland4fdb12f2020-07-21 02:21:48 +000038#include <mutex>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080039#include <stdio.h>
40#include <stdlib.h>
41#include <unistd.h>
42#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>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080046
Steven Moreland072cc7e2019-07-12 21:01:54 +000047#define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
Wale Ogunwale376b8222015-04-13 16:16:10 -070048#define DEFAULT_MAX_BINDER_THREADS 15
Hang Lub185ac02021-03-24 13:17:22 +080049#define DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION 1
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050
Martijn Coenen7bca77a2019-03-13 11:51:08 +000051#ifdef __ANDROID_VNDK__
52const char* kDefaultDriver = "/dev/vndbinder";
53#else
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070054const char* kDefaultDriver = "/dev/binder";
Martijn Coenen7bca77a2019-03-13 11:51:08 +000055#endif
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070056
Philip Cuadraa082fa82016-04-08 10:29:14 -070057// -------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
59namespace android {
Wale Ogunwale376b8222015-04-13 16:16:10 -070060
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061class PoolThread : public Thread
62{
63public:
Chih-Hung Hsiehe2347b72016-04-25 15:41:05 -070064 explicit PoolThread(bool isMain)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065 : mIsMain(isMain)
66 {
67 }
Jooyung Han1b228f42020-01-30 13:41:12 +090068
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080069protected:
70 virtual bool threadLoop()
71 {
72 IPCThreadState::self()->joinThreadPool(mIsMain);
73 return false;
74 }
Jooyung Han1b228f42020-01-30 13:41:12 +090075
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076 const bool mIsMain;
77};
78
79sp<ProcessState> ProcessState::self()
80{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000081 return init(kDefaultDriver, false /*requireDefault*/);
Martijn Coenen55d871c2017-03-21 15:56:40 -070082}
83
84sp<ProcessState> ProcessState::initWithDriver(const char* driver)
85{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000086 return init(driver, true /*requireDefault*/);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087}
88
Steven Moreland072cc7e2019-07-12 21:01:54 +000089sp<ProcessState> ProcessState::selfOrNull()
90{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000091 return init(nullptr, false /*requireDefault*/);
92}
93
Steven Morelandee9df902021-10-14 14:00:08 -070094[[clang::no_destroy]] static sp<ProcessState> gProcess;
95[[clang::no_destroy]] static std::mutex gProcessMutex;
96
97static void verifyNotForked(bool forked) {
Steven Morelandbd98e0f2021-10-14 14:24:15 -070098 LOG_ALWAYS_FATAL_IF(forked, "libbinder ProcessState can not be used after fork");
Steven Morelandee9df902021-10-14 14:00:08 -070099}
100
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000101sp<ProcessState> ProcessState::init(const char *driver, bool requireDefault)
102{
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000103
104 if (driver == nullptr) {
105 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Morelandee9df902021-10-14 14:00:08 -0700106 if (gProcess) {
107 verifyNotForked(gProcess->mForked);
108 }
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000109 return gProcess;
110 }
111
112 [[clang::no_destroy]] static std::once_flag gProcessOnce;
113 std::call_once(gProcessOnce, [&](){
114 if (access(driver, R_OK) == -1) {
115 ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
116 driver = "/dev/binder";
117 }
118
Steven Morelandee9df902021-10-14 14:00:08 -0700119 // we must install these before instantiating the gProcess object,
120 // otherwise this would race with creating it, and there could be the
121 // possibility of an invalid gProcess object forked by another thread
122 // before these are installed
123 int ret = pthread_atfork(ProcessState::onFork, ProcessState::parentPostFork,
124 ProcessState::childPostFork);
125 LOG_ALWAYS_FATAL_IF(ret != 0, "pthread_atfork error %s", strerror(ret));
126
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000127 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000128 gProcess = sp<ProcessState>::make(driver);
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000129 });
130
131 if (requireDefault) {
132 // Detect if we are trying to initialize with a different driver, and
133 // consider that an error. ProcessState will only be initialized once above.
134 LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,
135 "ProcessState was already initialized with %s,"
136 " can't initialize with %s.",
137 gProcess->getDriverName().c_str(), driver);
138 }
139
Steven Morelandee9df902021-10-14 14:00:08 -0700140 verifyNotForked(gProcess->mForked);
Colin Cross9d45ccc2017-06-20 17:48:33 -0700141 return gProcess;
142}
143
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800144sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800145{
Steven Morelandc709dd82019-08-05 20:30:14 -0700146 sp<IBinder> context = getStrongProxyForHandle(0);
147
Steven Moreland4da8fb02020-12-29 22:51:32 +0000148 if (context) {
149 // The root object is special since we get it directly from the driver, it is never
150 // written by Parcell::writeStrongBinder.
151 internal::Stability::markCompilationUnit(context.get());
152 } else {
153 ALOGW("Not able to get context object on %s.", mDriverName.c_str());
Steven Moreland8d93a712020-02-19 15:16:15 -0800154 }
155
Steven Morelandc709dd82019-08-05 20:30:14 -0700156 return context;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157}
158
Steven Morelandee9df902021-10-14 14:00:08 -0700159void ProcessState::onFork() {
160 // make sure another thread isn't currently retrieving ProcessState
161 gProcessMutex.lock();
162}
163
164void ProcessState::parentPostFork() {
165 gProcessMutex.unlock();
166}
167
168void ProcessState::childPostFork() {
169 // another thread might call fork before gProcess is instantiated, but after
170 // the thread handler is installed
171 if (gProcess) {
172 gProcess->mForked = true;
173 }
174 gProcessMutex.unlock();
175}
176
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800177void ProcessState::startThreadPool()
178{
179 AutoMutex _l(mLock);
180 if (!mThreadPoolStarted) {
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000181 if (mMaxThreads == 0) {
182 ALOGW("Extra binder thread started, but 0 threads requested. Do not use "
183 "*startThreadPool when zero threads are requested.");
184 }
185
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800186 mThreadPoolStarted = true;
187 spawnPooledThread(true);
188 }
189}
190
Steven Moreland61096622020-08-31 23:36:39 +0000191bool ProcessState::becomeContextManager()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192{
Steven Moreland4411d712019-07-12 14:02:53 -0700193 AutoMutex _l(mLock);
Jeff Browne16986c2011-07-08 18:52:57 -0700194
Steven Moreland4411d712019-07-12 14:02:53 -0700195 flat_binder_object obj {
196 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
197 };
Steven Moreland3085a472018-12-26 13:59:23 -0800198
Steven Moreland4411d712019-07-12 14:02:53 -0700199 int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
Steven Moreland3085a472018-12-26 13:59:23 -0800200
Steven Moreland4411d712019-07-12 14:02:53 -0700201 // fallback to original method
202 if (result != 0) {
203 android_errorWriteLog(0x534e4554, "121035042");
Steven Moreland3085a472018-12-26 13:59:23 -0800204
Hungming Chen28b42522020-08-28 17:29:55 +0800205 int unused = 0;
206 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800207 }
Steven Moreland4411d712019-07-12 14:02:53 -0700208
209 if (result == -1) {
Steven Moreland4411d712019-07-12 14:02:53 -0700210 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
211 }
212
213 return result == 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214}
215
Colin Cross9d45ccc2017-06-20 17:48:33 -0700216// Get references to userspace objects held by the kernel binder driver
217// Writes up to count elements into buf, and returns the total number
218// of references the kernel has, which may be larger than count.
219// buf may be NULL if count is 0. The pointers returned by this method
220// should only be used for debugging and not dereferenced, they may
221// already be invalid.
222ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
223{
Colin Cross9d45ccc2017-06-20 17:48:33 -0700224 binder_node_debug_info info = {};
225
Yi Kongfdd8da92018-06-07 17:52:27 -0700226 uintptr_t* end = buf ? buf + buf_count : nullptr;
Colin Cross9d45ccc2017-06-20 17:48:33 -0700227 size_t count = 0;
228
229 do {
230 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
231 if (result < 0) {
232 return -1;
233 }
234 if (info.ptr != 0) {
235 if (buf && buf < end)
236 *buf++ = info.ptr;
237 count++;
238 if (buf && buf < end)
239 *buf++ = info.cookie;
240 count++;
241 }
242 } while (info.ptr != 0);
243
244 return count;
245}
246
Jon Spivack902e6fc2019-10-18 21:22:37 -0700247// Queries the driver for the current strong reference count of the node
248// that the handle points to. Can only be used by the servicemanager.
249//
250// Returns -1 in case of failure, otherwise the strong reference count.
Steven Morelande8393882020-12-18 02:27:20 +0000251ssize_t ProcessState::getStrongRefCountForNode(const sp<BpBinder>& binder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000252 if (binder->isRpcBinder()) return -1;
253
Jon Spivack902e6fc2019-10-18 21:22:37 -0700254 binder_node_info_for_ref info;
255 memset(&info, 0, sizeof(binder_node_info_for_ref));
256
Steven Moreland99157622021-09-13 16:27:34 -0700257 info.handle = binder->getPrivateAccessor().binderHandle();
Jon Spivack902e6fc2019-10-18 21:22:37 -0700258
259 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
260
261 if (result != OK) {
262 static bool logged = false;
263 if (!logged) {
264 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
265 logged = true;
266 }
267 return -1;
268 }
269
270 return info.strong_count;
271}
272
Steven Moreland7732a092019-01-02 17:54:16 -0800273void ProcessState::setCallRestriction(CallRestriction restriction) {
Steven Moreland28723ae2019-04-01 18:52:30 -0700274 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
275 "Call restrictions must be set before the threadpool is started.");
Steven Moreland7732a092019-01-02 17:54:16 -0800276
277 mCallRestriction = restriction;
278}
279
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
281{
282 const size_t N=mHandleToObject.size();
283 if (N <= (size_t)handle) {
284 handle_entry e;
Yi Kongfdd8da92018-06-07 17:52:27 -0700285 e.binder = nullptr;
286 e.refs = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
Yi Kongfdd8da92018-06-07 17:52:27 -0700288 if (err < NO_ERROR) return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800289 }
290 return &mHandleToObject.editItemAt(handle);
291}
292
293sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
294{
295 sp<IBinder> result;
296
297 AutoMutex _l(mLock);
298
299 handle_entry* e = lookupHandleLocked(handle);
300
Yi Kongfdd8da92018-06-07 17:52:27 -0700301 if (e != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800302 // We need to create a new BpBinder if there isn't currently one, OR we
Steven Morelande171d622019-07-17 16:06:01 -0700303 // are unable to acquire a weak reference on this current one. The
304 // attemptIncWeak() is safe because we know the BpBinder destructor will always
305 // call expungeHandle(), which acquires the same lock we are holding now.
306 // We need to do this because there is a race condition between someone
307 // releasing a reference on this BpBinder, and a new reference on its handle
308 // arriving from the driver.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800309 IBinder* b = e->binder;
Yi Kongfdd8da92018-06-07 17:52:27 -0700310 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
Todd Poynora7b0f042013-06-18 17:25:37 -0700311 if (handle == 0) {
312 // Special case for context manager...
313 // The context manager is the only object for which we create
314 // a BpBinder proxy without already holding a reference.
315 // Perform a dummy transaction to ensure the context manager
316 // is registered before we create the first local reference
317 // to it (which will occur when creating the BpBinder).
318 // If a local reference is created for the BpBinder when the
319 // context manager is not present, the driver will fail to
320 // provide a reference to the context manager, but the
321 // driver API does not return status.
322 //
323 // Note that this is not race-free if the context manager
324 // dies while this code runs.
Todd Poynora7b0f042013-06-18 17:25:37 -0700325
Steven Moreland9514b202020-09-21 18:03:27 +0000326 IPCThreadState* ipc = IPCThreadState::self();
327
328 CallRestriction originalCallRestriction = ipc->getCallRestriction();
329 ipc->setCallRestriction(CallRestriction::NONE);
330
Todd Poynora7b0f042013-06-18 17:25:37 -0700331 Parcel data;
Steven Moreland9514b202020-09-21 18:03:27 +0000332 status_t status = ipc->transact(
Yi Kongfdd8da92018-06-07 17:52:27 -0700333 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
Steven Moreland9514b202020-09-21 18:03:27 +0000334
335 ipc->setCallRestriction(originalCallRestriction);
336
Todd Poynora7b0f042013-06-18 17:25:37 -0700337 if (status == DEAD_OBJECT)
Yi Kongfdd8da92018-06-07 17:52:27 -0700338 return nullptr;
Todd Poynora7b0f042013-06-18 17:25:37 -0700339 }
340
Steven Moreland99157622021-09-13 16:27:34 -0700341 sp<BpBinder> b = BpBinder::PrivateAccessor::create(handle);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000342 e->binder = b.get();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343 if (b) e->refs = b->getWeakRefs();
344 result = b;
345 } else {
346 // This little bit of nastyness is to allow us to add a primary
347 // reference to the remote proxy when this team doesn't have one
348 // but another team is sending the handle to us.
349 result.force_set(b);
350 e->refs->decWeak(this);
351 }
352 }
353
354 return result;
355}
356
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800357void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
358{
359 AutoMutex _l(mLock);
Jooyung Han1b228f42020-01-30 13:41:12 +0900360
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800361 handle_entry* e = lookupHandleLocked(handle);
362
363 // This handle may have already been replaced with a new BpBinder
364 // (if someone failed the AttemptIncWeak() above); we don't want
365 // to overwrite it.
Yi Kongfdd8da92018-06-07 17:52:27 -0700366 if (e && e->binder == binder) e->binder = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800367}
368
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800369String8 ProcessState::makeBinderThreadName() {
370 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
Philip Cuadraa082fa82016-04-08 10:29:14 -0700371 pid_t pid = getpid();
Steven Moreland281abad2022-02-24 22:06:40 +0000372
373 std::string_view driverName = mDriverName.c_str();
374 android::base::ConsumePrefix(&driverName, "/dev/");
375
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800376 String8 name;
Steven Moreland281abad2022-02-24 22:06:40 +0000377 name.appendFormat("%.*s:%d_%X", static_cast<int>(driverName.length()), driverName.data(), pid,
378 s);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800379 return name;
380}
381
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800382void ProcessState::spawnPooledThread(bool isMain)
383{
384 if (mThreadPoolStarted) {
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800385 String8 name = makeBinderThreadName();
386 ALOGV("Spawning new pooled thread, name=%s\n", name.string());
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000387 sp<Thread> t = sp<PoolThread>::make(isMain);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800388 t->run(name.string());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389 }
390}
391
Mathias Agopian1b80f792012-04-17 16:11:08 -0700392status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
Steven Moreland1fdb98b2020-03-06 21:42:12 +0000393 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
394 "Binder threadpool cannot be shrunk after starting");
Mathias Agopian1b80f792012-04-17 16:11:08 -0700395 status_t result = NO_ERROR;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700396 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
397 mMaxThreads = maxThreads;
398 } else {
Mathias Agopian1b80f792012-04-17 16:11:08 -0700399 result = -errno;
400 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
401 }
402 return result;
403}
404
Yifan Hong84bedeb2021-04-21 21:37:17 -0700405size_t ProcessState::getThreadPoolMaxThreadCount() const {
406 // may actually be one more than this, if join is called
407 if (mThreadPoolStarted) return mMaxThreads;
408 // must not be initialized or maybe has poll thread setup, we
409 // currently don't track this in libbinder
410 return 0;
411}
412
Carlos Llamas4f886702022-03-07 22:07:03 -0800413#define DRIVER_FEATURES_PATH "/dev/binderfs/features/"
414bool ProcessState::isDriverFeatureEnabled(const DriverFeature feature) {
415 static const char* const names[] = {
416 [static_cast<int>(DriverFeature::ONEWAY_SPAM_DETECTION)] =
417 DRIVER_FEATURES_PATH "oneway_spam_detection",
Carlos Llamasb235b122021-12-20 06:38:44 -0800418 [static_cast<int>(DriverFeature::EXTENDED_ERROR)] =
419 DRIVER_FEATURES_PATH "extended_error",
Carlos Llamas4f886702022-03-07 22:07:03 -0800420 };
421 int fd = open(names[static_cast<int>(feature)], O_RDONLY | O_CLOEXEC);
422 char on;
423 if (fd == -1) {
424 ALOGE_IF(errno != ENOENT, "%s: cannot open %s: %s", __func__,
425 names[static_cast<int>(feature)], strerror(errno));
426 return false;
427 }
428 if (read(fd, &on, sizeof(on)) == -1) {
429 ALOGE("%s: error reading to %s: %s", __func__,
430 names[static_cast<int>(feature)], strerror(errno));
431 return false;
432 }
433 close(fd);
434 return on == '1';
435}
436
Hang Lub185ac02021-03-24 13:17:22 +0800437status_t ProcessState::enableOnewaySpamDetection(bool enable) {
438 uint32_t enableDetection = enable ? 1 : 0;
439 if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
Martijn Coenende0a39e2021-04-22 14:38:46 +0200440 ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
Hang Lub185ac02021-03-24 13:17:22 +0800441 return -errno;
442 }
443 return NO_ERROR;
444}
445
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800446void ProcessState::giveThreadPoolName() {
447 androidSetThreadName( makeBinderThreadName().string() );
448}
449
Iliyan Malchev32062242017-04-10 14:06:11 -0700450String8 ProcessState::getDriverName() {
451 return mDriverName;
452}
453
Steven Moreland13a43c92021-08-30 13:21:48 -0700454static base::Result<int> open_driver(const char* driver) {
Martijn Coenen55d871c2017-03-21 15:56:40 -0700455 int fd = open(driver, O_RDWR | O_CLOEXEC);
Steven Moreland13a43c92021-08-30 13:21:48 -0700456 if (fd < 0) {
457 return base::ErrnoError() << "Opening '" << driver << "' failed";
458 }
459 int vers = 0;
460 status_t result = ioctl(fd, BINDER_VERSION, &vers);
461 if (result == -1) {
462 close(fd);
463 return base::ErrnoError() << "Binder ioctl to obtain version failed";
464 }
465 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
466 close(fd);
467 return base::Error() << "Binder driver protocol(" << vers
468 << ") does not match user space protocol("
469 << BINDER_CURRENT_PROTOCOL_VERSION
470 << ")! ioctl() return value: " << result;
471 }
472 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
473 result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
474 if (result == -1) {
475 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
476 }
477 uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
478 result = ioctl(fd, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
479 if (result == -1) {
Carlos Llamas4f886702022-03-07 22:07:03 -0800480 ALOGE_IF(ProcessState::isDriverFeatureEnabled(
481 ProcessState::DriverFeature::ONEWAY_SPAM_DETECTION),
482 "Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800483 }
484 return fd;
485}
486
Steven Moreland13a43c92021-08-30 13:21:48 -0700487ProcessState::ProcessState(const char* driver)
488 : mDriverName(String8(driver)),
489 mDriverFD(-1),
490 mVMStart(MAP_FAILED),
491 mThreadCountLock(PTHREAD_MUTEX_INITIALIZER),
492 mThreadCountDecrement(PTHREAD_COND_INITIALIZER),
493 mExecutingThreadsCount(0),
494 mWaitingForThreads(0),
495 mMaxThreads(DEFAULT_MAX_BINDER_THREADS),
496 mStarvationStartTimeMs(0),
Steven Morelandee9df902021-10-14 14:00:08 -0700497 mForked(false),
Steven Moreland13a43c92021-08-30 13:21:48 -0700498 mThreadPoolStarted(false),
499 mThreadPoolSeq(1),
500 mCallRestriction(CallRestriction::NONE) {
501 base::Result<int> opened = open_driver(driver);
502
503 if (opened.ok()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800504 // mmap the binder, providing a chunk of virtual address space to receive transactions.
Steven Moreland13a43c92021-08-30 13:21:48 -0700505 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE,
506 opened.value(), 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800507 if (mVMStart == MAP_FAILED) {
Steven Moreland13a43c92021-08-30 13:21:48 -0700508 close(opened.value());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800509 // *sigh*
Steven Moreland13a43c92021-08-30 13:21:48 -0700510 opened = base::Error()
511 << "Using " << driver << " failed: unable to mmap transaction memory.";
Iliyan Malchev32062242017-04-10 14:06:11 -0700512 mDriverName.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800513 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800514 }
Jeff Browne16986c2011-07-08 18:52:57 -0700515
Steven Moreland24bc0d12019-10-11 12:29:20 -0700516#ifdef __ANDROID__
Steven Moreland13a43c92021-08-30 13:21:48 -0700517 LOG_ALWAYS_FATAL_IF(!opened.ok(), "Binder driver '%s' could not be opened. Terminating: %s",
518 driver, opened.error().message().c_str());
Steven Moreland24bc0d12019-10-11 12:29:20 -0700519#endif
Steven Moreland13a43c92021-08-30 13:21:48 -0700520
521 if (opened.ok()) {
522 mDriverFD = opened.value();
523 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800524}
525
526ProcessState::~ProcessState()
527{
zhongjieff405782016-03-09 15:05:04 +0800528 if (mDriverFD >= 0) {
529 if (mVMStart != MAP_FAILED) {
Steven Moreland072cc7e2019-07-12 21:01:54 +0000530 munmap(mVMStart, BINDER_VM_SIZE);
zhongjieff405782016-03-09 15:05:04 +0800531 }
532 close(mDriverFD);
533 }
534 mDriverFD = -1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800535}
Jooyung Han1b228f42020-01-30 13:41:12 +0900536
Steven Moreland61ff8492019-09-26 16:05:45 -0700537} // namespace android