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