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 <cutils/atomic.h> 25 #include <utils/Log.h> 26 #include <utils/String8.h> 27 #include <utils/String8.h> 28 #include <utils/threads.h> 29 30 #include <private/binder/binder_module.h> 31 #include <private/binder/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: 59 explicit PoolThread(bool isMain) 60 : mIsMain(isMain) 61 { 62 } 63 64 protected: 65 virtual bool threadLoop() 66 { 67 IPCThreadState::self()->joinThreadPool(mIsMain); 68 return false; 69 } 70 71 const bool mIsMain; 72 }; 73 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 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 105 sp<ProcessState> ProcessState::selfOrNull() 106 { 107 Mutex::Autolock _l(gProcessMutex); 108 return gProcess; 109 } 110 111 void ProcessState::setContextObject(const sp<IBinder>& object) 112 { 113 setContextObject(object, String16("default")); 114 } 115 116 sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/) 117 { 118 return getStrongProxyForHandle(0); 119 } 120 121 void ProcessState::setContextObject(const sp<IBinder>& object, const String16& name) 122 { 123 AutoMutex _l(mLock); 124 mContexts.add(name, object); 125 } 126 127 sp<IBinder> ProcessState::getContextObject(const String16& name, const sp<IBinder>& caller) 128 { 129 mLock.lock(); 130 sp<IBinder> object( 131 mContexts.indexOfKey(name) >= 0 ? mContexts.valueFor(name) : nullptr); 132 mLock.unlock(); 133 134 //printf("Getting context object %s for %p\n", String8(name).string(), caller.get()); 135 136 if (object != nullptr) return object; 137 138 // Don't attempt to retrieve contexts if we manage them 139 if (mManagesContexts) { 140 ALOGE("getContextObject(%s) failed, but we manage the contexts!\n", 141 String8(name).string()); 142 return nullptr; 143 } 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 159 if (object != nullptr) setContextObject(object, name); 160 return object; 161 } 162 163 void ProcessState::startThreadPool() 164 { 165 AutoMutex _l(mLock); 166 if (!mThreadPoolStarted) { 167 mThreadPoolStarted = true; 168 spawnPooledThread(true); 169 } 170 } 171 172 bool ProcessState::isContextManager(void) const 173 { 174 return mManagesContexts; 175 } 176 177 bool ProcessState::becomeContextManager(context_check_func checkFunc, void* userData) 178 { 179 if (!mManagesContexts) { 180 AutoMutex _l(mLock); 181 mBinderContextCheckFunc = checkFunc; 182 mBinderContextUserData = userData; 183 184 flat_binder_object obj { 185 .flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX, 186 }; 187 188 status_t result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj); 189 190 // fallback to original method 191 if (result != 0) { 192 android_errorWriteLog(0x534e4554, "121035042"); 193 194 int dummy = 0; 195 result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &dummy); 196 } 197 198 if (result == 0) { 199 mManagesContexts = true; 200 } else if (result == -1) { 201 mBinderContextCheckFunc = nullptr; 202 mBinderContextUserData = nullptr; 203 ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno)); 204 } 205 } 206 return mManagesContexts; 207 } 208 209 // Get references to userspace objects held by the kernel binder driver 210 // Writes up to count elements into buf, and returns the total number 211 // of references the kernel has, which may be larger than count. 212 // buf may be NULL if count is 0. The pointers returned by this method 213 // should only be used for debugging and not dereferenced, they may 214 // already be invalid. 215 ssize_t ProcessState::getKernelReferences(size_t buf_count, uintptr_t* buf) 216 { 217 binder_node_debug_info info = {}; 218 219 uintptr_t* end = buf ? buf + buf_count : nullptr; 220 size_t count = 0; 221 222 do { 223 status_t result = ioctl(mDriverFD, BINDER_GET_NODE_DEBUG_INFO, &info); 224 if (result < 0) { 225 return -1; 226 } 227 if (info.ptr != 0) { 228 if (buf && buf < end) 229 *buf++ = info.ptr; 230 count++; 231 if (buf && buf < end) 232 *buf++ = info.cookie; 233 count++; 234 } 235 } while (info.ptr != 0); 236 237 return count; 238 } 239 240 void ProcessState::setCallRestriction(CallRestriction restriction) { 241 LOG_ALWAYS_FATAL_IF(IPCThreadState::selfOrNull(), "Call restrictions must be set before the threadpool is started."); 242 243 mCallRestriction = restriction; 244 } 245 246 ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle) 247 { 248 const size_t N=mHandleToObject.size(); 249 if (N <= (size_t)handle) { 250 handle_entry e; 251 e.binder = nullptr; 252 e.refs = nullptr; 253 status_t err = mHandleToObject.insertAt(e, N, handle+1-N); 254 if (err < NO_ERROR) return nullptr; 255 } 256 return &mHandleToObject.editItemAt(handle); 257 } 258 259 sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle) 260 { 261 sp<IBinder> result; 262 263 AutoMutex _l(mLock); 264 265 handle_entry* e = lookupHandleLocked(handle); 266 267 if (e != nullptr) { 268 // We need to create a new BpBinder if there isn't currently one, OR we 269 // are unable to acquire a weak reference on this current one. See comment 270 // in getWeakProxyForHandle() for more info about this. 271 IBinder* b = e->binder; 272 if (b == nullptr || !e->refs->attemptIncWeak(this)) { 273 if (handle == 0) { 274 // Special case for context manager... 275 // The context manager is the only object for which we create 276 // a BpBinder proxy without already holding a reference. 277 // Perform a dummy transaction to ensure the context manager 278 // is registered before we create the first local reference 279 // to it (which will occur when creating the BpBinder). 280 // If a local reference is created for the BpBinder when the 281 // context manager is not present, the driver will fail to 282 // provide a reference to the context manager, but the 283 // driver API does not return status. 284 // 285 // Note that this is not race-free if the context manager 286 // dies while this code runs. 287 // 288 // TODO: add a driver API to wait for context manager, or 289 // stop special casing handle 0 for context manager and add 290 // a driver API to get a handle to the context manager with 291 // proper reference counting. 292 293 Parcel data; 294 status_t status = IPCThreadState::self()->transact( 295 0, IBinder::PING_TRANSACTION, data, nullptr, 0); 296 if (status == DEAD_OBJECT) 297 return nullptr; 298 } 299 300 b = BpBinder::create(handle); 301 e->binder = b; 302 if (b) e->refs = b->getWeakRefs(); 303 result = b; 304 } else { 305 // This little bit of nastyness is to allow us to add a primary 306 // reference to the remote proxy when this team doesn't have one 307 // but another team is sending the handle to us. 308 result.force_set(b); 309 e->refs->decWeak(this); 310 } 311 } 312 313 return result; 314 } 315 316 wp<IBinder> ProcessState::getWeakProxyForHandle(int32_t handle) 317 { 318 wp<IBinder> result; 319 320 AutoMutex _l(mLock); 321 322 handle_entry* e = lookupHandleLocked(handle); 323 324 if (e != nullptr) { 325 // We need to create a new BpBinder if there isn't currently one, OR we 326 // are unable to acquire a weak reference on this current one. The 327 // attemptIncWeak() is safe because we know the BpBinder destructor will always 328 // call expungeHandle(), which acquires the same lock we are holding now. 329 // We need to do this because there is a race condition between someone 330 // releasing a reference on this BpBinder, and a new reference on its handle 331 // arriving from the driver. 332 IBinder* b = e->binder; 333 if (b == nullptr || !e->refs->attemptIncWeak(this)) { 334 b = BpBinder::create(handle); 335 result = b; 336 e->binder = b; 337 if (b) e->refs = b->getWeakRefs(); 338 } else { 339 result = b; 340 e->refs->decWeak(this); 341 } 342 } 343 344 return result; 345 } 346 347 void ProcessState::expungeHandle(int32_t handle, IBinder* binder) 348 { 349 AutoMutex _l(mLock); 350 351 handle_entry* e = lookupHandleLocked(handle); 352 353 // This handle may have already been replaced with a new BpBinder 354 // (if someone failed the AttemptIncWeak() above); we don't want 355 // to overwrite it. 356 if (e && e->binder == binder) e->binder = nullptr; 357 } 358 359 String8 ProcessState::makeBinderThreadName() { 360 int32_t s = android_atomic_add(1, &mThreadPoolSeq); 361 pid_t pid = getpid(); 362 String8 name; 363 name.appendFormat("Binder:%d_%X", pid, s); 364 return name; 365 } 366 367 void ProcessState::spawnPooledThread(bool isMain) 368 { 369 if (mThreadPoolStarted) { 370 String8 name = makeBinderThreadName(); 371 ALOGV("Spawning new pooled thread, name=%s\n", name.string()); 372 sp<Thread> t = new PoolThread(isMain); 373 t->run(name.string()); 374 } 375 } 376 377 status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) { 378 status_t result = NO_ERROR; 379 if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) { 380 mMaxThreads = maxThreads; 381 } else { 382 result = -errno; 383 ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result)); 384 } 385 return result; 386 } 387 388 void ProcessState::giveThreadPoolName() { 389 androidSetThreadName( makeBinderThreadName().string() ); 390 } 391 392 String8 ProcessState::getDriverName() { 393 return mDriverName; 394 } 395 396 static int open_driver(const char *driver) 397 { 398 int fd = open(driver, O_RDWR | O_CLOEXEC); 399 if (fd >= 0) { 400 int vers = 0; 401 status_t result = ioctl(fd, BINDER_VERSION, &vers); 402 if (result == -1) { 403 ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno)); 404 close(fd); 405 fd = -1; 406 } 407 if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) { 408 ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)! ioctl() return value: %d", 409 vers, BINDER_CURRENT_PROTOCOL_VERSION, result); 410 close(fd); 411 fd = -1; 412 } 413 size_t maxThreads = DEFAULT_MAX_BINDER_THREADS; 414 result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads); 415 if (result == -1) { 416 ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno)); 417 } 418 } else { 419 ALOGW("Opening '%s' failed: %s\n", driver, strerror(errno)); 420 } 421 return fd; 422 } 423 424 ProcessState::ProcessState(const char *driver) 425 : mDriverName(String8(driver)) 426 , mDriverFD(open_driver(driver)) 427 , mVMStart(MAP_FAILED) 428 , mThreadCountLock(PTHREAD_MUTEX_INITIALIZER) 429 , mThreadCountDecrement(PTHREAD_COND_INITIALIZER) 430 , mExecutingThreadsCount(0) 431 , mMaxThreads(DEFAULT_MAX_BINDER_THREADS) 432 , mStarvationStartTimeMs(0) 433 , mManagesContexts(false) 434 , mBinderContextCheckFunc(nullptr) 435 , mBinderContextUserData(nullptr) 436 , mThreadPoolStarted(false) 437 , mThreadPoolSeq(1) 438 , mCallRestriction(CallRestriction::NONE) 439 { 440 if (mDriverFD >= 0) { 441 // mmap the binder, providing a chunk of virtual address space to receive transactions. 442 mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0); 443 if (mVMStart == MAP_FAILED) { 444 // *sigh* 445 ALOGE("Using %s failed: unable to mmap transaction memory.\n", mDriverName.c_str()); 446 close(mDriverFD); 447 mDriverFD = -1; 448 mDriverName.clear(); 449 } 450 } 451 452 LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver could not be opened. Terminating."); 453 } 454 455 ProcessState::~ProcessState() 456 { 457 if (mDriverFD >= 0) { 458 if (mVMStart != MAP_FAILED) { 459 munmap(mVMStart, BINDER_VM_SIZE); 460 } 461 close(mDriverFD); 462 } 463 mDriverFD = -1; 464 } 465 466 }; // namespace android 467