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