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