IPCThreadState.cpp revision 73a7dde7c3e5c8437f396deeb200f250b3346be7
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 "IPCThreadState"
18
19#include <binder/IPCThreadState.h>
20
21#include <binder/Binder.h>
22#include <binder/BpBinder.h>
23#include <binder/TextOutput.h>
24
25#include <cutils/sched_policy.h>
26#include <utils/Log.h>
27#include <utils/SystemClock.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 <inttypes.h>
35#include <pthread.h>
36#include <sched.h>
37#include <signal.h>
38#include <stdio.h>
39#include <sys/ioctl.h>
40#include <sys/resource.h>
41#include <unistd.h>
42
43#if LOG_NDEBUG
44
45#define IF_LOG_TRANSACTIONS() if (false)
46#define IF_LOG_COMMANDS() if (false)
47#define LOG_REMOTEREFS(...)
48#define IF_LOG_REMOTEREFS() if (false)
49#define LOG_THREADPOOL(...)
50#define LOG_ONEWAY(...)
51
52#else
53
54#define IF_LOG_TRANSACTIONS() IF_ALOG(LOG_VERBOSE, "transact")
55#define IF_LOG_COMMANDS() IF_ALOG(LOG_VERBOSE, "ipc")
56#define LOG_REMOTEREFS(...) ALOG(LOG_DEBUG, "remoterefs", __VA_ARGS__)
57#define IF_LOG_REMOTEREFS() IF_ALOG(LOG_DEBUG, "remoterefs")
58#define LOG_THREADPOOL(...) ALOG(LOG_DEBUG, "threadpool", __VA_ARGS__)
59#define LOG_ONEWAY(...) ALOG(LOG_DEBUG, "ipc", __VA_ARGS__)
60
61#endif
62
63// ---------------------------------------------------------------------------
64
65namespace android {
66
67// Static const and functions will be optimized out if not used,
68// when LOG_NDEBUG and references in IF_LOG_COMMANDS() are optimized out.
69static const char *kReturnStrings[] = {
70    "BR_ERROR",
71    "BR_OK",
72    "BR_TRANSACTION",
73    "BR_REPLY",
74    "BR_ACQUIRE_RESULT",
75    "BR_DEAD_REPLY",
76    "BR_TRANSACTION_COMPLETE",
77    "BR_INCREFS",
78    "BR_ACQUIRE",
79    "BR_RELEASE",
80    "BR_DECREFS",
81    "BR_ATTEMPT_ACQUIRE",
82    "BR_NOOP",
83    "BR_SPAWN_LOOPER",
84    "BR_FINISHED",
85    "BR_DEAD_BINDER",
86    "BR_CLEAR_DEATH_NOTIFICATION_DONE",
87    "BR_FAILED_REPLY"
88};
89
90static const char *kCommandStrings[] = {
91    "BC_TRANSACTION",
92    "BC_REPLY",
93    "BC_ACQUIRE_RESULT",
94    "BC_FREE_BUFFER",
95    "BC_INCREFS",
96    "BC_ACQUIRE",
97    "BC_RELEASE",
98    "BC_DECREFS",
99    "BC_INCREFS_DONE",
100    "BC_ACQUIRE_DONE",
101    "BC_ATTEMPT_ACQUIRE",
102    "BC_REGISTER_LOOPER",
103    "BC_ENTER_LOOPER",
104    "BC_EXIT_LOOPER",
105    "BC_REQUEST_DEATH_NOTIFICATION",
106    "BC_CLEAR_DEATH_NOTIFICATION",
107    "BC_DEAD_BINDER_DONE"
108};
109
110static const char* getReturnString(uint32_t cmd)
111{
112    size_t idx = cmd & 0xff;
113    if (idx < sizeof(kReturnStrings) / sizeof(kReturnStrings[0]))
114        return kReturnStrings[idx];
115    else
116        return "unknown";
117}
118
119static const void* printBinderTransactionData(TextOutput& out, const void* data)
120{
121    const binder_transaction_data* btd =
122        (const binder_transaction_data*)data;
123    if (btd->target.handle < 1024) {
124        /* want to print descriptors in decimal; guess based on value */
125        out << "target.desc=" << btd->target.handle;
126    } else {
127        out << "target.ptr=" << btd->target.ptr;
128    }
129    out << " (cookie " << btd->cookie << ")" << endl
130        << "code=" << TypeCode(btd->code) << ", flags=" << (void*)(long)btd->flags << endl
131        << "data=" << btd->data.ptr.buffer << " (" << (void*)btd->data_size
132        << " bytes)" << endl
133        << "offsets=" << btd->data.ptr.offsets << " (" << (void*)btd->offsets_size
134        << " bytes)";
135    return btd+1;
136}
137
138static const void* printReturnCommand(TextOutput& out, const void* _cmd)
139{
140    static const size_t N = sizeof(kReturnStrings)/sizeof(kReturnStrings[0]);
141    const int32_t* cmd = (const int32_t*)_cmd;
142    uint32_t code = (uint32_t)*cmd++;
143    size_t cmdIndex = code & 0xff;
144    if (code == BR_ERROR) {
145        out << "BR_ERROR: " << (void*)(long)(*cmd++) << endl;
146        return cmd;
147    } else if (cmdIndex >= N) {
148        out << "Unknown reply: " << code << endl;
149        return cmd;
150    }
151    out << kReturnStrings[cmdIndex];
152
153    switch (code) {
154        case BR_TRANSACTION:
155        case BR_REPLY: {
156            out << ": " << indent;
157            cmd = (const int32_t *)printBinderTransactionData(out, cmd);
158            out << dedent;
159        } break;
160
161        case BR_ACQUIRE_RESULT: {
162            const int32_t res = *cmd++;
163            out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
164        } break;
165
166        case BR_INCREFS:
167        case BR_ACQUIRE:
168        case BR_RELEASE:
169        case BR_DECREFS: {
170            const int32_t b = *cmd++;
171            const int32_t c = *cmd++;
172            out << ": target=" << (void*)(long)b << " (cookie " << (void*)(long)c << ")";
173        } break;
174
175        case BR_ATTEMPT_ACQUIRE: {
176            const int32_t p = *cmd++;
177            const int32_t b = *cmd++;
178            const int32_t c = *cmd++;
179            out << ": target=" << (void*)(long)b << " (cookie " << (void*)(long)c
180                << "), pri=" << p;
181        } break;
182
183        case BR_DEAD_BINDER:
184        case BR_CLEAR_DEATH_NOTIFICATION_DONE: {
185            const int32_t c = *cmd++;
186            out << ": death cookie " << (void*)(long)c;
187        } break;
188
189        default:
190            // no details to show for: BR_OK, BR_DEAD_REPLY,
191            // BR_TRANSACTION_COMPLETE, BR_FINISHED
192            break;
193    }
194
195    out << endl;
196    return cmd;
197}
198
199static const void* printCommand(TextOutput& out, const void* _cmd)
200{
201    static const size_t N = sizeof(kCommandStrings)/sizeof(kCommandStrings[0]);
202    const int32_t* cmd = (const int32_t*)_cmd;
203    uint32_t code = (uint32_t)*cmd++;
204    size_t cmdIndex = code & 0xff;
205
206    if (cmdIndex >= N) {
207        out << "Unknown command: " << code << endl;
208        return cmd;
209    }
210    out << kCommandStrings[cmdIndex];
211
212    switch (code) {
213        case BC_TRANSACTION:
214        case BC_REPLY: {
215            out << ": " << indent;
216            cmd = (const int32_t *)printBinderTransactionData(out, cmd);
217            out << dedent;
218        } break;
219
220        case BC_ACQUIRE_RESULT: {
221            const int32_t res = *cmd++;
222            out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
223        } break;
224
225        case BC_FREE_BUFFER: {
226            const int32_t buf = *cmd++;
227            out << ": buffer=" << (void*)(long)buf;
228        } break;
229
230        case BC_INCREFS:
231        case BC_ACQUIRE:
232        case BC_RELEASE:
233        case BC_DECREFS: {
234            const int32_t d = *cmd++;
235            out << ": desc=" << d;
236        } break;
237
238        case BC_INCREFS_DONE:
239        case BC_ACQUIRE_DONE: {
240            const int32_t b = *cmd++;
241            const int32_t c = *cmd++;
242            out << ": target=" << (void*)(long)b << " (cookie " << (void*)(long)c << ")";
243        } break;
244
245        case BC_ATTEMPT_ACQUIRE: {
246            const int32_t p = *cmd++;
247            const int32_t d = *cmd++;
248            out << ": desc=" << d << ", pri=" << p;
249        } break;
250
251        case BC_REQUEST_DEATH_NOTIFICATION:
252        case BC_CLEAR_DEATH_NOTIFICATION: {
253            const int32_t h = *cmd++;
254            const int32_t c = *cmd++;
255            out << ": handle=" << h << " (death cookie " << (void*)(long)c << ")";
256        } break;
257
258        case BC_DEAD_BINDER_DONE: {
259            const int32_t c = *cmd++;
260            out << ": death cookie " << (void*)(long)c;
261        } break;
262
263        default:
264            // no details to show for: BC_REGISTER_LOOPER, BC_ENTER_LOOPER,
265            // BC_EXIT_LOOPER
266            break;
267    }
268
269    out << endl;
270    return cmd;
271}
272
273static pthread_mutex_t gTLSMutex = PTHREAD_MUTEX_INITIALIZER;
274static bool gHaveTLS = false;
275static pthread_key_t gTLS = 0;
276static bool gShutdown = false;
277static bool gDisableBackgroundScheduling = false;
278
279IPCThreadState* IPCThreadState::self()
280{
281    if (gHaveTLS) {
282restart:
283        const pthread_key_t k = gTLS;
284        IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
285        if (st) return st;
286        return new IPCThreadState;
287    }
288
289    if (gShutdown) {
290        ALOGW("Calling IPCThreadState::self() during shutdown is dangerous, expect a crash.\n");
291        return NULL;
292    }
293
294    pthread_mutex_lock(&gTLSMutex);
295    if (!gHaveTLS) {
296        int key_create_value = pthread_key_create(&gTLS, threadDestructor);
297        if (key_create_value != 0) {
298            pthread_mutex_unlock(&gTLSMutex);
299            ALOGW("IPCThreadState::self() unable to create TLS key, expect a crash: %s\n",
300                    strerror(key_create_value));
301            return NULL;
302        }
303        gHaveTLS = true;
304    }
305    pthread_mutex_unlock(&gTLSMutex);
306    goto restart;
307}
308
309IPCThreadState* IPCThreadState::selfOrNull()
310{
311    if (gHaveTLS) {
312        const pthread_key_t k = gTLS;
313        IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
314        return st;
315    }
316    return NULL;
317}
318
319void IPCThreadState::shutdown()
320{
321    gShutdown = true;
322
323    if (gHaveTLS) {
324        // XXX Need to wait for all thread pool threads to exit!
325        IPCThreadState* st = (IPCThreadState*)pthread_getspecific(gTLS);
326        if (st) {
327            delete st;
328            pthread_setspecific(gTLS, NULL);
329        }
330        pthread_key_delete(gTLS);
331        gHaveTLS = false;
332    }
333}
334
335void IPCThreadState::disableBackgroundScheduling(bool disable)
336{
337    gDisableBackgroundScheduling = disable;
338}
339
340sp<ProcessState> IPCThreadState::process()
341{
342    return mProcess;
343}
344
345status_t IPCThreadState::clearLastError()
346{
347    const status_t err = mLastError;
348    mLastError = NO_ERROR;
349    return err;
350}
351
352pid_t IPCThreadState::getCallingPid() const
353{
354    return mCallingPid;
355}
356
357uid_t IPCThreadState::getCallingUid() const
358{
359    return mCallingUid;
360}
361
362int64_t IPCThreadState::clearCallingIdentity()
363{
364    int64_t token = ((int64_t)mCallingUid<<32) | mCallingPid;
365    clearCaller();
366    return token;
367}
368
369void IPCThreadState::setStrictModePolicy(int32_t policy)
370{
371    mStrictModePolicy = policy;
372}
373
374int32_t IPCThreadState::getStrictModePolicy() const
375{
376    return mStrictModePolicy;
377}
378
379void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
380{
381    mLastTransactionBinderFlags = flags;
382}
383
384int32_t IPCThreadState::getLastTransactionBinderFlags() const
385{
386    return mLastTransactionBinderFlags;
387}
388
389void IPCThreadState::restoreCallingIdentity(int64_t token)
390{
391    mCallingUid = (int)(token>>32);
392    mCallingPid = (int)token;
393}
394
395void IPCThreadState::clearCaller()
396{
397    mCallingPid = getpid();
398    mCallingUid = getuid();
399}
400
401void IPCThreadState::flushCommands()
402{
403    if (mProcess->mDriverFD <= 0)
404        return;
405    talkWithDriver(false);
406}
407
408void IPCThreadState::blockUntilThreadAvailable()
409{
410    pthread_mutex_lock(&mProcess->mThreadCountLock);
411    while (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads) {
412        ALOGW("Waiting for thread to be free. mExecutingThreadsCount=%lu mMaxThreads=%lu\n",
413                static_cast<unsigned long>(mProcess->mExecutingThreadsCount),
414                static_cast<unsigned long>(mProcess->mMaxThreads));
415        pthread_cond_wait(&mProcess->mThreadCountDecrement, &mProcess->mThreadCountLock);
416    }
417    pthread_mutex_unlock(&mProcess->mThreadCountLock);
418}
419
420status_t IPCThreadState::getAndExecuteCommand()
421{
422    status_t result;
423    int32_t cmd;
424
425    result = talkWithDriver();
426    if (result >= NO_ERROR) {
427        size_t IN = mIn.dataAvail();
428        if (IN < sizeof(int32_t)) return result;
429        cmd = mIn.readInt32();
430        IF_LOG_COMMANDS() {
431            alog << "Processing top-level Command: "
432                 << getReturnString(cmd) << endl;
433        }
434
435        pthread_mutex_lock(&mProcess->mThreadCountLock);
436        mProcess->mExecutingThreadsCount++;
437        if (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads &&
438                mProcess->mStarvationStartTimeMs == 0) {
439            mProcess->mStarvationStartTimeMs = uptimeMillis();
440        }
441        pthread_mutex_unlock(&mProcess->mThreadCountLock);
442
443        result = executeCommand(cmd);
444
445        pthread_mutex_lock(&mProcess->mThreadCountLock);
446        mProcess->mExecutingThreadsCount--;
447        if (mProcess->mExecutingThreadsCount < mProcess->mMaxThreads &&
448                mProcess->mStarvationStartTimeMs != 0) {
449            int64_t starvationTimeMs = uptimeMillis() - mProcess->mStarvationStartTimeMs;
450            if (starvationTimeMs > 100) {
451                ALOGE("binder thread pool (%zu threads) starved for %" PRId64 " ms",
452                      mProcess->mMaxThreads, starvationTimeMs);
453            }
454            mProcess->mStarvationStartTimeMs = 0;
455        }
456        pthread_cond_broadcast(&mProcess->mThreadCountDecrement);
457        pthread_mutex_unlock(&mProcess->mThreadCountLock);
458
459        // After executing the command, ensure that the thread is returned to the
460        // foreground cgroup before rejoining the pool.  The driver takes care of
461        // restoring the priority, but doesn't do anything with cgroups so we
462        // need to take care of that here in userspace.  Note that we do make
463        // sure to go in the foreground after executing a transaction, but
464        // there are other callbacks into user code that could have changed
465        // our group so we want to make absolutely sure it is put back.
466        set_sched_policy(mMyThreadId, SP_FOREGROUND);
467    }
468
469    return result;
470}
471
472// When we've cleared the incoming command queue, process any pending derefs
473void IPCThreadState::processPendingDerefs()
474{
475    if (mIn.dataPosition() >= mIn.dataSize()) {
476        size_t numPending = mPendingWeakDerefs.size();
477        if (numPending > 0) {
478            for (size_t i = 0; i < numPending; i++) {
479                RefBase::weakref_type* refs = mPendingWeakDerefs[i];
480                refs->decWeak(mProcess.get());
481            }
482            mPendingWeakDerefs.clear();
483        }
484
485        numPending = mPendingStrongDerefs.size();
486        if (numPending > 0) {
487            for (size_t i = 0; i < numPending; i++) {
488                BBinder* obj = mPendingStrongDerefs[i];
489                obj->decStrong(mProcess.get());
490            }
491            mPendingStrongDerefs.clear();
492        }
493    }
494}
495
496void IPCThreadState::joinThreadPool(bool isMain)
497{
498    LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
499
500    mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
501
502    // This thread may have been spawned by a thread that was in the background
503    // scheduling group, so first we will make sure it is in the foreground
504    // one to avoid performing an initial transaction in the background.
505    set_sched_policy(mMyThreadId, SP_FOREGROUND);
506
507    status_t result;
508    do {
509        processPendingDerefs();
510        // now get the next command to be processed, waiting if necessary
511        result = getAndExecuteCommand();
512
513        if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
514            ALOGE("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
515                  mProcess->mDriverFD, result);
516            abort();
517        }
518
519        // Let this thread exit the thread pool if it is no longer
520        // needed and it is not the main process thread.
521        if(result == TIMED_OUT && !isMain) {
522            break;
523        }
524    } while (result != -ECONNREFUSED && result != -EBADF);
525
526    LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%d\n",
527        (void*)pthread_self(), getpid(), result);
528
529    mOut.writeInt32(BC_EXIT_LOOPER);
530    talkWithDriver(false);
531}
532
533int IPCThreadState::setupPolling(int* fd)
534{
535    if (mProcess->mDriverFD <= 0) {
536        return -EBADF;
537    }
538
539    mOut.writeInt32(BC_ENTER_LOOPER);
540    *fd = mProcess->mDriverFD;
541    return 0;
542}
543
544status_t IPCThreadState::handlePolledCommands()
545{
546    status_t result;
547
548    do {
549        result = getAndExecuteCommand();
550    } while (mIn.dataPosition() < mIn.dataSize());
551
552    processPendingDerefs();
553    flushCommands();
554    return result;
555}
556
557void IPCThreadState::stopProcess(bool /*immediate*/)
558{
559    //ALOGI("**** STOPPING PROCESS");
560    flushCommands();
561    int fd = mProcess->mDriverFD;
562    mProcess->mDriverFD = -1;
563    close(fd);
564    //kill(getpid(), SIGKILL);
565}
566
567status_t IPCThreadState::transact(int32_t handle,
568                                  uint32_t code, const Parcel& data,
569                                  Parcel* reply, uint32_t flags)
570{
571    status_t err = data.errorCheck();
572
573    flags |= TF_ACCEPT_FDS;
574
575    IF_LOG_TRANSACTIONS() {
576        TextOutput::Bundle _b(alog);
577        alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
578            << handle << " / code " << TypeCode(code) << ": "
579            << indent << data << dedent << endl;
580    }
581
582    if (err == NO_ERROR) {
583        LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
584            (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
585        err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);
586    }
587
588    if (err != NO_ERROR) {
589        if (reply) reply->setError(err);
590        return (mLastError = err);
591    }
592
593    if ((flags & TF_ONE_WAY) == 0) {
594        #if 0
595        if (code == 4) { // relayout
596            ALOGI(">>>>>> CALLING transaction 4");
597        } else {
598            ALOGI(">>>>>> CALLING transaction %d", code);
599        }
600        #endif
601        if (reply) {
602            err = waitForResponse(reply);
603        } else {
604            Parcel fakeReply;
605            err = waitForResponse(&fakeReply);
606        }
607        #if 0
608        if (code == 4) { // relayout
609            ALOGI("<<<<<< RETURNING transaction 4");
610        } else {
611            ALOGI("<<<<<< RETURNING transaction %d", code);
612        }
613        #endif
614
615        IF_LOG_TRANSACTIONS() {
616            TextOutput::Bundle _b(alog);
617            alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
618                << handle << ": ";
619            if (reply) alog << indent << *reply << dedent << endl;
620            else alog << "(none requested)" << endl;
621        }
622    } else {
623        err = waitForResponse(NULL, NULL);
624    }
625
626    return err;
627}
628
629void IPCThreadState::incStrongHandle(int32_t handle)
630{
631    LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
632    mOut.writeInt32(BC_ACQUIRE);
633    mOut.writeInt32(handle);
634}
635
636void IPCThreadState::decStrongHandle(int32_t handle)
637{
638    LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
639    mOut.writeInt32(BC_RELEASE);
640    mOut.writeInt32(handle);
641}
642
643void IPCThreadState::incWeakHandle(int32_t handle)
644{
645    LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
646    mOut.writeInt32(BC_INCREFS);
647    mOut.writeInt32(handle);
648}
649
650void IPCThreadState::decWeakHandle(int32_t handle)
651{
652    LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
653    mOut.writeInt32(BC_DECREFS);
654    mOut.writeInt32(handle);
655}
656
657status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
658{
659#if HAS_BC_ATTEMPT_ACQUIRE
660    LOG_REMOTEREFS("IPCThreadState::attemptIncStrongHandle(%d)\n", handle);
661    mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
662    mOut.writeInt32(0); // xxx was thread priority
663    mOut.writeInt32(handle);
664    status_t result = UNKNOWN_ERROR;
665
666    waitForResponse(NULL, &result);
667
668#if LOG_REFCOUNTS
669    printf("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
670        handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
671#endif
672
673    return result;
674#else
675    (void)handle;
676    ALOGE("%s(%d): Not supported\n", __func__, handle);
677    return INVALID_OPERATION;
678#endif
679}
680
681void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
682{
683#if LOG_REFCOUNTS
684    printf("IPCThreadState::expungeHandle(%ld)\n", handle);
685#endif
686    self()->mProcess->expungeHandle(handle, binder);
687}
688
689status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
690{
691    mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
692    mOut.writeInt32((int32_t)handle);
693    mOut.writePointer((uintptr_t)proxy);
694    return NO_ERROR;
695}
696
697status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
698{
699    mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
700    mOut.writeInt32((int32_t)handle);
701    mOut.writePointer((uintptr_t)proxy);
702    return NO_ERROR;
703}
704
705IPCThreadState::IPCThreadState()
706    : mProcess(ProcessState::self()),
707      mMyThreadId(gettid()),
708      mStrictModePolicy(0),
709      mLastTransactionBinderFlags(0)
710{
711    pthread_setspecific(gTLS, this);
712    clearCaller();
713    mIn.setDataCapacity(256);
714    mOut.setDataCapacity(256);
715}
716
717IPCThreadState::~IPCThreadState()
718{
719}
720
721status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
722{
723    status_t err;
724    status_t statusBuffer;
725    err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
726    if (err < NO_ERROR) return err;
727
728    return waitForResponse(NULL, NULL);
729}
730
731status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
732{
733    uint32_t cmd;
734    int32_t err;
735
736    while (1) {
737        if ((err=talkWithDriver()) < NO_ERROR) break;
738        err = mIn.errorCheck();
739        if (err < NO_ERROR) break;
740        if (mIn.dataAvail() == 0) continue;
741
742        cmd = (uint32_t)mIn.readInt32();
743
744        IF_LOG_COMMANDS() {
745            alog << "Processing waitForResponse Command: "
746                << getReturnString(cmd) << endl;
747        }
748
749        switch (cmd) {
750        case BR_TRANSACTION_COMPLETE:
751            if (!reply && !acquireResult) goto finish;
752            break;
753
754        case BR_DEAD_REPLY:
755            err = DEAD_OBJECT;
756            goto finish;
757
758        case BR_FAILED_REPLY:
759            err = FAILED_TRANSACTION;
760            goto finish;
761
762        case BR_ACQUIRE_RESULT:
763            {
764                ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
765                const int32_t result = mIn.readInt32();
766                if (!acquireResult) continue;
767                *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
768            }
769            goto finish;
770
771        case BR_REPLY:
772            {
773                binder_transaction_data tr;
774                err = mIn.read(&tr, sizeof(tr));
775                ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
776                if (err != NO_ERROR) goto finish;
777
778                if (reply) {
779                    if ((tr.flags & TF_STATUS_CODE) == 0) {
780                        reply->ipcSetDataReference(
781                            reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
782                            tr.data_size,
783                            reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
784                            tr.offsets_size/sizeof(binder_size_t),
785                            freeBuffer, this);
786                    } else {
787                        err = *reinterpret_cast<const status_t*>(tr.data.ptr.buffer);
788                        freeBuffer(NULL,
789                            reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
790                            tr.data_size,
791                            reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
792                            tr.offsets_size/sizeof(binder_size_t), this);
793                    }
794                } else {
795                    freeBuffer(NULL,
796                        reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
797                        tr.data_size,
798                        reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
799                        tr.offsets_size/sizeof(binder_size_t), this);
800                    continue;
801                }
802            }
803            goto finish;
804
805        default:
806            err = executeCommand(cmd);
807            if (err != NO_ERROR) goto finish;
808            break;
809        }
810    }
811
812finish:
813    if (err != NO_ERROR) {
814        if (acquireResult) *acquireResult = err;
815        if (reply) reply->setError(err);
816        mLastError = err;
817    }
818
819    return err;
820}
821
822status_t IPCThreadState::talkWithDriver(bool doReceive)
823{
824    if (mProcess->mDriverFD <= 0) {
825        return -EBADF;
826    }
827
828    binder_write_read bwr;
829
830    // Is the read buffer empty?
831    const bool needRead = mIn.dataPosition() >= mIn.dataSize();
832
833    // We don't want to write anything if we are still reading
834    // from data left in the input buffer and the caller
835    // has requested to read the next data.
836    const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
837
838    bwr.write_size = outAvail;
839    bwr.write_buffer = (uintptr_t)mOut.data();
840
841    // This is what we'll read.
842    if (doReceive && needRead) {
843        bwr.read_size = mIn.dataCapacity();
844        bwr.read_buffer = (uintptr_t)mIn.data();
845    } else {
846        bwr.read_size = 0;
847        bwr.read_buffer = 0;
848    }
849
850    IF_LOG_COMMANDS() {
851        TextOutput::Bundle _b(alog);
852        if (outAvail != 0) {
853            alog << "Sending commands to driver: " << indent;
854            const void* cmds = (const void*)bwr.write_buffer;
855            const void* end = ((const uint8_t*)cmds)+bwr.write_size;
856            alog << HexDump(cmds, bwr.write_size) << endl;
857            while (cmds < end) cmds = printCommand(alog, cmds);
858            alog << dedent;
859        }
860        alog << "Size of receive buffer: " << bwr.read_size
861            << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
862    }
863
864    // Return immediately if there is nothing to do.
865    if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
866
867    bwr.write_consumed = 0;
868    bwr.read_consumed = 0;
869    status_t err;
870    do {
871        IF_LOG_COMMANDS() {
872            alog << "About to read/write, write size = " << mOut.dataSize() << endl;
873        }
874#if defined(__ANDROID__)
875        if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
876            err = NO_ERROR;
877        else
878            err = -errno;
879#else
880        err = INVALID_OPERATION;
881#endif
882        if (mProcess->mDriverFD <= 0) {
883            err = -EBADF;
884        }
885        IF_LOG_COMMANDS() {
886            alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
887        }
888    } while (err == -EINTR);
889
890    IF_LOG_COMMANDS() {
891        alog << "Our err: " << (void*)(intptr_t)err << ", write consumed: "
892            << bwr.write_consumed << " (of " << mOut.dataSize()
893                        << "), read consumed: " << bwr.read_consumed << endl;
894    }
895
896    if (err >= NO_ERROR) {
897        if (bwr.write_consumed > 0) {
898            if (bwr.write_consumed < mOut.dataSize())
899                mOut.remove(0, bwr.write_consumed);
900            else
901                mOut.setDataSize(0);
902        }
903        if (bwr.read_consumed > 0) {
904            mIn.setDataSize(bwr.read_consumed);
905            mIn.setDataPosition(0);
906        }
907        IF_LOG_COMMANDS() {
908            TextOutput::Bundle _b(alog);
909            alog << "Remaining data size: " << mOut.dataSize() << endl;
910            alog << "Received commands from driver: " << indent;
911            const void* cmds = mIn.data();
912            const void* end = mIn.data() + mIn.dataSize();
913            alog << HexDump(cmds, mIn.dataSize()) << endl;
914            while (cmds < end) cmds = printReturnCommand(alog, cmds);
915            alog << dedent;
916        }
917        return NO_ERROR;
918    }
919
920    return err;
921}
922
923status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
924    int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
925{
926    binder_transaction_data tr;
927
928    tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
929    tr.target.handle = handle;
930    tr.code = code;
931    tr.flags = binderFlags;
932    tr.cookie = 0;
933    tr.sender_pid = 0;
934    tr.sender_euid = 0;
935
936    const status_t err = data.errorCheck();
937    if (err == NO_ERROR) {
938        tr.data_size = data.ipcDataSize();
939        tr.data.ptr.buffer = data.ipcData();
940        tr.offsets_size = data.ipcObjectsCount()*sizeof(binder_size_t);
941        tr.data.ptr.offsets = data.ipcObjects();
942    } else if (statusBuffer) {
943        tr.flags |= TF_STATUS_CODE;
944        *statusBuffer = err;
945        tr.data_size = sizeof(status_t);
946        tr.data.ptr.buffer = reinterpret_cast<uintptr_t>(statusBuffer);
947        tr.offsets_size = 0;
948        tr.data.ptr.offsets = 0;
949    } else {
950        return (mLastError = err);
951    }
952
953    mOut.writeInt32(cmd);
954    mOut.write(&tr, sizeof(tr));
955
956    return NO_ERROR;
957}
958
959sp<BBinder> the_context_object;
960
961void setTheContextObject(sp<BBinder> obj)
962{
963    the_context_object = obj;
964}
965
966status_t IPCThreadState::executeCommand(int32_t cmd)
967{
968    BBinder* obj;
969    RefBase::weakref_type* refs;
970    status_t result = NO_ERROR;
971
972    switch ((uint32_t)cmd) {
973    case BR_ERROR:
974        result = mIn.readInt32();
975        break;
976
977    case BR_OK:
978        break;
979
980    case BR_ACQUIRE:
981        refs = (RefBase::weakref_type*)mIn.readPointer();
982        obj = (BBinder*)mIn.readPointer();
983        ALOG_ASSERT(refs->refBase() == obj,
984                   "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
985                   refs, obj, refs->refBase());
986        obj->incStrong(mProcess.get());
987        IF_LOG_REMOTEREFS() {
988            LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
989            obj->printRefs();
990        }
991        mOut.writeInt32(BC_ACQUIRE_DONE);
992        mOut.writePointer((uintptr_t)refs);
993        mOut.writePointer((uintptr_t)obj);
994        break;
995
996    case BR_RELEASE:
997        refs = (RefBase::weakref_type*)mIn.readPointer();
998        obj = (BBinder*)mIn.readPointer();
999        ALOG_ASSERT(refs->refBase() == obj,
1000                   "BR_RELEASE: object %p does not match cookie %p (expected %p)",
1001                   refs, obj, refs->refBase());
1002        IF_LOG_REMOTEREFS() {
1003            LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
1004            obj->printRefs();
1005        }
1006        mPendingStrongDerefs.push(obj);
1007        break;
1008
1009    case BR_INCREFS:
1010        refs = (RefBase::weakref_type*)mIn.readPointer();
1011        obj = (BBinder*)mIn.readPointer();
1012        refs->incWeak(mProcess.get());
1013        mOut.writeInt32(BC_INCREFS_DONE);
1014        mOut.writePointer((uintptr_t)refs);
1015        mOut.writePointer((uintptr_t)obj);
1016        break;
1017
1018    case BR_DECREFS:
1019        refs = (RefBase::weakref_type*)mIn.readPointer();
1020        obj = (BBinder*)mIn.readPointer();
1021        // NOTE: This assertion is not valid, because the object may no
1022        // longer exist (thus the (BBinder*)cast above resulting in a different
1023        // memory address).
1024        //ALOG_ASSERT(refs->refBase() == obj,
1025        //           "BR_DECREFS: object %p does not match cookie %p (expected %p)",
1026        //           refs, obj, refs->refBase());
1027        mPendingWeakDerefs.push(refs);
1028        break;
1029
1030    case BR_ATTEMPT_ACQUIRE:
1031        refs = (RefBase::weakref_type*)mIn.readPointer();
1032        obj = (BBinder*)mIn.readPointer();
1033
1034        {
1035            const bool success = refs->attemptIncStrong(mProcess.get());
1036            ALOG_ASSERT(success && refs->refBase() == obj,
1037                       "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
1038                       refs, obj, refs->refBase());
1039
1040            mOut.writeInt32(BC_ACQUIRE_RESULT);
1041            mOut.writeInt32((int32_t)success);
1042        }
1043        break;
1044
1045    case BR_TRANSACTION:
1046        {
1047            binder_transaction_data tr;
1048            result = mIn.read(&tr, sizeof(tr));
1049            ALOG_ASSERT(result == NO_ERROR,
1050                "Not enough command data for brTRANSACTION");
1051            if (result != NO_ERROR) break;
1052
1053            Parcel buffer;
1054            buffer.ipcSetDataReference(
1055                reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1056                tr.data_size,
1057                reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1058                tr.offsets_size/sizeof(binder_size_t), freeBuffer, this);
1059
1060            const pid_t origPid = mCallingPid;
1061            const uid_t origUid = mCallingUid;
1062            const int32_t origStrictModePolicy = mStrictModePolicy;
1063            const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
1064
1065            mCallingPid = tr.sender_pid;
1066            mCallingUid = tr.sender_euid;
1067            mLastTransactionBinderFlags = tr.flags;
1068
1069            int curPrio = getpriority(PRIO_PROCESS, mMyThreadId);
1070            if (gDisableBackgroundScheduling) {
1071                if (curPrio > ANDROID_PRIORITY_NORMAL) {
1072                    // We have inherited a reduced priority from the caller, but do not
1073                    // want to run in that state in this process.  The driver set our
1074                    // priority already (though not our scheduling class), so bounce
1075                    // it back to the default before invoking the transaction.
1076                    setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL);
1077                }
1078            } else {
1079                if (curPrio >= ANDROID_PRIORITY_BACKGROUND) {
1080                    // We want to use the inherited priority from the caller.
1081                    // Ensure this thread is in the background scheduling class,
1082                    // since the driver won't modify scheduling classes for us.
1083                    // The scheduling group is reset to default by the caller
1084                    // once this method returns after the transaction is complete.
1085                    set_sched_policy(mMyThreadId, SP_BACKGROUND);
1086                }
1087            }
1088
1089            //ALOGI(">>>> TRANSACT from pid %d uid %d\n", mCallingPid, mCallingUid);
1090
1091            Parcel reply;
1092            status_t error;
1093            IF_LOG_TRANSACTIONS() {
1094                TextOutput::Bundle _b(alog);
1095                alog << "BR_TRANSACTION thr " << (void*)pthread_self()
1096                    << " / obj " << tr.target.ptr << " / code "
1097                    << TypeCode(tr.code) << ": " << indent << buffer
1098                    << dedent << endl
1099                    << "Data addr = "
1100                    << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1101                    << ", offsets addr="
1102                    << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
1103            }
1104            if (tr.target.ptr) {
1105                // We only have a weak reference on the target object, so we must first try to
1106                // safely acquire a strong reference before doing anything else with it.
1107                if (reinterpret_cast<RefBase::weakref_type*>(
1108                        tr.target.ptr)->attemptIncStrong(this)) {
1109                    error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,
1110                            &reply, tr.flags);
1111                    reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);
1112                } else {
1113                    error = UNKNOWN_TRANSACTION;
1114                }
1115
1116            } else {
1117                error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
1118            }
1119
1120            //ALOGI("<<<< TRANSACT from pid %d restore pid %d uid %d\n",
1121            //     mCallingPid, origPid, origUid);
1122
1123            if ((tr.flags & TF_ONE_WAY) == 0) {
1124                LOG_ONEWAY("Sending reply to %d!", mCallingPid);
1125                if (error < NO_ERROR) reply.setError(error);
1126                sendReply(reply, 0);
1127            } else {
1128                LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1129            }
1130
1131            mCallingPid = origPid;
1132            mCallingUid = origUid;
1133            mStrictModePolicy = origStrictModePolicy;
1134            mLastTransactionBinderFlags = origTransactionBinderFlags;
1135
1136            IF_LOG_TRANSACTIONS() {
1137                TextOutput::Bundle _b(alog);
1138                alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
1139                    << tr.target.ptr << ": " << indent << reply << dedent << endl;
1140            }
1141
1142        }
1143        break;
1144
1145    case BR_DEAD_BINDER:
1146        {
1147            BpBinder *proxy = (BpBinder*)mIn.readPointer();
1148            proxy->sendObituary();
1149            mOut.writeInt32(BC_DEAD_BINDER_DONE);
1150            mOut.writePointer((uintptr_t)proxy);
1151        } break;
1152
1153    case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1154        {
1155            BpBinder *proxy = (BpBinder*)mIn.readPointer();
1156            proxy->getWeakRefs()->decWeak(proxy);
1157        } break;
1158
1159    case BR_FINISHED:
1160        result = TIMED_OUT;
1161        break;
1162
1163    case BR_NOOP:
1164        break;
1165
1166    case BR_SPAWN_LOOPER:
1167        mProcess->spawnPooledThread(false);
1168        break;
1169
1170    default:
1171        printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
1172        result = UNKNOWN_ERROR;
1173        break;
1174    }
1175
1176    if (result != NO_ERROR) {
1177        mLastError = result;
1178    }
1179
1180    return result;
1181}
1182
1183void IPCThreadState::threadDestructor(void *st)
1184{
1185        IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1186        if (self) {
1187                self->flushCommands();
1188#if defined(__ANDROID__)
1189        if (self->mProcess->mDriverFD > 0) {
1190            ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1191        }
1192#endif
1193                delete self;
1194        }
1195}
1196
1197
1198void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data,
1199                                size_t /*dataSize*/,
1200                                const binder_size_t* /*objects*/,
1201                                size_t /*objectsSize*/, void* /*cookie*/)
1202{
1203    //ALOGI("Freeing parcel %p", &parcel);
1204    IF_LOG_COMMANDS() {
1205        alog << "Writing BC_FREE_BUFFER for " << data << endl;
1206    }
1207    ALOG_ASSERT(data != NULL, "Called with NULL data");
1208    if (parcel != NULL) parcel->closeFileDescriptors();
1209    IPCThreadState* state = self();
1210    state->mOut.writeInt32(BC_FREE_BUFFER);
1211    state->mOut.writePointer((uintptr_t)data);
1212}
1213
1214}; // namespace android
1215