1 /*
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
19 #include <binder/ProcessState.h>
20
21 #include <binder/BpBinder.h>
22 #include <binder/IPCThreadState.h>
23 #include <binder/IServiceManager.h>
24 #include <binder/Stability.h>
25 #include <cutils/atomic.h>
26 #include <utils/Log.h>
27 #include <utils/String8.h>
28 #include <utils/threads.h>
29
30 #include "Static.h"
31 #include "binder_module.h"
32
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <mutex>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <unistd.h>
39 #include <sys/ioctl.h>
40 #include <sys/mman.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43
44 #define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
45 #define DEFAULT_MAX_BINDER_THREADS 15
46 #define DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION 1
47
48 #ifdef __ANDROID_VNDK__
49 const char* kDefaultDriver = "/dev/vndbinder";
50 #else
51 const char* kDefaultDriver = "/dev/binder";
52 #endif
53
54 // -------------------------------------------------------------------------
55
56 namespace android {
57
58 class PoolThread : public Thread
59 {
60 public:
PoolThread(bool isMain)61 explicit PoolThread(bool isMain)
62 : mIsMain(isMain)
63 {
64 }
65
66 protected:
threadLoop()67 virtual bool threadLoop()
68 {
69 IPCThreadState::self()->joinThreadPool(mIsMain);
70 return false;
71 }
72
73 const bool mIsMain;
74 };
75
self()76 sp<ProcessState> ProcessState::self()
77 {
78 return init(kDefaultDriver, false /*requireDefault*/);
79 }
80
initWithDriver(const char * driver)81 sp<ProcessState> ProcessState::initWithDriver(const char* driver)
82 {
83 return init(driver, true /*requireDefault*/);
84 }
85
selfOrNull()86 sp<ProcessState> ProcessState::selfOrNull()
87 {
88 return init(nullptr, false /*requireDefault*/);
89 }
90
init(const char * driver,bool requireDefault)91 sp<ProcessState> ProcessState::init(const char *driver, bool requireDefault)
92 {
93 [[clang::no_destroy]] static sp<ProcessState> gProcess;
94 [[clang::no_destroy]] static std::mutex gProcessMutex;
95
96 if (driver == nullptr) {
97 std::lock_guard<std::mutex> l(gProcessMutex);
98 return gProcess;
99 }
100
101 [[clang::no_destroy]] static std::once_flag gProcessOnce;
102 std::call_once(gProcessOnce, [&](){
103 if (access(driver, R_OK) == -1) {
104 ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
105 driver = "/dev/binder";
106 }
107
108 std::lock_guard<std::mutex> l(gProcessMutex);
109 gProcess = sp<ProcessState>::make(driver);
110 });
111
112 if (requireDefault) {
113 // Detect if we are trying to initialize with a different driver, and
114 // consider that an error. ProcessState will only be initialized once above.
115 LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,
116 "ProcessState was already initialized with %s,"
117 " can't initialize with %s.",
118 gProcess->getDriverName().c_str(), driver);
119 }
120
121 return gProcess;
122 }
123
getContextObject(const sp<IBinder> &)124 sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
125 {
126 sp<IBinder> context = getStrongProxyForHandle(0);
127
128 if (context) {
129 // The root object is special since we get it directly from the driver, it is never
130 // written by Parcell::writeStrongBinder.
131 internal::Stability::markCompilationUnit(context.get());
132 } else {
133 ALOGW("Not able to get context object on %s.", mDriverName.c_str());
134 }
135
136 return context;
137 }
138
startThreadPool()139 void ProcessState::startThreadPool()
140 {
141 AutoMutex _l(mLock);
142 if (!mThreadPoolStarted) {
143 mThreadPoolStarted = true;
144 spawnPooledThread(true);
145 }
146 }
147
becomeContextManager()148 bool ProcessState::becomeContextManager()
149 {
150 AutoMutex _l(mLock);
151
152 flat_binder_object obj {
153 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,
154 };
155
156 int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);
157
158 // fallback to original method
159 if (result != 0) {
160 android_errorWriteLog(0x534e4554, "121035042");
161
162 int unused = 0;
163 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);
164 }
165
166 if (result == -1) {
167 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
168 }
169
170 return result == 0;
171 }
172
173 // Get references to userspace objects held by the kernel binder driver
174 // Writes up to count elements into buf, and returns the total number
175 // of references the kernel has, which may be larger than count.
176 // buf may be NULL if count is 0. The pointers returned by this method
177 // should only be used for debugging and not dereferenced, they may
178 // already be invalid.
getKernelReferences(size_t buf_count,uintptr_t * buf)179 ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf)
180 {
181 binder_node_debug_info info = {};
182
183 uintptr_t* end = buf ? buf + buf_count : nullptr;
184 size_t count = 0;
185
186 do {
187 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info);
188 if (result < 0) {
189 return -1;
190 }
191 if (info.ptr != 0) {
192 if (buf && buf < end)
193 *buf++ = info.ptr;
194 count++;
195 if (buf && buf < end)
196 *buf++ = info.cookie;
197 count++;
198 }
199 } while (info.ptr != 0);
200
201 return count;
202 }
203
204 // Queries the driver for the current strong reference count of the node
205 // that the handle points to. Can only be used by the servicemanager.
206 //
207 // Returns -1 in case of failure, otherwise the strong reference count.
getStrongRefCountForNode(const sp<BpBinder> & binder)208 ssize_t ProcessState::getStrongRefCountForNode(const sp<BpBinder>& binder) {
209 if (binder->isRpcBinder()) return -1;
210
211 binder_node_info_for_ref info;
212 memset(&info, 0, sizeof(binder_node_info_for_ref));
213
214 info.handle = binder->getPrivateAccessorForId().binderHandle();
215
216 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_INFO_FOR_REF, &info);
217
218 if (result != OK) {
219 static bool logged = false;
220 if (!logged) {
221 ALOGW("Kernel does not support BINDER_GET_NODE_INFO_FOR_REF.");
222 logged = true;
223 }
224 return -1;
225 }
226
227 return info.strong_count;
228 }
229
setCallRestriction(CallRestriction restriction)230 void ProcessState::setCallRestriction(CallRestriction restriction) {
231 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull() != nullptr,
232 "Call restrictions must be set before the threadpool is started.");
233
234 mCallRestriction = restriction;
235 }
236
lookupHandleLocked(int32_t handle)237 ProcessState::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;
242 e.binder = nullptr;
243 e.refs = nullptr;
244 status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
245 if (err < NO_ERROR) return nullptr;
246 }
247 return &mHandleToObject.editItemAt(handle);
248 }
249
getStrongProxyForHandle(int32_t handle)250 sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
251 {
252 sp<IBinder> result;
253
254 AutoMutex _l(mLock);
255
256 handle_entry* e = lookupHandleLocked(handle);
257
258 if (e != nullptr) {
259 // 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. The
261 // attemptIncWeak() is safe because we know the BpBinder destructor will always
262 // call expungeHandle(), which acquires the same lock we are holding now.
263 // We need to do this because there is a race condition between someone
264 // releasing a reference on this BpBinder, and a new reference on its handle
265 // arriving from the driver.
266 IBinder* b = e->binder;
267 if (b == nullptr || !e->refs->attemptIncWeak(this)) {
268 if (handle == 0) {
269 // Special case for context manager...
270 // The context manager is the only object for which we create
271 // a BpBinder proxy without already holding a reference.
272 // Perform a dummy transaction to ensure the context manager
273 // is registered before we create the first local reference
274 // to it (which will occur when creating the BpBinder).
275 // If a local reference is created for the BpBinder when the
276 // context manager is not present, the driver will fail to
277 // provide a reference to the context manager, but the
278 // driver API does not return status.
279 //
280 // Note that this is not race-free if the context manager
281 // dies while this code runs.
282 //
283 // TODO: add a driver API to wait for context manager, or
284 // stop special casing handle 0 for context manager and add
285 // a driver API to get a handle to the context manager with
286 // proper reference counting.
287
288 IPCThreadState* ipc = IPCThreadState::self();
289
290 CallRestriction originalCallRestriction = ipc->getCallRestriction();
291 ipc->setCallRestriction(CallRestriction::NONE);
292
293 Parcel data;
294 status_t status = ipc->transact(
295 0, IBinder::PING_TRANSACTION, data, nullptr, 0);
296
297 ipc->setCallRestriction(originalCallRestriction);
298
299 if (status == DEAD_OBJECT)
300 return nullptr;
301 }
302
303 sp<BpBinder> b = BpBinder::create(handle);
304 e->binder = b.get();
305 if (b) e->refs = b->getWeakRefs();
306 result = b;
307 } else {
308 // This little bit of nastyness is to allow us to add a primary
309 // reference to the remote proxy when this team doesn't have one
310 // but another team is sending the handle to us.
311 result.force_set(b);
312 e->refs->decWeak(this);
313 }
314 }
315
316 return result;
317 }
318
expungeHandle(int32_t handle,IBinder * binder)319 void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
320 {
321 AutoMutex _l(mLock);
322
323 handle_entry* e = lookupHandleLocked(handle);
324
325 // This handle may have already been replaced with a new BpBinder
326 // (if someone failed the AttemptIncWeak() above); we don't want
327 // to overwrite it.
328 if (e && e->binder == binder) e->binder = nullptr;
329 }
330
makeBinderThreadName()331 String8 ProcessState::makeBinderThreadName() {
332 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
333 pid_t pid = getpid();
334 String8 name;
335 name.appendFormat("Binder:%d_%X", pid, s);
336 return name;
337 }
338
spawnPooledThread(bool isMain)339 void ProcessState::spawnPooledThread(bool isMain)
340 {
341 if (mThreadPoolStarted) {
342 String8 name = makeBinderThreadName();
343 ALOGV("Spawning new pooled thread, name=%s\n", name.string());
344 sp<Thread> t = sp<PoolThread>::make(isMain);
345 t->run(name.string());
346 }
347 }
348
setThreadPoolMaxThreadCount(size_t maxThreads)349 status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
350 LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
351 "Binder threadpool cannot be shrunk after starting");
352 status_t result = NO_ERROR;
353 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
354 mMaxThreads = maxThreads;
355 } else {
356 result = -errno;
357 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
358 }
359 return result;
360 }
361
enableOnewaySpamDetection(bool enable)362 status_t ProcessState::enableOnewaySpamDetection(bool enable) {
363 uint32_t enableDetection = enable ? 1 : 0;
364 if (ioctl(mDriverFD, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enableDetection) == -1) {
365 ALOGI("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
366 return -errno;
367 }
368 return NO_ERROR;
369 }
370
giveThreadPoolName()371 void ProcessState::giveThreadPoolName() {
372 androidSetThreadName( makeBinderThreadName().string() );
373 }
374
getDriverName()375 String8 ProcessState::getDriverName() {
376 return mDriverName;
377 }
378
open_driver(const char * driver)379 static int open_driver(const char *driver)
380 {
381 int fd = open(driver, O_RDWR | O_CLOEXEC);
382 if (fd >= 0) {
383 int vers = 0;
384 status_t result = ioctl(fd, BINDER_VERSION, &vers);
385 if (result == -1) {
386 ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));
387 close(fd);
388 fd = -1;
389 }
390 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
391 ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)! ioctl() return value: %d",
392 vers, BINDER_CURRENT_PROTOCOL_VERSION, result);
393 close(fd);
394 fd = -1;
395 }
396 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
397 result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
398 if (result == -1) {
399 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
400 }
401 uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;
402 result = ioctl(fd, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);
403 if (result == -1) {
404 ALOGD("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));
405 }
406 } else {
407 ALOGW("Opening '%s' failed: %s\n", driver, strerror(errno));
408 }
409 return fd;
410 }
411
ProcessState(const char * driver)412 ProcessState::ProcessState(const char *driver)
413 : mDriverName(String8(driver))
414 , mDriverFD(open_driver(driver))
415 , mVMStart(MAP_FAILED)
416 , mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
417 , mThreadCountDecrement(PTHREAD_COND_INITIALIZER)
418 , mExecutingThreadsCount(0)
419 , mWaitingForThreads(0)
420 , mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
421 , mStarvationStartTimeMs(0)
422 , mThreadPoolStarted(false)
423 , mThreadPoolSeq(1)
424 , mCallRestriction(CallRestriction::NONE)
425 {
426 if (mDriverFD >= 0) {
427 // mmap the binder, providing a chunk of virtual address space to receive transactions.
428 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
429 if (mVMStart == MAP_FAILED) {
430 // *sigh*
431 ALOGE("Using %s failed: unable to mmap transaction memory.\n", mDriverName.c_str());
432 close(mDriverFD);
433 mDriverFD = -1;
434 mDriverName.clear();
435 }
436 }
437
438 #ifdef __ANDROID__
439 LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver '%s' could not be opened. Terminating.", driver);
440 #endif
441 }
442
~ProcessState()443 ProcessState::~ProcessState()
444 {
445 if (mDriverFD >= 0) {
446 if (mVMStart != MAP_FAILED) {
447 munmap(mVMStart, BINDER_VM_SIZE);
448 }
449 close(mDriverFD);
450 }
451 mDriverFD = -1;
452 }
453
454 } // namespace android
455