blob: c8cdb77b9ce980cb49e181bd6985b767a40cfe42 [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
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070021#include <binder/BpBinder.h>
22#include <binder/IPCThreadState.h>
Steven Moreland2716e112018-02-23 14:57:20 -080023#include <binder/IServiceManager.h>
24#include <cutils/atomic.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080025#include <utils/Log.h>
26#include <utils/String8.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080027#include <utils/String8.h>
28#include <utils/threads.h>
29
Mathias Agopian208059f2009-05-18 15:08:03 -070030#include <private/binder/binder_module.h>
31#include <private/binder/Static.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
33#include <errno.h>
34#include <fcntl.h>
35#include <stdio.h>
36#include <stdlib.h>
37#include <unistd.h>
38#include <sys/ioctl.h>
39#include <sys/mman.h>
40#include <sys/stat.h>
Philip Cuadraa082fa82016-04-08 10:29:14 -070041#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080042
Ganesh Mahendran6ac7fb52017-03-03 09:41:14 +080043#define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
Wale Ogunwale376b8222015-04-13 16:16:10 -070044#define DEFAULT_MAX_BINDER_THREADS 15
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080045
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070046#ifdef __ANDROID_VNDK__
47const char* kDefaultDriver = "/dev/vndbinder";
48#else
49const char* kDefaultDriver = "/dev/binder";
50#endif
51
Philip Cuadraa082fa82016-04-08 10:29:14 -070052// -------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053
54namespace android {
Wale Ogunwale376b8222015-04-13 16:16:10 -070055
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056class PoolThread : public Thread
57{
58public:
Chih-Hung Hsiehe2347b72016-04-25 15:41:05 -070059 explicit PoolThread(bool isMain)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060 : mIsMain(isMain)
61 {
62 }
63
64protected:
65 virtual bool threadLoop()
66 {
67 IPCThreadState::self()->joinThreadPool(mIsMain);
68 return false;
69 }
70
71 const bool mIsMain;
72};
73
74sp<ProcessState> ProcessState::self()
75{
Mathias Agopiane8db8712012-04-16 19:30:56 -070076 Mutex::Autolock _l(gProcessMutex);
Yi Kongfdd8da92018-06-07 17:52:27 -070077 if (gProcess != nullptr) {
Mathias Agopiane8db8712012-04-16 19:30:56 -070078 return gProcess;
79 }
Steven Moreland2ae2f5e2018-07-06 13:02:53 -070080 gProcess = new ProcessState(kDefaultDriver);
Martijn Coenen55d871c2017-03-21 15:56:40 -070081 return gProcess;
82}
83
84sp<ProcessState> ProcessState::initWithDriver(const char* driver)
85{
86 Mutex::Autolock _l(gProcessMutex);
Yi Kongfdd8da92018-06-07 17:52:27 -070087 if (gProcess != nullptr) {
Iliyan Malcheved1ffe02017-04-14 00:34:57 -070088 // Allow for initWithDriver to be called repeatedly with the same
89 // driver.
90 if (!strcmp(gProcess->getDriverName().c_str(), driver)) {
91 return gProcess;
92 }
Martijn Coenen55d871c2017-03-21 15:56:40 -070093 LOG_ALWAYS_FATAL("ProcessState was already initialized.");
94 }
Steven Moreland376a5592017-12-19 15:42:16 -080095
96 if (access(driver, R_OK) == -1) {
97 ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
98 driver = "/dev/binder";
99 }
100
Martijn Coenen55d871c2017-03-21 15:56:40 -0700101 gProcess = new ProcessState(driver);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102 return gProcess;
103}
104
Colin Cross9d45ccc2017-06-20 17:48:33 -0700105sp<ProcessState> ProcessState::selfOrNull()
106{
107 Mutex::Autolock _l(gProcessMutex);
108 return gProcess;
109}
110
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800111void ProcessState::setContextObject(const sp<IBinder>& object)
112{
113 setContextObject(object, String16("default"));
114}
115
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800116sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800117{
Jeff Browne16986c2011-07-08 18:52:57 -0700118 return getStrongProxyForHandle(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800119}
120
121void ProcessState::setContextObject(const sp<IBinder>& object, const String16& name)
122{
123 AutoMutex _l(mLock);
124 mContexts.add(name, object);
125}
126
127sp<IBinder> ProcessState::getContextObject(const String16& name, const sp<IBinder>& caller)
128{
129 mLock.lock();
130 sp<IBinder> object(
Yi Kongfdd8da92018-06-07 17:52:27 -0700131 mContexts.indexOfKey(name) >= 0 ? mContexts.valueFor(name) : nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800132 mLock.unlock();
133
134 //printf("Getting context object %s for %p\n", String8(name).string(), caller.get());
135
Yi Kongfdd8da92018-06-07 17:52:27 -0700136 if (object != nullptr) return object;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137
138 // Don't attempt to retrieve contexts if we manage them
139 if (mManagesContexts) {
Steve Blocke6f43dd2012-01-06 19:20:56 +0000140 ALOGE("getContextObject(%s) failed, but we manage the contexts!\n",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141 String8(name).string());
Yi Kongfdd8da92018-06-07 17:52:27 -0700142 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 }
144
145 IPCThreadState* ipc = IPCThreadState::self();
146 {
147 Parcel data, reply;
148 // no interface token on this magic transaction
149 data.writeString16(name);
150 data.writeStrongBinder(caller);
151 status_t result = ipc->transact(0 /*magic*/, 0, data, &reply, 0);
152 if (result == NO_ERROR) {
153 object = reply.readStrongBinder();
154 }
155 }
156
157 ipc->flushCommands();
158
Yi Kongfdd8da92018-06-07 17:52:27 -0700159 if (object != nullptr) setContextObject(object, name);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160 return object;
161}
162
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163void ProcessState::startThreadPool()
164{
165 AutoMutex _l(mLock);
166 if (!mThreadPoolStarted) {
167 mThreadPoolStarted = true;
168 spawnPooledThread(true);
169 }
170}
171
172bool ProcessState::isContextManager(void) const
173{
174 return mManagesContexts;
175}
176
177bool ProcessState::becomeContextManager(context_check_func checkFunc, void* userData)
178{
179 if (!mManagesContexts) {
180 AutoMutex _l(mLock);
181 mBinderContextCheckFunc = checkFunc;
182 mBinderContextUserData = userData;
Jeff Browne16986c2011-07-08 18:52:57 -0700183
184 int dummy = 0;
Jeff Browne16986c2011-07-08 18:52:57 -0700185 status_t result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &dummy);
Jeff Browne16986c2011-07-08 18:52:57 -0700186 if (result == 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800187 mManagesContexts = true;
Jeff Browne16986c2011-07-08 18:52:57 -0700188 } else if (result == -1) {
Yi Kongfdd8da92018-06-07 17:52:27 -0700189 mBinderContextCheckFunc = nullptr;
190 mBinderContextUserData = nullptr;
Steve Blocke6f43dd2012-01-06 19:20:56 +0000191 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192 }
193 }
194 return mManagesContexts;
195}
196
Colin Cross9d45ccc2017-06-20 17:48:33 -0700197// Get references to userspace objects held by the kernel binder driver
198// Writes up to count elements into buf, and returns the total number
199// of references the kernel has, which may be larger than count.
200// buf may be NULL if count is 0. The pointers returned by this method
201// should only be used for debugging and not dereferenced, they may
202// already be invalid.
203ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
204{
205 // TODO: remove these when they are defined by bionic's binder.h
206 struct binder_node_debug_info {
207 binder_uintptr_t ptr;
208 binder_uintptr_t cookie;
209 __u32 has_strong_ref;
210 __u32 has_weak_ref;
211 };
212#define BINDER_GET_NODE_DEBUG_INFO _IOWR('b', 11, struct binder_node_debug_info)
213
214 binder_node_debug_info info = {};
215
Yi Kongfdd8da92018-06-07 17:52:27 -0700216 uintptr_t* end = buf ? buf + buf_count : nullptr;
Colin Cross9d45ccc2017-06-20 17:48:33 -0700217 size_t count = 0;
218
219 do {
220 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
221 if (result < 0) {
222 return -1;
223 }
224 if (info.ptr != 0) {
225 if (buf && buf < end)
226 *buf++ = info.ptr;
227 count++;
228 if (buf && buf < end)
229 *buf++ = info.cookie;
230 count++;
231 }
232 } while (info.ptr != 0);
233
234 return count;
235}
236
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
238{
239 const size_t N=mHandleToObject.size();
240 if (N <= (size_t)handle) {
241 handle_entry e;
Yi Kongfdd8da92018-06-07 17:52:27 -0700242 e.binder = nullptr;
243 e.refs = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
Yi Kongfdd8da92018-06-07 17:52:27 -0700245 if (err < NO_ERROR) return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800246 }
247 return &mHandleToObject.editItemAt(handle);
248}
249
250sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
251{
252 sp<IBinder> result;
253
254 AutoMutex _l(mLock);
255
256 handle_entry* e = lookupHandleLocked(handle);
257
Yi Kongfdd8da92018-06-07 17:52:27 -0700258 if (e != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259 // We need to create a new BpBinder if there isn't currently one, OR we
260 // are unable to acquire a weak reference on this current one. See comment
261 // in getWeakProxyForHandle() for more info about this.
262 IBinder* b = e->binder;
Yi Kongfdd8da92018-06-07 17:52:27 -0700263 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
Todd Poynora7b0f042013-06-18 17:25:37 -0700264 if (handle == 0) {
265 // Special case for context manager...
266 // The context manager is the only object for which we create
267 // a BpBinder proxy without already holding a reference.
268 // Perform a dummy transaction to ensure the context manager
269 // is registered before we create the first local reference
270 // to it (which will occur when creating the BpBinder).
271 // If a local reference is created for the BpBinder when the
272 // context manager is not present, the driver will fail to
273 // provide a reference to the context manager, but the
274 // driver API does not return status.
275 //
276 // Note that this is not race-free if the context manager
277 // dies while this code runs.
278 //
279 // TODO: add a driver API to wait for context manager, or
280 // stop special casing handle 0 for context manager and add
281 // a driver API to get a handle to the context manager with
282 // proper reference counting.
283
284 Parcel data;
285 status_t status = IPCThreadState::self()->transact(
Yi Kongfdd8da92018-06-07 17:52:27 -0700286 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
Todd Poynora7b0f042013-06-18 17:25:37 -0700287 if (status == DEAD_OBJECT)
Yi Kongfdd8da92018-06-07 17:52:27 -0700288 return nullptr;
Todd Poynora7b0f042013-06-18 17:25:37 -0700289 }
290
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291 b = new BpBinder(handle);
292 e->binder = b;
293 if (b) e->refs = b->getWeakRefs();
294 result = b;
295 } else {
296 // This little bit of nastyness is to allow us to add a primary
297 // reference to the remote proxy when this team doesn't have one
298 // but another team is sending the handle to us.
299 result.force_set(b);
300 e->refs->decWeak(this);
301 }
302 }
303
304 return result;
305}
306
307wp<IBinder> ProcessState::getWeakProxyForHandle(int32_t handle)
308{
309 wp<IBinder> result;
310
311 AutoMutex _l(mLock);
312
313 handle_entry* e = lookupHandleLocked(handle);
314
Yi Kongfdd8da92018-06-07 17:52:27 -0700315 if (e != nullptr) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800316 // We need to create a new BpBinder if there isn't currently one, OR we
317 // are unable to acquire a weak reference on this current one. The
318 // attemptIncWeak() is safe because we know the BpBinder destructor will always
319 // call expungeHandle(), which acquires the same lock we are holding now.
320 // We need to do this because there is a race condition between someone
321 // releasing a reference on this BpBinder, and a new reference on its handle
322 // arriving from the driver.
323 IBinder* b = e->binder;
Yi Kongfdd8da92018-06-07 17:52:27 -0700324 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800325 b = new BpBinder(handle);
326 result = b;
327 e->binder = b;
328 if (b) e->refs = b->getWeakRefs();
329 } else {
330 result = b;
331 e->refs->decWeak(this);
332 }
333 }
334
335 return result;
336}
337
338void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
339{
340 AutoMutex _l(mLock);
341
342 handle_entry* e = lookupHandleLocked(handle);
343
344 // This handle may have already been replaced with a new BpBinder
345 // (if someone failed the AttemptIncWeak() above); we don't want
346 // to overwrite it.
Yi Kongfdd8da92018-06-07 17:52:27 -0700347 if (e && e->binder == binder) e->binder = nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800348}
349
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800350String8 ProcessState::makeBinderThreadName() {
351 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
Philip Cuadraa082fa82016-04-08 10:29:14 -0700352 pid_t pid = getpid();
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800353 String8 name;
Philip Cuadraa082fa82016-04-08 10:29:14 -0700354 name.appendFormat("Binder:%d_%X", pid, s);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800355 return name;
356}
357
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800358void ProcessState::spawnPooledThread(bool isMain)
359{
360 if (mThreadPoolStarted) {
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800361 String8 name = makeBinderThreadName();
362 ALOGV("Spawning new pooled thread, name=%s\n", name.string());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800363 sp<Thread> t = new PoolThread(isMain);
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800364 t->run(name.string());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800365 }
366}
367
Mathias Agopian1b80f792012-04-17 16:11:08 -0700368status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
369 status_t result = NO_ERROR;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700370 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
371 mMaxThreads = maxThreads;
372 } else {
Mathias Agopian1b80f792012-04-17 16:11:08 -0700373 result = -errno;
374 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
375 }
376 return result;
377}
378
Mathias Agopiane3e43b32013-03-07 15:34:28 -0800379void ProcessState::giveThreadPoolName() {
380 androidSetThreadName( makeBinderThreadName().string() );
381}
382
Iliyan Malchev32062242017-04-10 14:06:11 -0700383String8 ProcessState::getDriverName() {
384 return mDriverName;
385}
386
Martijn Coenen55d871c2017-03-21 15:56:40 -0700387static int open_driver(const char *driver)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388{
Martijn Coenen55d871c2017-03-21 15:56:40 -0700389 int fd = open(driver, O_RDWR | O_CLOEXEC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800390 if (fd >= 0) {
Jin Wei78181df2012-10-18 17:00:48 +0800391 int vers = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800392 status_t result = ioctl(fd, BINDER_VERSION, &vers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800393 if (result == -1) {
Steve Blocke6f43dd2012-01-06 19:20:56 +0000394 ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800395 close(fd);
396 fd = -1;
397 }
398 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
Greg Hartman67ac00f2017-01-03 16:54:59 -0800399 ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)! ioctl() return value: %d",
400 vers, BINDER_CURRENT_PROTOCOL_VERSION, result);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401 close(fd);
402 fd = -1;
403 }
Wale Ogunwale376b8222015-04-13 16:16:10 -0700404 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405 result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
406 if (result == -1) {
Steve Blocke6f43dd2012-01-06 19:20:56 +0000407 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409 } else {
Martijn Coenen55d871c2017-03-21 15:56:40 -0700410 ALOGW("Opening '%s' failed: %s\n", driver, strerror(errno));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411 }
412 return fd;
413}
414
Martijn Coenen55d871c2017-03-21 15:56:40 -0700415ProcessState::ProcessState(const char *driver)
Iliyan Malchev32062242017-04-10 14:06:11 -0700416 : mDriverName(String8(driver))
417 , mDriverFD(open_driver(driver))
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800418 , mVMStart(MAP_FAILED)
Wale Ogunwale376b8222015-04-13 16:16:10 -0700419 , mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
420 , mThreadCountDecrement(PTHREAD_COND_INITIALIZER)
421 , mExecutingThreadsCount(0)
422 , mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
Colin Cross96e83222016-04-15 14:29:55 -0700423 , mStarvationStartTimeMs(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424 , mManagesContexts(false)
Yi Kongfdd8da92018-06-07 17:52:27 -0700425 , mBinderContextCheckFunc(nullptr)
426 , mBinderContextUserData(nullptr)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427 , mThreadPoolStarted(false)
428 , mThreadPoolSeq(1)
429{
430 if (mDriverFD >= 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431 // mmap the binder, providing a chunk of virtual address space to receive transactions.
Yi Kongfdd8da92018-06-07 17:52:27 -0700432 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800433 if (mVMStart == MAP_FAILED) {
434 // *sigh*
Steven Moreland376a5592017-12-19 15:42:16 -0800435 ALOGE("Using %s failed: unable to mmap transaction memory.\n", mDriverName.c_str());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800436 close(mDriverFD);
437 mDriverFD = -1;
Iliyan Malchev32062242017-04-10 14:06:11 -0700438 mDriverName.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800439 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800440 }
Jeff Browne16986c2011-07-08 18:52:57 -0700441
442 LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver could not be opened. Terminating.");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800443}
444
445ProcessState::~ProcessState()
446{
zhongjieff405782016-03-09 15:05:04 +0800447 if (mDriverFD >= 0) {
448 if (mVMStart != MAP_FAILED) {
449 munmap(mVMStart, BINDER_VM_SIZE);
450 }
451 close(mDriverFD);
452 }
453 mDriverFD = -1;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800454}
455
456}; // namespace android