IPCThreadState.cpp revision d547432f98889d57a8c37e91090664efe63da436
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    tr.cookie = 0;
855    tr.sender_pid = 0;
856    tr.sender_euid = 0;
857
858    const status_t err = data.errorCheck();
859    if (err == NO_ERROR) {
860        tr.data_size = data.ipcDataSize();
861        tr.data.ptr.buffer = data.ipcData();
862        tr.offsets_size = data.ipcObjectsCount()*sizeof(size_t);
863        tr.data.ptr.offsets = data.ipcObjects();
864    } else if (statusBuffer) {
865        tr.flags |= TF_STATUS_CODE;
866        *statusBuffer = err;
867        tr.data_size = sizeof(status_t);
868        tr.data.ptr.buffer = statusBuffer;
869        tr.offsets_size = 0;
870        tr.data.ptr.offsets = NULL;
871    } else {
872        return (mLastError = err);
873    }
874
875    mOut.writeInt32(cmd);
876    mOut.write(&tr, sizeof(tr));
877
878    return NO_ERROR;
879}
880
881sp<BBinder> the_context_object;
882
883void setTheContextObject(sp<BBinder> obj)
884{
885    the_context_object = obj;
886}
887
888status_t IPCThreadState::executeCommand(int32_t cmd)
889{
890    BBinder* obj;
891    RefBase::weakref_type* refs;
892    status_t result = NO_ERROR;
893
894    switch (cmd) {
895    case BR_ERROR:
896        result = mIn.readInt32();
897        break;
898
899    case BR_OK:
900        break;
901
902    case BR_ACQUIRE:
903        refs = (RefBase::weakref_type*)mIn.readInt32();
904        obj = (BBinder*)mIn.readInt32();
905        LOG_ASSERT(refs->refBase() == obj,
906                   "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
907                   refs, obj, refs->refBase());
908        obj->incStrong(mProcess.get());
909        IF_LOG_REMOTEREFS() {
910            LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
911            obj->printRefs();
912        }
913        mOut.writeInt32(BC_ACQUIRE_DONE);
914        mOut.writeInt32((int32_t)refs);
915        mOut.writeInt32((int32_t)obj);
916        break;
917
918    case BR_RELEASE:
919        refs = (RefBase::weakref_type*)mIn.readInt32();
920        obj = (BBinder*)mIn.readInt32();
921        LOG_ASSERT(refs->refBase() == obj,
922                   "BR_RELEASE: object %p does not match cookie %p (expected %p)",
923                   refs, obj, refs->refBase());
924        IF_LOG_REMOTEREFS() {
925            LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
926            obj->printRefs();
927        }
928        mPendingStrongDerefs.push(obj);
929        break;
930
931    case BR_INCREFS:
932        refs = (RefBase::weakref_type*)mIn.readInt32();
933        obj = (BBinder*)mIn.readInt32();
934        refs->incWeak(mProcess.get());
935        mOut.writeInt32(BC_INCREFS_DONE);
936        mOut.writeInt32((int32_t)refs);
937        mOut.writeInt32((int32_t)obj);
938        break;
939
940    case BR_DECREFS:
941        refs = (RefBase::weakref_type*)mIn.readInt32();
942        obj = (BBinder*)mIn.readInt32();
943        // NOTE: This assertion is not valid, because the object may no
944        // longer exist (thus the (BBinder*)cast above resulting in a different
945        // memory address).
946        //LOG_ASSERT(refs->refBase() == obj,
947        //           "BR_DECREFS: object %p does not match cookie %p (expected %p)",
948        //           refs, obj, refs->refBase());
949        mPendingWeakDerefs.push(refs);
950        break;
951
952    case BR_ATTEMPT_ACQUIRE:
953        refs = (RefBase::weakref_type*)mIn.readInt32();
954        obj = (BBinder*)mIn.readInt32();
955
956        {
957            const bool success = refs->attemptIncStrong(mProcess.get());
958            LOG_ASSERT(success && refs->refBase() == obj,
959                       "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
960                       refs, obj, refs->refBase());
961
962            mOut.writeInt32(BC_ACQUIRE_RESULT);
963            mOut.writeInt32((int32_t)success);
964        }
965        break;
966
967    case BR_TRANSACTION:
968        {
969            binder_transaction_data tr;
970            result = mIn.read(&tr, sizeof(tr));
971            LOG_ASSERT(result == NO_ERROR,
972                "Not enough command data for brTRANSACTION");
973            if (result != NO_ERROR) break;
974
975            Parcel buffer;
976            buffer.ipcSetDataReference(
977                reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
978                tr.data_size,
979                reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
980                tr.offsets_size/sizeof(size_t), freeBuffer, this);
981
982            const pid_t origPid = mCallingPid;
983            const uid_t origUid = mCallingUid;
984
985            mCallingPid = tr.sender_pid;
986            mCallingUid = tr.sender_euid;
987
988            int curPrio = getpriority(PRIO_PROCESS, mMyThreadId);
989            if (gDisableBackgroundScheduling) {
990                if (curPrio > ANDROID_PRIORITY_NORMAL) {
991                    // We have inherited a reduced priority from the caller, but do not
992                    // want to run in that state in this process.  The driver set our
993                    // priority already (though not our scheduling class), so bounce
994                    // it back to the default before invoking the transaction.
995                    setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL);
996                }
997            } else {
998                if (curPrio >= ANDROID_PRIORITY_BACKGROUND) {
999                    // We want to use the inherited priority from the caller.
1000                    // Ensure this thread is in the background scheduling class,
1001                    // since the driver won't modify scheduling classes for us.
1002                    // The scheduling group is reset to default by the caller
1003                    // once this method returns after the transaction is complete.
1004                    androidSetThreadSchedulingGroup(mMyThreadId,
1005                                                    ANDROID_TGROUP_BG_NONINTERACT);
1006                }
1007            }
1008
1009            //LOGI(">>>> TRANSACT from pid %d uid %d\n", mCallingPid, mCallingUid);
1010
1011            Parcel reply;
1012            IF_LOG_TRANSACTIONS() {
1013                TextOutput::Bundle _b(alog);
1014                alog << "BR_TRANSACTION thr " << (void*)pthread_self()
1015                    << " / obj " << tr.target.ptr << " / code "
1016                    << TypeCode(tr.code) << ": " << indent << buffer
1017                    << dedent << endl
1018                    << "Data addr = "
1019                    << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1020                    << ", offsets addr="
1021                    << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
1022            }
1023            if (tr.target.ptr) {
1024                sp<BBinder> b((BBinder*)tr.cookie);
1025                const status_t error = b->transact(tr.code, buffer, &reply, tr.flags);
1026                if (error < NO_ERROR) reply.setError(error);
1027
1028            } else {
1029                const status_t error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
1030                if (error < NO_ERROR) reply.setError(error);
1031            }
1032
1033            //LOGI("<<<< TRANSACT from pid %d restore pid %d uid %d\n",
1034            //     mCallingPid, origPid, origUid);
1035
1036            if ((tr.flags & TF_ONE_WAY) == 0) {
1037                LOG_ONEWAY("Sending reply to %d!", mCallingPid);
1038                sendReply(reply, 0);
1039            } else {
1040                LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1041            }
1042
1043            mCallingPid = origPid;
1044            mCallingUid = origUid;
1045
1046            IF_LOG_TRANSACTIONS() {
1047                TextOutput::Bundle _b(alog);
1048                alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
1049                    << tr.target.ptr << ": " << indent << reply << dedent << endl;
1050            }
1051
1052        }
1053        break;
1054
1055    case BR_DEAD_BINDER:
1056        {
1057            BpBinder *proxy = (BpBinder*)mIn.readInt32();
1058            proxy->sendObituary();
1059            mOut.writeInt32(BC_DEAD_BINDER_DONE);
1060            mOut.writeInt32((int32_t)proxy);
1061        } break;
1062
1063    case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1064        {
1065            BpBinder *proxy = (BpBinder*)mIn.readInt32();
1066            proxy->getWeakRefs()->decWeak(proxy);
1067        } break;
1068
1069    case BR_FINISHED:
1070        result = TIMED_OUT;
1071        break;
1072
1073    case BR_NOOP:
1074        break;
1075
1076    case BR_SPAWN_LOOPER:
1077        mProcess->spawnPooledThread(false);
1078        break;
1079
1080    default:
1081        printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
1082        result = UNKNOWN_ERROR;
1083        break;
1084    }
1085
1086    if (result != NO_ERROR) {
1087        mLastError = result;
1088    }
1089
1090    return result;
1091}
1092
1093void IPCThreadState::threadDestructor(void *st)
1094{
1095	IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1096	if (self) {
1097		self->flushCommands();
1098#if defined(HAVE_ANDROID_OS)
1099        ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1100#endif
1101		delete self;
1102	}
1103}
1104
1105
1106void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data, size_t dataSize,
1107                                const size_t* objects, size_t objectsSize,
1108                                void* cookie)
1109{
1110    //LOGI("Freeing parcel %p", &parcel);
1111    IF_LOG_COMMANDS() {
1112        alog << "Writing BC_FREE_BUFFER for " << data << endl;
1113    }
1114    LOG_ASSERT(data != NULL, "Called with NULL data");
1115    if (parcel != NULL) parcel->closeFileDescriptors();
1116    IPCThreadState* state = self();
1117    state->mOut.writeInt32(BC_FREE_BUFFER);
1118    state->mOut.writeInt32((int32_t)data);
1119}
1120
1121}; // namespace android
1122