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