IPCThreadState.cpp revision 002e1e58dfe19dd3e49a59c6827cbf51573941a2
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()
366{
367    return mCallingPid;
368}
369
370int IPCThreadState::getCallingUid()
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
421void IPCThreadState::joinThreadPool(bool isMain)
422{
423    LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
424
425    mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
426
427    // This thread may have been spawned by a thread that was in the background
428    // scheduling group, so first we will make sure it is in the foreground
429    // one to avoid performing an initial transaction in the background.
430    set_sched_policy(mMyThreadId, SP_FOREGROUND);
431
432    status_t result;
433    do {
434        int32_t cmd;
435
436        // When we've cleared the incoming command queue, process any pending derefs
437        if (mIn.dataPosition() >= mIn.dataSize()) {
438            size_t numPending = mPendingWeakDerefs.size();
439            if (numPending > 0) {
440                for (size_t i = 0; i < numPending; i++) {
441                    RefBase::weakref_type* refs = mPendingWeakDerefs[i];
442                    refs->decWeak(mProcess.get());
443                }
444                mPendingWeakDerefs.clear();
445            }
446
447            numPending = mPendingStrongDerefs.size();
448            if (numPending > 0) {
449                for (size_t i = 0; i < numPending; i++) {
450                    BBinder* obj = mPendingStrongDerefs[i];
451                    obj->decStrong(mProcess.get());
452                }
453                mPendingStrongDerefs.clear();
454            }
455        }
456
457        // now get the next command to be processed, waiting if necessary
458        result = talkWithDriver();
459        if (result >= NO_ERROR) {
460            size_t IN = mIn.dataAvail();
461            if (IN < sizeof(int32_t)) continue;
462            cmd = mIn.readInt32();
463            IF_LOG_COMMANDS() {
464                alog << "Processing top-level Command: "
465                    << getReturnString(cmd) << endl;
466            }
467
468
469            result = executeCommand(cmd);
470        }
471
472        // After executing the command, ensure that the thread is returned to the
473        // foreground cgroup before rejoining the pool.  The driver takes care of
474        // restoring the priority, but doesn't do anything with cgroups so we
475        // need to take care of that here in userspace.  Note that we do make
476        // sure to go in the foreground after executing a transaction, but
477        // there are other callbacks into user code that could have changed
478        // our group so we want to make absolutely sure it is put back.
479        set_sched_policy(mMyThreadId, SP_FOREGROUND);
480
481        // Let this thread exit the thread pool if it is no longer
482        // needed and it is not the main process thread.
483        if(result == TIMED_OUT && !isMain) {
484            break;
485        }
486    } while (result != -ECONNREFUSED && result != -EBADF);
487
488    LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%p\n",
489        (void*)pthread_self(), getpid(), (void*)result);
490
491    mOut.writeInt32(BC_EXIT_LOOPER);
492    talkWithDriver(false);
493}
494
495void IPCThreadState::stopProcess(bool immediate)
496{
497    //ALOGI("**** STOPPING PROCESS");
498    flushCommands();
499    int fd = mProcess->mDriverFD;
500    mProcess->mDriverFD = -1;
501    close(fd);
502    //kill(getpid(), SIGKILL);
503}
504
505status_t IPCThreadState::transact(int32_t handle,
506                                  uint32_t code, const Parcel& data,
507                                  Parcel* reply, uint32_t flags)
508{
509    status_t err = data.errorCheck();
510
511    flags |= TF_ACCEPT_FDS;
512
513    IF_LOG_TRANSACTIONS() {
514        TextOutput::Bundle _b(alog);
515        alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
516            << handle << " / code " << TypeCode(code) << ": "
517            << indent << data << dedent << endl;
518    }
519
520    if (err == NO_ERROR) {
521        LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
522            (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
523        err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);
524    }
525
526    if (err != NO_ERROR) {
527        if (reply) reply->setError(err);
528        return (mLastError = err);
529    }
530
531    if ((flags & TF_ONE_WAY) == 0) {
532        #if 0
533        if (code == 4) { // relayout
534            ALOGI(">>>>>> CALLING transaction 4");
535        } else {
536            ALOGI(">>>>>> CALLING transaction %d", code);
537        }
538        #endif
539        if (reply) {
540            err = waitForResponse(reply);
541        } else {
542            Parcel fakeReply;
543            err = waitForResponse(&fakeReply);
544        }
545        #if 0
546        if (code == 4) { // relayout
547            ALOGI("<<<<<< RETURNING transaction 4");
548        } else {
549            ALOGI("<<<<<< RETURNING transaction %d", code);
550        }
551        #endif
552
553        IF_LOG_TRANSACTIONS() {
554            TextOutput::Bundle _b(alog);
555            alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
556                << handle << ": ";
557            if (reply) alog << indent << *reply << dedent << endl;
558            else alog << "(none requested)" << endl;
559        }
560    } else {
561        err = waitForResponse(NULL, NULL);
562    }
563
564    return err;
565}
566
567void IPCThreadState::incStrongHandle(int32_t handle)
568{
569    LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
570    mOut.writeInt32(BC_ACQUIRE);
571    mOut.writeInt32(handle);
572}
573
574void IPCThreadState::decStrongHandle(int32_t handle)
575{
576    LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
577    mOut.writeInt32(BC_RELEASE);
578    mOut.writeInt32(handle);
579}
580
581void IPCThreadState::incWeakHandle(int32_t handle)
582{
583    LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
584    mOut.writeInt32(BC_INCREFS);
585    mOut.writeInt32(handle);
586}
587
588void IPCThreadState::decWeakHandle(int32_t handle)
589{
590    LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
591    mOut.writeInt32(BC_DECREFS);
592    mOut.writeInt32(handle);
593}
594
595status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
596{
597    LOG_REMOTEREFS("IPCThreadState::attemptIncStrongHandle(%d)\n", handle);
598    mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
599    mOut.writeInt32(0); // xxx was thread priority
600    mOut.writeInt32(handle);
601    status_t result = UNKNOWN_ERROR;
602
603    waitForResponse(NULL, &result);
604
605#if LOG_REFCOUNTS
606    printf("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
607        handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
608#endif
609
610    return result;
611}
612
613void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
614{
615#if LOG_REFCOUNTS
616    printf("IPCThreadState::expungeHandle(%ld)\n", handle);
617#endif
618    self()->mProcess->expungeHandle(handle, binder);
619}
620
621status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
622{
623    mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
624    mOut.writeInt32((int32_t)handle);
625    mOut.writeInt32((int32_t)proxy);
626    return NO_ERROR;
627}
628
629status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
630{
631    mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
632    mOut.writeInt32((int32_t)handle);
633    mOut.writeInt32((int32_t)proxy);
634    return NO_ERROR;
635}
636
637IPCThreadState::IPCThreadState()
638    : mProcess(ProcessState::self()),
639      mMyThreadId(androidGetTid()),
640      mStrictModePolicy(0),
641      mLastTransactionBinderFlags(0)
642{
643    pthread_setspecific(gTLS, this);
644    clearCaller();
645    mIn.setDataCapacity(256);
646    mOut.setDataCapacity(256);
647}
648
649IPCThreadState::~IPCThreadState()
650{
651}
652
653status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
654{
655    status_t err;
656    status_t statusBuffer;
657    err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
658    if (err < NO_ERROR) return err;
659
660    return waitForResponse(NULL, NULL);
661}
662
663status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
664{
665    int32_t cmd;
666    int32_t err;
667
668    while (1) {
669        if ((err=talkWithDriver()) < NO_ERROR) break;
670        err = mIn.errorCheck();
671        if (err < NO_ERROR) break;
672        if (mIn.dataAvail() == 0) continue;
673
674        cmd = mIn.readInt32();
675
676        IF_LOG_COMMANDS() {
677            alog << "Processing waitForResponse Command: "
678                << getReturnString(cmd) << endl;
679        }
680
681        switch (cmd) {
682        case BR_TRANSACTION_COMPLETE:
683            if (!reply && !acquireResult) goto finish;
684            break;
685
686        case BR_DEAD_REPLY:
687            err = DEAD_OBJECT;
688            goto finish;
689
690        case BR_FAILED_REPLY:
691            err = FAILED_TRANSACTION;
692            goto finish;
693
694        case BR_ACQUIRE_RESULT:
695            {
696                ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
697                const int32_t result = mIn.readInt32();
698                if (!acquireResult) continue;
699                *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
700            }
701            goto finish;
702
703        case BR_REPLY:
704            {
705                binder_transaction_data tr;
706                err = mIn.read(&tr, sizeof(tr));
707                ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
708                if (err != NO_ERROR) goto finish;
709
710                if (reply) {
711                    if ((tr.flags & TF_STATUS_CODE) == 0) {
712                        reply->ipcSetDataReference(
713                            reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
714                            tr.data_size,
715                            reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
716                            tr.offsets_size/sizeof(size_t),
717                            freeBuffer, this);
718                    } else {
719                        err = *static_cast<const status_t*>(tr.data.ptr.buffer);
720                        freeBuffer(NULL,
721                            reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
722                            tr.data_size,
723                            reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
724                            tr.offsets_size/sizeof(size_t), this);
725                    }
726                } else {
727                    freeBuffer(NULL,
728                        reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
729                        tr.data_size,
730                        reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
731                        tr.offsets_size/sizeof(size_t), this);
732                    continue;
733                }
734            }
735            goto finish;
736
737        default:
738            err = executeCommand(cmd);
739            if (err != NO_ERROR) goto finish;
740            break;
741        }
742    }
743
744finish:
745    if (err != NO_ERROR) {
746        if (acquireResult) *acquireResult = err;
747        if (reply) reply->setError(err);
748        mLastError = err;
749    }
750
751    return err;
752}
753
754status_t IPCThreadState::talkWithDriver(bool doReceive)
755{
756    if (mProcess->mDriverFD <= 0) {
757        return -EBADF;
758    }
759
760    binder_write_read bwr;
761
762    // Is the read buffer empty?
763    const bool needRead = mIn.dataPosition() >= mIn.dataSize();
764
765    // We don't want to write anything if we are still reading
766    // from data left in the input buffer and the caller
767    // has requested to read the next data.
768    const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
769
770    bwr.write_size = outAvail;
771    bwr.write_buffer = (long unsigned int)mOut.data();
772
773    // This is what we'll read.
774    if (doReceive && needRead) {
775        bwr.read_size = mIn.dataCapacity();
776        bwr.read_buffer = (long unsigned int)mIn.data();
777    } else {
778        bwr.read_size = 0;
779        bwr.read_buffer = 0;
780    }
781
782    IF_LOG_COMMANDS() {
783        TextOutput::Bundle _b(alog);
784        if (outAvail != 0) {
785            alog << "Sending commands to driver: " << indent;
786            const void* cmds = (const void*)bwr.write_buffer;
787            const void* end = ((const uint8_t*)cmds)+bwr.write_size;
788            alog << HexDump(cmds, bwr.write_size) << endl;
789            while (cmds < end) cmds = printCommand(alog, cmds);
790            alog << dedent;
791        }
792        alog << "Size of receive buffer: " << bwr.read_size
793            << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
794    }
795
796    // Return immediately if there is nothing to do.
797    if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
798
799    bwr.write_consumed = 0;
800    bwr.read_consumed = 0;
801    status_t err;
802    do {
803        IF_LOG_COMMANDS() {
804            alog << "About to read/write, write size = " << mOut.dataSize() << endl;
805        }
806#if defined(HAVE_ANDROID_OS)
807        if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
808            err = NO_ERROR;
809        else
810            err = -errno;
811#else
812        err = INVALID_OPERATION;
813#endif
814        if (mProcess->mDriverFD <= 0) {
815            err = -EBADF;
816        }
817        IF_LOG_COMMANDS() {
818            alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
819        }
820    } while (err == -EINTR);
821
822    IF_LOG_COMMANDS() {
823        alog << "Our err: " << (void*)err << ", write consumed: "
824            << bwr.write_consumed << " (of " << mOut.dataSize()
825			<< "), read consumed: " << bwr.read_consumed << endl;
826    }
827
828    if (err >= NO_ERROR) {
829        if (bwr.write_consumed > 0) {
830            if (bwr.write_consumed < (ssize_t)mOut.dataSize())
831                mOut.remove(0, bwr.write_consumed);
832            else
833                mOut.setDataSize(0);
834        }
835        if (bwr.read_consumed > 0) {
836            mIn.setDataSize(bwr.read_consumed);
837            mIn.setDataPosition(0);
838        }
839        IF_LOG_COMMANDS() {
840            TextOutput::Bundle _b(alog);
841            alog << "Remaining data size: " << mOut.dataSize() << endl;
842            alog << "Received commands from driver: " << indent;
843            const void* cmds = mIn.data();
844            const void* end = mIn.data() + mIn.dataSize();
845            alog << HexDump(cmds, mIn.dataSize()) << endl;
846            while (cmds < end) cmds = printReturnCommand(alog, cmds);
847            alog << dedent;
848        }
849        return NO_ERROR;
850    }
851
852    return err;
853}
854
855status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
856    int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
857{
858    binder_transaction_data tr;
859
860    tr.target.handle = handle;
861    tr.code = code;
862    tr.flags = binderFlags;
863    tr.cookie = 0;
864    tr.sender_pid = 0;
865    tr.sender_euid = 0;
866
867    const status_t err = data.errorCheck();
868    if (err == NO_ERROR) {
869        tr.data_size = data.ipcDataSize();
870        tr.data.ptr.buffer = data.ipcData();
871        tr.offsets_size = data.ipcObjectsCount()*sizeof(size_t);
872        tr.data.ptr.offsets = data.ipcObjects();
873    } else if (statusBuffer) {
874        tr.flags |= TF_STATUS_CODE;
875        *statusBuffer = err;
876        tr.data_size = sizeof(status_t);
877        tr.data.ptr.buffer = statusBuffer;
878        tr.offsets_size = 0;
879        tr.data.ptr.offsets = NULL;
880    } else {
881        return (mLastError = err);
882    }
883
884    mOut.writeInt32(cmd);
885    mOut.write(&tr, sizeof(tr));
886
887    return NO_ERROR;
888}
889
890sp<BBinder> the_context_object;
891
892void setTheContextObject(sp<BBinder> obj)
893{
894    the_context_object = obj;
895}
896
897status_t IPCThreadState::executeCommand(int32_t cmd)
898{
899    BBinder* obj;
900    RefBase::weakref_type* refs;
901    status_t result = NO_ERROR;
902
903    switch (cmd) {
904    case BR_ERROR:
905        result = mIn.readInt32();
906        break;
907
908    case BR_OK:
909        break;
910
911    case BR_ACQUIRE:
912        refs = (RefBase::weakref_type*)mIn.readInt32();
913        obj = (BBinder*)mIn.readInt32();
914        ALOG_ASSERT(refs->refBase() == obj,
915                   "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
916                   refs, obj, refs->refBase());
917        obj->incStrong(mProcess.get());
918        IF_LOG_REMOTEREFS() {
919            LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
920            obj->printRefs();
921        }
922        mOut.writeInt32(BC_ACQUIRE_DONE);
923        mOut.writeInt32((int32_t)refs);
924        mOut.writeInt32((int32_t)obj);
925        break;
926
927    case BR_RELEASE:
928        refs = (RefBase::weakref_type*)mIn.readInt32();
929        obj = (BBinder*)mIn.readInt32();
930        ALOG_ASSERT(refs->refBase() == obj,
931                   "BR_RELEASE: object %p does not match cookie %p (expected %p)",
932                   refs, obj, refs->refBase());
933        IF_LOG_REMOTEREFS() {
934            LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
935            obj->printRefs();
936        }
937        mPendingStrongDerefs.push(obj);
938        break;
939
940    case BR_INCREFS:
941        refs = (RefBase::weakref_type*)mIn.readInt32();
942        obj = (BBinder*)mIn.readInt32();
943        refs->incWeak(mProcess.get());
944        mOut.writeInt32(BC_INCREFS_DONE);
945        mOut.writeInt32((int32_t)refs);
946        mOut.writeInt32((int32_t)obj);
947        break;
948
949    case BR_DECREFS:
950        refs = (RefBase::weakref_type*)mIn.readInt32();
951        obj = (BBinder*)mIn.readInt32();
952        // NOTE: This assertion is not valid, because the object may no
953        // longer exist (thus the (BBinder*)cast above resulting in a different
954        // memory address).
955        //ALOG_ASSERT(refs->refBase() == obj,
956        //           "BR_DECREFS: object %p does not match cookie %p (expected %p)",
957        //           refs, obj, refs->refBase());
958        mPendingWeakDerefs.push(refs);
959        break;
960
961    case BR_ATTEMPT_ACQUIRE:
962        refs = (RefBase::weakref_type*)mIn.readInt32();
963        obj = (BBinder*)mIn.readInt32();
964
965        {
966            const bool success = refs->attemptIncStrong(mProcess.get());
967            ALOG_ASSERT(success && refs->refBase() == obj,
968                       "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
969                       refs, obj, refs->refBase());
970
971            mOut.writeInt32(BC_ACQUIRE_RESULT);
972            mOut.writeInt32((int32_t)success);
973        }
974        break;
975
976    case BR_TRANSACTION:
977        {
978            binder_transaction_data tr;
979            result = mIn.read(&tr, sizeof(tr));
980            ALOG_ASSERT(result == NO_ERROR,
981                "Not enough command data for brTRANSACTION");
982            if (result != NO_ERROR) break;
983
984            Parcel buffer;
985            buffer.ipcSetDataReference(
986                reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
987                tr.data_size,
988                reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
989                tr.offsets_size/sizeof(size_t), freeBuffer, this);
990
991            const pid_t origPid = mCallingPid;
992            const uid_t origUid = mCallingUid;
993
994            mCallingPid = tr.sender_pid;
995            mCallingUid = tr.sender_euid;
996
997            int curPrio = getpriority(PRIO_PROCESS, mMyThreadId);
998            if (gDisableBackgroundScheduling) {
999                if (curPrio > ANDROID_PRIORITY_NORMAL) {
1000                    // We have inherited a reduced priority from the caller, but do not
1001                    // want to run in that state in this process.  The driver set our
1002                    // priority already (though not our scheduling class), so bounce
1003                    // it back to the default before invoking the transaction.
1004                    setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL);
1005                }
1006            } else {
1007                if (curPrio >= ANDROID_PRIORITY_BACKGROUND) {
1008                    // We want to use the inherited priority from the caller.
1009                    // Ensure this thread is in the background scheduling class,
1010                    // since the driver won't modify scheduling classes for us.
1011                    // The scheduling group is reset to default by the caller
1012                    // once this method returns after the transaction is complete.
1013                    set_sched_policy(mMyThreadId, SP_BACKGROUND);
1014                }
1015            }
1016
1017            //ALOGI(">>>> TRANSACT from pid %d uid %d\n", mCallingPid, mCallingUid);
1018
1019            Parcel reply;
1020            IF_LOG_TRANSACTIONS() {
1021                TextOutput::Bundle _b(alog);
1022                alog << "BR_TRANSACTION thr " << (void*)pthread_self()
1023                    << " / obj " << tr.target.ptr << " / code "
1024                    << TypeCode(tr.code) << ": " << indent << buffer
1025                    << dedent << endl
1026                    << "Data addr = "
1027                    << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1028                    << ", offsets addr="
1029                    << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
1030            }
1031            if (tr.target.ptr) {
1032                sp<BBinder> b((BBinder*)tr.cookie);
1033                const status_t error = b->transact(tr.code, buffer, &reply, tr.flags);
1034                if (error < NO_ERROR) reply.setError(error);
1035
1036            } else {
1037                const status_t error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
1038                if (error < NO_ERROR) reply.setError(error);
1039            }
1040
1041            //ALOGI("<<<< TRANSACT from pid %d restore pid %d uid %d\n",
1042            //     mCallingPid, origPid, origUid);
1043
1044            if ((tr.flags & TF_ONE_WAY) == 0) {
1045                LOG_ONEWAY("Sending reply to %d!", mCallingPid);
1046                sendReply(reply, 0);
1047            } else {
1048                LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1049            }
1050
1051            mCallingPid = origPid;
1052            mCallingUid = origUid;
1053
1054            IF_LOG_TRANSACTIONS() {
1055                TextOutput::Bundle _b(alog);
1056                alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
1057                    << tr.target.ptr << ": " << indent << reply << dedent << endl;
1058            }
1059
1060        }
1061        break;
1062
1063    case BR_DEAD_BINDER:
1064        {
1065            BpBinder *proxy = (BpBinder*)mIn.readInt32();
1066            proxy->sendObituary();
1067            mOut.writeInt32(BC_DEAD_BINDER_DONE);
1068            mOut.writeInt32((int32_t)proxy);
1069        } break;
1070
1071    case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1072        {
1073            BpBinder *proxy = (BpBinder*)mIn.readInt32();
1074            proxy->getWeakRefs()->decWeak(proxy);
1075        } break;
1076
1077    case BR_FINISHED:
1078        result = TIMED_OUT;
1079        break;
1080
1081    case BR_NOOP:
1082        break;
1083
1084    case BR_SPAWN_LOOPER:
1085        mProcess->spawnPooledThread(false);
1086        break;
1087
1088    default:
1089        printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
1090        result = UNKNOWN_ERROR;
1091        break;
1092    }
1093
1094    if (result != NO_ERROR) {
1095        mLastError = result;
1096    }
1097
1098    return result;
1099}
1100
1101void IPCThreadState::threadDestructor(void *st)
1102{
1103	IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1104	if (self) {
1105		self->flushCommands();
1106#if defined(HAVE_ANDROID_OS)
1107        if (self->mProcess->mDriverFD > 0) {
1108            ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1109        }
1110#endif
1111		delete self;
1112	}
1113}
1114
1115
1116void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data, size_t dataSize,
1117                                const size_t* objects, size_t objectsSize,
1118                                void* cookie)
1119{
1120    //ALOGI("Freeing parcel %p", &parcel);
1121    IF_LOG_COMMANDS() {
1122        alog << "Writing BC_FREE_BUFFER for " << data << endl;
1123    }
1124    ALOG_ASSERT(data != NULL, "Called with NULL data");
1125    if (parcel != NULL) parcel->closeFileDescriptors();
1126    IPCThreadState* state = self();
1127    state->mOut.writeInt32(BC_FREE_BUFFER);
1128    state->mOut.writeInt32((int32_t)data);
1129}
1130
1131}; // namespace android
1132