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