Home | History | Annotate | Download | only in binder
      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 <cutils/process_name.h>
     20 
     21 #include <binder/ProcessState.h>
     22 
     23 #include <utils/Atomic.h>
     24 #include <binder/BpBinder.h>
     25 #include <binder/IPCThreadState.h>
     26 #include <utils/Log.h>
     27 #include <utils/String8.h>
     28 #include <binder/IServiceManager.h>
     29 #include <utils/String8.h>
     30 #include <utils/threads.h>
     31 
     32 #include <private/binder/binder_module.h>
     33 #include <private/binder/Static.h>
     34 
     35 #include <errno.h>
     36 #include <fcntl.h>
     37 #include <stdio.h>
     38 #include <stdlib.h>
     39 #include <unistd.h>
     40 #include <sys/ioctl.h>
     41 #include <sys/mman.h>
     42 #include <sys/stat.h>
     43 
     44 #define BINDER_VM_SIZE ((1*1024*1024) - (4096 *2))
     45 
     46 
     47 // ---------------------------------------------------------------------------
     48 
     49 namespace android {
     50 
     51 // Global variables
     52 int                 mArgC;
     53 const char* const*  mArgV;
     54 int                 mArgLen;
     55 
     56 class PoolThread : public Thread
     57 {
     58 public:
     59     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 != NULL) {
     78         return gProcess;
     79     }
     80     gProcess = new ProcessState;
     81     return gProcess;
     82 }
     83 
     84 void ProcessState::setContextObject(const sp<IBinder>& object)
     85 {
     86     setContextObject(object, String16("default"));
     87 }
     88 
     89 sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& caller)
     90 {
     91     return getStrongProxyForHandle(0);
     92 }
     93 
     94 void ProcessState::setContextObject(const sp<IBinder>& object, const String16& name)
     95 {
     96     AutoMutex _l(mLock);
     97     mContexts.add(name, object);
     98 }
     99 
    100 sp<IBinder> ProcessState::getContextObject(const String16& name, const sp<IBinder>& caller)
    101 {
    102     mLock.lock();
    103     sp<IBinder> object(
    104         mContexts.indexOfKey(name) >= 0 ? mContexts.valueFor(name) : NULL);
    105     mLock.unlock();
    106 
    107     //printf("Getting context object %s for %p\n", String8(name).string(), caller.get());
    108 
    109     if (object != NULL) return object;
    110 
    111     // Don't attempt to retrieve contexts if we manage them
    112     if (mManagesContexts) {
    113         ALOGE("getContextObject(%s) failed, but we manage the contexts!\n",
    114             String8(name).string());
    115         return NULL;
    116     }
    117 
    118     IPCThreadState* ipc = IPCThreadState::self();
    119     {
    120         Parcel data, reply;
    121         // no interface token on this magic transaction
    122         data.writeString16(name);
    123         data.writeStrongBinder(caller);
    124         status_t result = ipc->transact(0 /*magic*/, 0, data, &reply, 0);
    125         if (result == NO_ERROR) {
    126             object = reply.readStrongBinder();
    127         }
    128     }
    129 
    130     ipc->flushCommands();
    131 
    132     if (object != NULL) setContextObject(object, name);
    133     return object;
    134 }
    135 
    136 void ProcessState::startThreadPool()
    137 {
    138     AutoMutex _l(mLock);
    139     if (!mThreadPoolStarted) {
    140         mThreadPoolStarted = true;
    141         spawnPooledThread(true);
    142     }
    143 }
    144 
    145 bool ProcessState::isContextManager(void) const
    146 {
    147     return mManagesContexts;
    148 }
    149 
    150 bool ProcessState::becomeContextManager(context_check_func checkFunc, void* userData)
    151 {
    152     if (!mManagesContexts) {
    153         AutoMutex _l(mLock);
    154         mBinderContextCheckFunc = checkFunc;
    155         mBinderContextUserData = userData;
    156 
    157         int dummy = 0;
    158         status_t result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &dummy);
    159         if (result == 0) {
    160             mManagesContexts = true;
    161         } else if (result == -1) {
    162             mBinderContextCheckFunc = NULL;
    163             mBinderContextUserData = NULL;
    164             ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));
    165         }
    166     }
    167     return mManagesContexts;
    168 }
    169 
    170 ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
    171 {
    172     const size_t N=mHandleToObject.size();
    173     if (N <= (size_t)handle) {
    174         handle_entry e;
    175         e.binder = NULL;
    176         e.refs = NULL;
    177         status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
    178         if (err < NO_ERROR) return NULL;
    179     }
    180     return &mHandleToObject.editItemAt(handle);
    181 }
    182 
    183 sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
    184 {
    185     sp<IBinder> result;
    186 
    187     AutoMutex _l(mLock);
    188 
    189     handle_entry* e = lookupHandleLocked(handle);
    190 
    191     if (e != NULL) {
    192         // We need to create a new BpBinder if there isn't currently one, OR we
    193         // are unable to acquire a weak reference on this current one.  See comment
    194         // in getWeakProxyForHandle() for more info about this.
    195         IBinder* b = e->binder;
    196         if (b == NULL || !e->refs->attemptIncWeak(this)) {
    197             if (handle == 0) {
    198                 // Special case for context manager...
    199                 // The context manager is the only object for which we create
    200                 // a BpBinder proxy without already holding a reference.
    201                 // Perform a dummy transaction to ensure the context manager
    202                 // is registered before we create the first local reference
    203                 // to it (which will occur when creating the BpBinder).
    204                 // If a local reference is created for the BpBinder when the
    205                 // context manager is not present, the driver will fail to
    206                 // provide a reference to the context manager, but the
    207                 // driver API does not return status.
    208                 //
    209                 // Note that this is not race-free if the context manager
    210                 // dies while this code runs.
    211                 //
    212                 // TODO: add a driver API to wait for context manager, or
    213                 // stop special casing handle 0 for context manager and add
    214                 // a driver API to get a handle to the context manager with
    215                 // proper reference counting.
    216 
    217                 Parcel data;
    218                 status_t status = IPCThreadState::self()->transact(
    219                         0, IBinder::PING_TRANSACTION, data, NULL, 0);
    220                 if (status == DEAD_OBJECT)
    221                    return NULL;
    222             }
    223 
    224             b = new BpBinder(handle);
    225             e->binder = b;
    226             if (b) e->refs = b->getWeakRefs();
    227             result = b;
    228         } else {
    229             // This little bit of nastyness is to allow us to add a primary
    230             // reference to the remote proxy when this team doesn't have one
    231             // but another team is sending the handle to us.
    232             result.force_set(b);
    233             e->refs->decWeak(this);
    234         }
    235     }
    236 
    237     return result;
    238 }
    239 
    240 wp<IBinder> ProcessState::getWeakProxyForHandle(int32_t handle)
    241 {
    242     wp<IBinder> result;
    243 
    244     AutoMutex _l(mLock);
    245 
    246     handle_entry* e = lookupHandleLocked(handle);
    247 
    248     if (e != NULL) {
    249         // We need to create a new BpBinder if there isn't currently one, OR we
    250         // are unable to acquire a weak reference on this current one.  The
    251         // attemptIncWeak() is safe because we know the BpBinder destructor will always
    252         // call expungeHandle(), which acquires the same lock we are holding now.
    253         // We need to do this because there is a race condition between someone
    254         // releasing a reference on this BpBinder, and a new reference on its handle
    255         // arriving from the driver.
    256         IBinder* b = e->binder;
    257         if (b == NULL || !e->refs->attemptIncWeak(this)) {
    258             b = new BpBinder(handle);
    259             result = b;
    260             e->binder = b;
    261             if (b) e->refs = b->getWeakRefs();
    262         } else {
    263             result = b;
    264             e->refs->decWeak(this);
    265         }
    266     }
    267 
    268     return result;
    269 }
    270 
    271 void ProcessState::expungeHandle(int32_t handle, IBinder* binder)
    272 {
    273     AutoMutex _l(mLock);
    274 
    275     handle_entry* e = lookupHandleLocked(handle);
    276 
    277     // This handle may have already been replaced with a new BpBinder
    278     // (if someone failed the AttemptIncWeak() above); we don't want
    279     // to overwrite it.
    280     if (e && e->binder == binder) e->binder = NULL;
    281 }
    282 
    283 void ProcessState::setArgs(int argc, const char* const argv[])
    284 {
    285     mArgC = argc;
    286     mArgV = (const char **)argv;
    287 
    288     mArgLen = 0;
    289     for (int i=0; i<argc; i++) {
    290         mArgLen += strlen(argv[i]) + 1;
    291     }
    292     mArgLen--;
    293 }
    294 
    295 int ProcessState::getArgC() const
    296 {
    297     return mArgC;
    298 }
    299 
    300 const char* const* ProcessState::getArgV() const
    301 {
    302     return mArgV;
    303 }
    304 
    305 void ProcessState::setArgV0(const char* txt)
    306 {
    307     if (mArgV != NULL) {
    308         strncpy((char*)mArgV[0], txt, mArgLen);
    309         set_process_name(txt);
    310     }
    311 }
    312 
    313 String8 ProcessState::makeBinderThreadName() {
    314     int32_t s = android_atomic_add(1, &mThreadPoolSeq);
    315     String8 name;
    316     name.appendFormat("Binder_%X", s);
    317     return name;
    318 }
    319 
    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 
    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         result = -errno;
    334         ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
    335     }
    336     return result;
    337 }
    338 
    339 void ProcessState::giveThreadPoolName() {
    340     androidSetThreadName( makeBinderThreadName().string() );
    341 }
    342 
    343 static int open_driver()
    344 {
    345     int fd = open("/dev/binder", O_RDWR);
    346     if (fd >= 0) {
    347         fcntl(fd, F_SETFD, FD_CLOEXEC);
    348         int vers;
    349         status_t result = ioctl(fd, BINDER_VERSION, &vers);
    350         if (result == -1) {
    351             ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));
    352             close(fd);
    353             fd = -1;
    354         }
    355         if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
    356             ALOGE("Binder driver protocol does not match user space protocol!");
    357             close(fd);
    358             fd = -1;
    359         }
    360         size_t maxThreads = 15;
    361         result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
    362         if (result == -1) {
    363             ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
    364         }
    365     } else {
    366         ALOGW("Opening '/dev/binder' failed: %s\n", strerror(errno));
    367     }
    368     return fd;
    369 }
    370 
    371 ProcessState::ProcessState()
    372     : mDriverFD(open_driver())
    373     , mVMStart(MAP_FAILED)
    374     , mManagesContexts(false)
    375     , mBinderContextCheckFunc(NULL)
    376     , mBinderContextUserData(NULL)
    377     , mThreadPoolStarted(false)
    378     , mThreadPoolSeq(1)
    379 {
    380     if (mDriverFD >= 0) {
    381         // XXX Ideally, there should be a specific define for whether we
    382         // have mmap (or whether we could possibly have the kernel module
    383         // availabla).
    384 #if !defined(HAVE_WIN32_IPC)
    385         // mmap the binder, providing a chunk of virtual address space to receive transactions.
    386         mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
    387         if (mVMStart == MAP_FAILED) {
    388             // *sigh*
    389             ALOGE("Using /dev/binder failed: unable to mmap transaction memory.\n");
    390             close(mDriverFD);
    391             mDriverFD = -1;
    392         }
    393 #else
    394         mDriverFD = -1;
    395 #endif
    396     }
    397 
    398     LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver could not be opened.  Terminating.");
    399 }
    400 
    401 ProcessState::~ProcessState()
    402 {
    403 }
    404 
    405 }; // namespace android
    406