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