blob: b14a83844746f3cd190dc77d04c1e30bdaed54f0 [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>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080028#include <utils/Log.h>
29#include <utils/String8.h>
Andrei Homescua643e2d2022-03-09 05:47:59 +000030#include <utils/threads.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031
Steven Morelanda4853cd2019-07-12 15:44:37 -070032#include "Static.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>
Steven Moreland4fdb12f2020-07-21 02:21:48 +000037#include <mutex>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080038#include <stdio.h>
39#include <stdlib.h>
40#include <unistd.h>
41#include <sys/ioctl.h>
42#include <sys/mman.h>
43#include <sys/stat.h>
Philip Cuadraa082fa82016-04-08 10:29:14 -070044#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080045
Steven Moreland072cc7e2019-07-12 21:01:54 +000046#define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
Wale Ogunwale376b8222015-04-13 16:16:10 -070047#define DEFAULT_MAX_BINDER_THREADS 15
Hang Lub185ac02021-03-24 13:17:22 +080048#define DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION 1
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080049
Martijn Coenen7bca77a2019-03-13 11:51:08 +000050#ifdef __ANDROID_VNDK__
51const char* kDefaultDriver = "/dev/vndbinder";
52#else
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070053const char* kDefaultDriver = "/dev/binder";
Martijn Coenen7bca77a2019-03-13 11:51:08 +000054#endif
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070055
Philip Cuadraa082fa82016-04-08 10:29:14 -070056// -------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057
58namespace android {
Wale Ogunwale376b8222015-04-13 16:16:10 -070059
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060class PoolThread : public Thread
61{
62public:
Chih-Hung Hsiehe2347b72016-04-25 15:41:05 -070063 explicit PoolThread(bool isMain)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064 : mIsMain(isMain)
65 {
66 }
Jooyung Han1b228f42020-01-30 13:41:12 +090067
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068protected:
69 virtual bool threadLoop()
70 {
71 IPCThreadState::self()->joinThreadPool(mIsMain);
72 return false;
73 }
Jooyung Han1b228f42020-01-30 13:41:12 +090074
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075 const bool mIsMain;
76};
77
78sp<ProcessState> ProcessState::self()
79{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000080 return init(kDefaultDriver, false /*requireDefault*/);
Martijn Coenen55d871c2017-03-21 15:56:40 -070081}
82
83sp<ProcessState> ProcessState::initWithDriver(const char* driver)
84{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000085 return init(driver, true /*requireDefault*/);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086}
87
Steven Moreland072cc7e2019-07-12 21:01:54 +000088sp<ProcessState> ProcessState::selfOrNull()
89{
Steven Moreland4fdb12f2020-07-21 02:21:48 +000090 return init(nullptr, false /*requireDefault*/);
91}
92
Steven Morelandee9df902021-10-14 14:00:08 -070093[[clang::no_destroy]] static sp<ProcessState> gProcess;
94[[clang::no_destroy]] static std::mutex gProcessMutex;
95
96static void verifyNotForked(bool forked) {
Steven Morelandbd98e0f2021-10-14 14:24:15 -070097 LOG_ALWAYS_FATAL_IF(forked, "libbinder ProcessState can not be used after fork");
Steven Morelandee9df902021-10-14 14:00:08 -070098}
99
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000100sp<ProcessState> ProcessState::init(const char *driver, bool requireDefault)
101{
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000102
103 if (driver == nullptr) {
104 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Morelandee9df902021-10-14 14:00:08 -0700105 if (gProcess) {
106 verifyNotForked(gProcess->mForked);
107 }
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000108 return gProcess;
109 }
110
111 [[clang::no_destroy]] static std::once_flag gProcessOnce;
112 std::call_once(gProcessOnce, [&](){
113 if (access(driver, R_OK) == -1) {
114 ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
115 driver = "/dev/binder";
116 }
117
Steven Morelandee9df902021-10-14 14:00:08 -0700118 // we must install these before instantiating the gProcess object,
119 // otherwise this would race with creating it, and there could be the
120 // possibility of an invalid gProcess object forked by another thread
121 // before these are installed
122 int ret = pthread_atfork(ProcessState::onFork, ProcessState::parentPostFork,
123 ProcessState::childPostFork);
124 LOG_ALWAYS_FATAL_IF(ret != 0, "pthread_atfork error %s", strerror(ret));
125
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000126 std::lock_guard<std::mutex> l(gProcessMutex);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000127 gProcess = sp<ProcessState>::make(driver);
Steven Moreland4fdb12f2020-07-21 02:21:48 +0000128 });
129
130 if (requireDefault) {
131 // Detect if we are trying to initialize with a different driver, and
132 // consider that an error. ProcessState will only be initialized once above.
133 LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,
134 "ProcessState was already initialized with %s,"
135 " can't initialize with %s.",
136 gProcess->getDriverName().c_str(), driver);
137 }
138
Steven Morelandee9df902021-10-14 14:00:08 -0700139 verifyNotForked(gProcess->mForked);
Colin Cross9d45ccc2017-06-20 17:48:33 -0700140 return gProcess;
141}
142
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800143sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800144{
Steven Morelandc709dd82019-08-05 20:30:14 -0700145 sp<IBinder> context = getStrongProxyForHandle(0);
146
Steven Moreland4da8fb02020-12-29 22:51:32 +0000147 if (context) {
148 // The root object is special since we get it directly from the driver, it is never
149 // written by Parcell::writeStrongBinder.
150 internal::Stability::markCompilationUnit(context.get());
151 } else {
152 ALOGW("Not able to get context object on %s.", mDriverName.c_str());
Steven Moreland8d93a712020-02-19 15:16:15 -0800153 }
154
Steven Morelandc709dd82019-08-05 20:30:14 -0700155 return context;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800156}
157
Steven Morelandee9df902021-10-14 14:00:08 -0700158void ProcessState::onFork() {
159 // make sure another thread isn't currently retrieving ProcessState
160 gProcessMutex.lock();
161}
162
163void ProcessState::parentPostFork() {
164 gProcessMutex.unlock();
165}
166
167void ProcessState::childPostFork() {
168 // another thread might call fork before gProcess is instantiated, but after
169 // the thread handler is installed
170 if (gProcess) {
171 gProcess->mForked = true;
172 }
173 gProcessMutex.unlock();
174}
175
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800176void ProcessState::startThreadPool()
177{
178 AutoMutex _l(mLock);
179 if (!mThreadPoolStarted) {
Steven Morelandf5a5bb82021-12-16 00:04:29 +0000180 if (mMaxThreads == 0) {
181 ALOGW("Extra binder thread started, but 0 threads requested. Do not use "
182 "*startThreadPool when zero threads are requested.");
183 }
184
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800185 mThreadPoolStarted = true;
186 spawnPooledThread(true);
187 }
188}
189
Steven Moreland61096622020-08-31 23:36:39 +0000190bool ProcessState::becomeContextManager()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800191{
Steven Moreland4411d712019-07-12 14:02:53 -0700192 AutoMutex _l(mLock);
Jeff Browne16986c2011-07-08 18:52:57 -0700193
Steven Moreland4411d712019-07-12 14:02:53 -0700194 flat_binder_object obj {
195 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
196 };
Steven Moreland3085a472018-12-26 13:59:23 -0800197
Steven Moreland4411d712019-07-12 14:02:53 -0700198 int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
Steven Moreland3085a472018-12-26 13:59:23 -0800199
Steven Moreland4411d712019-07-12 14:02:53 -0700200 // fallback to original method
201 if (result != 0) {
202 android_errorWriteLog(0x534e4554, "121035042");
Steven Moreland3085a472018-12-26 13:59:23 -0800203
Hungming Chen28b42522020-08-28 17:29:55 +0800204 int unused = 0;
205 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206 }
Steven Moreland4411d712019-07-12 14:02:53 -0700207
208 if (result == -1) {
Steven Moreland4411d712019-07-12 14:02:53 -0700209 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
210 }
211
212 return result == 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800213}
214
Colin Cross9d45ccc2017-06-20 17:48:33 -0700215// Get references to userspace objects held by the kernel binder driver
216// Writes up to count elements into buf, and returns the total number
217// of references the kernel has, which may be larger than count.
218// buf may be NULL if count is 0. The pointers returned by this method
219// should only be used for debugging and not dereferenced, they may
220// already be invalid.
221ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
222{
Colin Cross9d45ccc2017-06-20 17:48:33 -0700223 binder_node_debug_info info = {};
224
Yi Kongfdd8da92018-06-07 17:52:27 -0700225 uintptr_t* end = buf ? buf + buf_count : nullptr;
Colin Cross9d45ccc2017-06-20 17:48:33 -0700226 size_t count = 0;
227
228 do {
229 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
230 if (result < 0) {
231 return -1;
232 }
233 if (info.ptr != 0) {
234 if (buf && buf < end)
235 *buf++ = info.ptr;
236 count++;
237 if (buf && buf < end)
238 *buf++ = info.cookie;
239 count++;
240 }
241 } while (info.ptr != 0);
242
243 return count;
244}
245
Jon Spivack902e6fc2019-10-18 21:22:37 -0700246// Queries the driver for the current strong reference count of the node
247// that the handle points to. Can only be used by the servicemanager.
248//
249// Returns -1 in case of failure, otherwise the strong reference count.
Steven Morelande8393882020-12-18 02:27:20 +0000250ssize_t ProcessState::getStrongRefCountForNode(const sp<BpBinder>& binder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000251 if (binder->isRpcBinder()) return -1;
252
Jon Spivack902e6fc2019-10-18 21:22:37 -0700253 binder_node_info_for_ref info;
254 memset(&info, 0, sizeof(binder_node_info_for_ref));
255
Steven Moreland99157622021-09-13 16:27:34 -0700256 info.handle = binder->getPrivateAccessor().binderHandle();
Jon Spivack902e6fc2019-10-18 21:22:37 -0700257
258 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
259
260 if (result != OK) {
261 static bool logged = false;
262 if (!logged) {
263 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
264 logged = true;
265 }
266 return -1;
267 }
268
269 return info.strong_count;
270}
271
Steven Moreland7732a092019-01-02 17:54:16 -0800272void ProcessState::setCallRestriction(CallRestriction restriction) {
Steven Moreland28723ae2019-04-01 18:52:30 -0700273 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
274 "Call restrictions must be set before the threadpool is started.");
Steven Moreland7732a092019-01-02 17:54:16 -0800275
276 mCallRestriction = restriction;
277}
278
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800279ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
280{
281 const size_t N=mHandleToObject.size();
282 if (N <= (size_t)handle) {
283 handle_entry e;
Yi Kongfdd8da92018-06-07 17:52:27 -0700284 e.binder = nullptr;
285 e.refs = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
Yi Kongfdd8da92018-06-07 17:52:27 -0700287 if (err < NO_ERROR) return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288 }
289 return &mHandleToObject.editItemAt(handle);
290}
291
292sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
293{
294 sp<IBinder> result;
295
296 AutoMutex _l(mLock);
297
298 handle_entry* e = lookupHandleLocked(handle);
299
Yi Kongfdd8da92018-06-07 17:52:27 -0700300 if (e != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800301 // We need to create a new BpBinder if there isn't currently one, OR we
Steven Morelande171d622019-07-17 16:06:01 -0700302 // are unable to acquire a weak reference on this current one. The
303 // attemptIncWeak() is safe because we know the BpBinder destructor will always
304 // call expungeHandle(), which acquires the same lock we are holding now.
305 // We need to do this because there is a race condition between someone
306 // releasing a reference on this BpBinder, and a new reference on its handle
307 // arriving from the driver.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800308 IBinder* b = e->binder;
Yi Kongfdd8da92018-06-07 17:52:27 -0700309 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
Todd Poynora7b0f042013-06-18 17:25:37 -0700310 if (handle == 0) {
311 // Special case for context manager...
312 // The context manager is the only object for which we create
313 // a BpBinder proxy without already holding a reference.
314 // Perform a dummy transaction to ensure the context manager
315 // is registered before we create the first local reference
316 // to it (which will occur when creating the BpBinder).
317 // If a local reference is created for the BpBinder when the
318 // context manager is not present, the driver will fail to
319 // provide a reference to the context manager, but the
320 // driver API does not return status.
321 //
322 // Note that this is not race-free if the context manager
323 // dies while this code runs.
Todd Poynora7b0f042013-06-18 17:25:37 -0700324
Steven Moreland9514b202020-09-21 18:03:27 +0000325 IPCThreadState* ipc = IPCThreadState::self();
326
327 CallRestriction originalCallRestriction = ipc->getCallRestriction();
328 ipc->setCallRestriction(CallRestriction::NONE);
329
Todd Poynora7b0f042013-06-18 17:25:37 -0700330 Parcel data;
Steven Moreland9514b202020-09-21 18:03:27 +0000331 status_t status = ipc->transact(
Yi Kongfdd8da92018-06-07 17:52:27 -0700332 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
Steven Moreland9514b202020-09-21 18:03:27 +0000333
334 ipc->setCallRestriction(originalCallRestriction);
335
Todd Poynora7b0f042013-06-18 17:25:37 -0700336 if (status == DEAD_OBJECT)
Yi Kongfdd8da92018-06-07 17:52:27 -0700337 return nullptr;
Todd Poynora7b0f042013-06-18 17:25:37 -0700338 }
339
Steven Moreland99157622021-09-13 16:27:34 -0700340 sp<BpBinder> b = BpBinder::PrivateAccessor::create(handle);
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000341 e->binder = b.get();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342 if (b) e->refs = b->getWeakRefs();
343 result = b;
344 } else {
345 // This little bit of nastyness is to allow us to add a primary
346 // reference to the remote proxy when this team doesn't have one
347 // but another team is sending the handle to us.
348 result.force_set(b);
349 e->refs->decWeak(this);
350 }
351 }
352
353 return result;
354}
355
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800356void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
357{
358 AutoMutex _l(mLock);
Jooyung Han1b228f42020-01-30 13:41:12 +0900359
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800360 handle_entry* e = lookupHandleLocked(handle);
361
362 // This handle may have already been replaced with a new BpBinder
363 // (if someone failed the AttemptIncWeak() above); we don't want
364 // to overwrite it.
Yi Kongfdd8da92018-06-07 17:52:27 -0700365 if (e && e->binder == binder) e->binder = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800366}
367
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800368String8 ProcessState::makeBinderThreadName() {
369 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
Philip Cuadraa082fa82016-04-08 10:29:14 -0700370 pid_t pid = getpid();
Steven Moreland281abad2022-02-24 22:06:40 +0000371
372 std::string_view driverName = mDriverName.c_str();
373 android::base::ConsumePrefix(&driverName, "/dev/");
374
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800375 String8 name;
Steven Moreland281abad2022-02-24 22:06:40 +0000376 name.appendFormat("%.*s:%d_%X", static_cast<int>(driverName.length()), driverName.data(), pid,
377 s);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800378 return name;
379}
380
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381void ProcessState::spawnPooledThread(bool isMain)
382{
383 if (mThreadPoolStarted) {
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800384 String8 name = makeBinderThreadName();
385 ALOGV("Spawning new pooled thread, name=%s\n", name.string());
Steven Moreland1a3a8ef2021-04-02 02:52:46 +0000386 sp<Thread> t = sp<PoolThread>::make(isMain);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800387 t->run(name.string());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388 }
389}
390
Mathias Agopian1b80f792012-04-17 16:11:08 -0700391status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
Steven Moreland1fdb98b2020-03-06 21:42:12 +0000392 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
393 "Binder threadpool cannot be shrunk after starting");
Mathias Agopian1b80f792012-04-17 16:11:08 -0700394 status_t result = NO_ERROR;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700395 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
396 mMaxThreads = maxThreads;
397 } else {
Mathias Agopian1b80f792012-04-17 16:11:08 -0700398 result = -errno;
399 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
400 }
401 return result;
402}
403
Yifan Hong84bedeb2021-04-21 21:37:17 -0700404size_t ProcessState::getThreadPoolMaxThreadCount() const {
405 // may actually be one more than this, if join is called
406 if (mThreadPoolStarted) return mMaxThreads;
407 // must not be initialized or maybe has poll thread setup, we
408 // currently don't track this in libbinder
409 return 0;
410}
411
Carlos Llamas4f886702022-03-07 22:07:03 -0800412#define DRIVER_FEATURES_PATH "/dev/binderfs/features/"
413bool ProcessState::isDriverFeatureEnabled(const DriverFeature feature) {
414 static const char* const names[] = {
415 [static_cast<int>(DriverFeature::ONEWAY_SPAM_DETECTION)] =
416 DRIVER_FEATURES_PATH "oneway_spam_detection",
417 };
418 int fd = open(names[static_cast<int>(feature)], O_RDONLY | O_CLOEXEC);
419 char on;
420 if (fd == -1) {
421 ALOGE_IF(errno != ENOENT, "%s: cannot open %s: %s", __func__,
422 names[static_cast<int>(feature)], strerror(errno));
423 return false;
424 }
425 if (read(fd, &on, sizeof(on)) == -1) {
426 ALOGE("%s: error reading to %s: %s", __func__,
427 names[static_cast<int>(feature)], strerror(errno));
428 return false;
429 }
430 close(fd);
431 return on == '1';
432}
433
Hang Lub185ac02021-03-24 13:17:22 +0800434status_t ProcessState::enableOnewaySpamDetection(bool enable) {
435 uint32_t enableDetection = enable ? 1 : 0;
436 if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
Martijn Coenende0a39e2021-04-22 14:38:46 +0200437 ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
Hang Lub185ac02021-03-24 13:17:22 +0800438 return -errno;
439 }
440 return NO_ERROR;
441}
442
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800443void ProcessState::giveThreadPoolName() {
444 androidSetThreadName( makeBinderThreadName().string() );
445}
446
Iliyan Malchev32062242017-04-10 14:06:11 -0700447String8 ProcessState::getDriverName() {
448 return mDriverName;
449}
450
Steven Moreland13a43c92021-08-30 13:21:48 -0700451static base::Result<int> open_driver(const char* driver) {
Martijn Coenen55d871c2017-03-21 15:56:40 -0700452 int fd = open(driver, O_RDWR | O_CLOEXEC);
Steven Moreland13a43c92021-08-30 13:21:48 -0700453 if (fd < 0) {
454 return base::ErrnoError() << "Opening '" << driver << "' failed";
455 }
456 int vers = 0;
457 status_t result = ioctl(fd, BINDER_VERSION, &vers);
458 if (result == -1) {
459 close(fd);
460 return base::ErrnoError() << "Binder ioctl to obtain version failed";
461 }
462 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
463 close(fd);
464 return base::Error() << "Binder driver protocol(" << vers
465 << ") does not match user space protocol("
466 << BINDER_CURRENT_PROTOCOL_VERSION
467 << ")! ioctl() return value: " << result;
468 }
469 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
470 result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
471 if (result == -1) {
472 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
473 }
474 uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
475 result = ioctl(fd, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
476 if (result == -1) {
Carlos Llamas4f886702022-03-07 22:07:03 -0800477 ALOGE_IF(ProcessState::isDriverFeatureEnabled(
478 ProcessState::DriverFeature::ONEWAY_SPAM_DETECTION),
479 "Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800480 }
481 return fd;
482}
483
Steven Moreland13a43c92021-08-30 13:21:48 -0700484ProcessState::ProcessState(const char* driver)
485 : mDriverName(String8(driver)),
486 mDriverFD(-1),
487 mVMStart(MAP_FAILED),
488 mThreadCountLock(PTHREAD_MUTEX_INITIALIZER),
489 mThreadCountDecrement(PTHREAD_COND_INITIALIZER),
490 mExecutingThreadsCount(0),
491 mWaitingForThreads(0),
492 mMaxThreads(DEFAULT_MAX_BINDER_THREADS),
493 mStarvationStartTimeMs(0),
Steven Morelandee9df902021-10-14 14:00:08 -0700494 mForked(false),
Steven Moreland13a43c92021-08-30 13:21:48 -0700495 mThreadPoolStarted(false),
496 mThreadPoolSeq(1),
497 mCallRestriction(CallRestriction::NONE) {
498 base::Result<int> opened = open_driver(driver);
499
500 if (opened.ok()) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800501 // mmap the binder, providing a chunk of virtual address space to receive transactions.
Steven Moreland13a43c92021-08-30 13:21:48 -0700502 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE,
503 opened.value(), 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800504 if (mVMStart == MAP_FAILED) {
Steven Moreland13a43c92021-08-30 13:21:48 -0700505 close(opened.value());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800506 // *sigh*
Steven Moreland13a43c92021-08-30 13:21:48 -0700507 opened = base::Error()
508 << "Using " << driver << " failed: unable to mmap transaction memory.";
Iliyan Malchev32062242017-04-10 14:06:11 -0700509 mDriverName.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800510 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800511 }
Jeff Browne16986c2011-07-08 18:52:57 -0700512
Steven Moreland24bc0d12019-10-11 12:29:20 -0700513#ifdef __ANDROID__
Steven Moreland13a43c92021-08-30 13:21:48 -0700514 LOG_ALWAYS_FATAL_IF(!opened.ok(), "Binder driver '%s' could not be opened. Terminating: %s",
515 driver, opened.error().message().c_str());
Steven Moreland24bc0d12019-10-11 12:29:20 -0700516#endif
Steven Moreland13a43c92021-08-30 13:21:48 -0700517
518 if (opened.ok()) {
519 mDriverFD = opened.value();
520 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800521}
522
523ProcessState::~ProcessState()
524{
zhongjieff405782016-03-09 15:05:04 +0800525 if (mDriverFD >= 0) {
526 if (mVMStart != MAP_FAILED) {
Steven Moreland072cc7e2019-07-12 21:01:54 +0000527 munmap(mVMStart, BINDER_VM_SIZE);
zhongjieff405782016-03-09 15:05:04 +0800528 }
529 close(mDriverFD);
530 }
531 mDriverFD = -1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800532}
Jooyung Han1b228f42020-01-30 13:41:12 +0900533
Steven Moreland61ff8492019-09-26 16:05:45 -0700534} // namespace android