IPCThreadState.cpp revision b5c41353337b3db2dc0ca0df163d5294af8281bc
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;
295
296IPCThreadState* IPCThreadState::self()
297{
298    if (gHaveTLS) {
299restart:
300        const pthread_key_t k = gTLS;
301        IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
302        if (st) return st;
303        return new IPCThreadState;
304    }
305
306    if (gShutdown) return NULL;
307
308    pthread_mutex_lock(&gTLSMutex);
309    if (!gHaveTLS) {
310        if (pthread_key_create(&gTLS, threadDestructor) != 0) {
311            pthread_mutex_unlock(&gTLSMutex);
312            return NULL;
313        }
314        gHaveTLS = true;
315    }
316    pthread_mutex_unlock(&gTLSMutex);
317    goto restart;
318}
319
320void IPCThreadState::shutdown()
321{
322    gShutdown = true;
323
324    if (gHaveTLS) {
325        // XXX Need to wait for all thread pool threads to exit!
326        IPCThreadState* st = (IPCThreadState*)pthread_getspecific(gTLS);
327        if (st) {
328            delete st;
329            pthread_setspecific(gTLS, NULL);
330        }
331        gHaveTLS = false;
332    }
333}
334
335sp<ProcessState> IPCThreadState::process()
336{
337    return mProcess;
338}
339
340status_t IPCThreadState::clearLastError()
341{
342    const status_t err = mLastError;
343    mLastError = NO_ERROR;
344    return err;
345}
346
347int IPCThreadState::getCallingPid()
348{
349    return mCallingPid;
350}
351
352int IPCThreadState::getCallingUid()
353{
354    return mCallingUid;
355}
356
357int64_t IPCThreadState::clearCallingIdentity()
358{
359    int64_t token = ((int64_t)mCallingUid<<32) | mCallingPid;
360    clearCaller();
361    return token;
362}
363
364void IPCThreadState::restoreCallingIdentity(int64_t token)
365{
366    mCallingUid = (int)(token>>32);
367    mCallingPid = (int)token;
368}
369
370void IPCThreadState::clearCaller()
371{
372    mCallingPid = getpid();
373    mCallingUid = getuid();
374}
375
376void IPCThreadState::flushCommands()
377{
378    if (mProcess->mDriverFD <= 0)
379        return;
380    talkWithDriver(false);
381}
382
383void IPCThreadState::joinThreadPool(bool isMain)
384{
385    LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
386
387    mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
388
389    status_t result;
390    do {
391        int32_t cmd;
392
393        // When we've cleared the incoming command queue, process any pending derefs
394        if (mIn.dataPosition() >= mIn.dataSize()) {
395            size_t numPending = mPendingWeakDerefs.size();
396            if (numPending > 0) {
397                for (size_t i = 0; i < numPending; i++) {
398                    RefBase::weakref_type* refs = mPendingWeakDerefs[i];
399                    refs->decWeak(mProcess.get());
400                }
401                mPendingWeakDerefs.clear();
402            }
403
404            numPending = mPendingStrongDerefs.size();
405            if (numPending > 0) {
406                for (size_t i = 0; i < numPending; i++) {
407                    BBinder* obj = mPendingStrongDerefs[i];
408                    obj->decStrong(mProcess.get());
409                }
410                mPendingStrongDerefs.clear();
411            }
412        }
413
414        // now get the next command to be processed, waiting if necessary
415        result = talkWithDriver();
416        if (result >= NO_ERROR) {
417            size_t IN = mIn.dataAvail();
418            if (IN < sizeof(int32_t)) continue;
419            cmd = mIn.readInt32();
420            IF_LOG_COMMANDS() {
421                alog << "Processing top-level Command: "
422                    << getReturnString(cmd) << endl;
423            }
424
425
426            result = executeCommand(cmd);
427
428            // Make sure that after executing the command that we put the thread back into the
429            // default cgroup. This is just a failsafe incase the thread's priority or cgroup was
430            // not properly restored.
431            set_sched_policy(getpid(), SP_FOREGROUND);
432        }
433
434        // Let this thread exit the thread pool if it is no longer
435        // needed and it is not the main process thread.
436        if(result == TIMED_OUT && !isMain) {
437            break;
438        }
439    } while (result != -ECONNREFUSED && result != -EBADF);
440
441    LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%p\n",
442        (void*)pthread_self(), getpid(), (void*)result);
443
444    mOut.writeInt32(BC_EXIT_LOOPER);
445    talkWithDriver(false);
446}
447
448void IPCThreadState::stopProcess(bool immediate)
449{
450    //LOGI("**** STOPPING PROCESS");
451    flushCommands();
452    int fd = mProcess->mDriverFD;
453    mProcess->mDriverFD = -1;
454    close(fd);
455    //kill(getpid(), SIGKILL);
456}
457
458status_t IPCThreadState::transact(int32_t handle,
459                                  uint32_t code, const Parcel& data,
460                                  Parcel* reply, uint32_t flags)
461{
462    status_t err = data.errorCheck();
463
464    flags |= TF_ACCEPT_FDS;
465
466    IF_LOG_TRANSACTIONS() {
467        TextOutput::Bundle _b(alog);
468        alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
469            << handle << " / code " << TypeCode(code) << ": "
470            << indent << data << dedent << endl;
471    }
472
473    if (err == NO_ERROR) {
474        LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
475            (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
476        err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);
477    }
478
479    if (err != NO_ERROR) {
480        if (reply) reply->setError(err);
481        return (mLastError = err);
482    }
483
484    if ((flags & TF_ONE_WAY) == 0) {
485        if (reply) {
486            err = waitForResponse(reply);
487        } else {
488            Parcel fakeReply;
489            err = waitForResponse(&fakeReply);
490        }
491
492        IF_LOG_TRANSACTIONS() {
493            TextOutput::Bundle _b(alog);
494            alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
495                << handle << ": ";
496            if (reply) alog << indent << *reply << dedent << endl;
497            else alog << "(none requested)" << endl;
498        }
499    } else {
500        err = waitForResponse(NULL, NULL);
501    }
502
503    return err;
504}
505
506void IPCThreadState::incStrongHandle(int32_t handle)
507{
508    LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
509    mOut.writeInt32(BC_ACQUIRE);
510    mOut.writeInt32(handle);
511}
512
513void IPCThreadState::decStrongHandle(int32_t handle)
514{
515    LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
516    mOut.writeInt32(BC_RELEASE);
517    mOut.writeInt32(handle);
518}
519
520void IPCThreadState::incWeakHandle(int32_t handle)
521{
522    LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
523    mOut.writeInt32(BC_INCREFS);
524    mOut.writeInt32(handle);
525}
526
527void IPCThreadState::decWeakHandle(int32_t handle)
528{
529    LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
530    mOut.writeInt32(BC_DECREFS);
531    mOut.writeInt32(handle);
532}
533
534status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
535{
536    mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
537    mOut.writeInt32(0); // xxx was thread priority
538    mOut.writeInt32(handle);
539    status_t result = UNKNOWN_ERROR;
540
541    waitForResponse(NULL, &result);
542
543#if LOG_REFCOUNTS
544    printf("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
545        handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
546#endif
547
548    return result;
549}
550
551void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
552{
553#if LOG_REFCOUNTS
554    printf("IPCThreadState::expungeHandle(%ld)\n", handle);
555#endif
556    self()->mProcess->expungeHandle(handle, binder);
557}
558
559status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
560{
561    mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
562    mOut.writeInt32((int32_t)handle);
563    mOut.writeInt32((int32_t)proxy);
564    return NO_ERROR;
565}
566
567status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
568{
569    mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
570    mOut.writeInt32((int32_t)handle);
571    mOut.writeInt32((int32_t)proxy);
572    return NO_ERROR;
573}
574
575IPCThreadState::IPCThreadState()
576    : mProcess(ProcessState::self())
577{
578    pthread_setspecific(gTLS, this);
579        clearCaller();
580    mIn.setDataCapacity(256);
581    mOut.setDataCapacity(256);
582}
583
584IPCThreadState::~IPCThreadState()
585{
586}
587
588status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
589{
590    status_t err;
591    status_t statusBuffer;
592    err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
593    if (err < NO_ERROR) return err;
594
595    return waitForResponse(NULL, NULL);
596}
597
598status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
599{
600    int32_t cmd;
601    int32_t err;
602
603    while (1) {
604        if ((err=talkWithDriver()) < NO_ERROR) break;
605        err = mIn.errorCheck();
606        if (err < NO_ERROR) break;
607        if (mIn.dataAvail() == 0) continue;
608
609        cmd = mIn.readInt32();
610
611        IF_LOG_COMMANDS() {
612            alog << "Processing waitForResponse Command: "
613                << getReturnString(cmd) << endl;
614        }
615
616        switch (cmd) {
617        case BR_TRANSACTION_COMPLETE:
618            if (!reply && !acquireResult) goto finish;
619            break;
620
621        case BR_DEAD_REPLY:
622            err = DEAD_OBJECT;
623            goto finish;
624
625        case BR_FAILED_REPLY:
626            err = FAILED_TRANSACTION;
627            goto finish;
628
629        case BR_ACQUIRE_RESULT:
630            {
631                LOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
632                const int32_t result = mIn.readInt32();
633                if (!acquireResult) continue;
634                *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
635            }
636            goto finish;
637
638        case BR_REPLY:
639            {
640                binder_transaction_data tr;
641                err = mIn.read(&tr, sizeof(tr));
642                LOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
643                if (err != NO_ERROR) goto finish;
644
645                if (reply) {
646                    if ((tr.flags & TF_STATUS_CODE) == 0) {
647                        reply->ipcSetDataReference(
648                            reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
649                            tr.data_size,
650                            reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
651                            tr.offsets_size/sizeof(size_t),
652                            freeBuffer, this);
653                    } else {
654                        err = *static_cast<const status_t*>(tr.data.ptr.buffer);
655                        freeBuffer(NULL,
656                            reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
657                            tr.data_size,
658                            reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
659                            tr.offsets_size/sizeof(size_t), this);
660                    }
661                } else {
662                    freeBuffer(NULL,
663                        reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
664                        tr.data_size,
665                        reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
666                        tr.offsets_size/sizeof(size_t), this);
667                    continue;
668                }
669            }
670            goto finish;
671
672        default:
673            err = executeCommand(cmd);
674            if (err != NO_ERROR) goto finish;
675            break;
676        }
677    }
678
679finish:
680    if (err != NO_ERROR) {
681        if (acquireResult) *acquireResult = err;
682        if (reply) reply->setError(err);
683        mLastError = err;
684    }
685
686    return err;
687}
688
689status_t IPCThreadState::talkWithDriver(bool doReceive)
690{
691    LOG_ASSERT(mProcess->mDriverFD >= 0, "Binder driver is not opened");
692
693    binder_write_read bwr;
694
695    // Is the read buffer empty?
696    const bool needRead = mIn.dataPosition() >= mIn.dataSize();
697
698    // We don't want to write anything if we are still reading
699    // from data left in the input buffer and the caller
700    // has requested to read the next data.
701    const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
702
703    bwr.write_size = outAvail;
704    bwr.write_buffer = (long unsigned int)mOut.data();
705
706    // This is what we'll read.
707    if (doReceive && needRead) {
708        bwr.read_size = mIn.dataCapacity();
709        bwr.read_buffer = (long unsigned int)mIn.data();
710    } else {
711        bwr.read_size = 0;
712    }
713
714    IF_LOG_COMMANDS() {
715        TextOutput::Bundle _b(alog);
716        if (outAvail != 0) {
717            alog << "Sending commands to driver: " << indent;
718            const void* cmds = (const void*)bwr.write_buffer;
719            const void* end = ((const uint8_t*)cmds)+bwr.write_size;
720            alog << HexDump(cmds, bwr.write_size) << endl;
721            while (cmds < end) cmds = printCommand(alog, cmds);
722            alog << dedent;
723        }
724        alog << "Size of receive buffer: " << bwr.read_size
725            << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
726    }
727
728    // Return immediately if there is nothing to do.
729    if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
730
731    bwr.write_consumed = 0;
732    bwr.read_consumed = 0;
733    status_t err;
734    do {
735        IF_LOG_COMMANDS() {
736            alog << "About to read/write, write size = " << mOut.dataSize() << endl;
737        }
738#if defined(HAVE_ANDROID_OS)
739        if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
740            err = NO_ERROR;
741        else
742            err = -errno;
743#else
744        err = INVALID_OPERATION;
745#endif
746        IF_LOG_COMMANDS() {
747            alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
748        }
749    } while (err == -EINTR);
750
751    IF_LOG_COMMANDS() {
752        alog << "Our err: " << (void*)err << ", write consumed: "
753            << bwr.write_consumed << " (of " << mOut.dataSize()
754			<< "), read consumed: " << bwr.read_consumed << endl;
755    }
756
757    if (err >= NO_ERROR) {
758        if (bwr.write_consumed > 0) {
759            if (bwr.write_consumed < (ssize_t)mOut.dataSize())
760                mOut.remove(0, bwr.write_consumed);
761            else
762                mOut.setDataSize(0);
763        }
764        if (bwr.read_consumed > 0) {
765            mIn.setDataSize(bwr.read_consumed);
766            mIn.setDataPosition(0);
767        }
768        IF_LOG_COMMANDS() {
769            TextOutput::Bundle _b(alog);
770            alog << "Remaining data size: " << mOut.dataSize() << endl;
771            alog << "Received commands from driver: " << indent;
772            const void* cmds = mIn.data();
773            const void* end = mIn.data() + mIn.dataSize();
774            alog << HexDump(cmds, mIn.dataSize()) << endl;
775            while (cmds < end) cmds = printReturnCommand(alog, cmds);
776            alog << dedent;
777        }
778        return NO_ERROR;
779    }
780
781    return err;
782}
783
784status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
785    int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
786{
787    binder_transaction_data tr;
788
789    tr.target.handle = handle;
790    tr.code = code;
791    tr.flags = binderFlags;
792
793    const status_t err = data.errorCheck();
794    if (err == NO_ERROR) {
795        tr.data_size = data.ipcDataSize();
796        tr.data.ptr.buffer = data.ipcData();
797        tr.offsets_size = data.ipcObjectsCount()*sizeof(size_t);
798        tr.data.ptr.offsets = data.ipcObjects();
799    } else if (statusBuffer) {
800        tr.flags |= TF_STATUS_CODE;
801        *statusBuffer = err;
802        tr.data_size = sizeof(status_t);
803        tr.data.ptr.buffer = statusBuffer;
804        tr.offsets_size = 0;
805        tr.data.ptr.offsets = NULL;
806    } else {
807        return (mLastError = err);
808    }
809
810    mOut.writeInt32(cmd);
811    mOut.write(&tr, sizeof(tr));
812
813    return NO_ERROR;
814}
815
816sp<BBinder> the_context_object;
817
818void setTheContextObject(sp<BBinder> obj)
819{
820    the_context_object = obj;
821}
822
823status_t IPCThreadState::executeCommand(int32_t cmd)
824{
825    BBinder* obj;
826    RefBase::weakref_type* refs;
827    status_t result = NO_ERROR;
828
829    switch (cmd) {
830    case BR_ERROR:
831        result = mIn.readInt32();
832        break;
833
834    case BR_OK:
835        break;
836
837    case BR_ACQUIRE:
838        refs = (RefBase::weakref_type*)mIn.readInt32();
839        obj = (BBinder*)mIn.readInt32();
840        LOG_ASSERT(refs->refBase() == obj,
841                   "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
842                   refs, obj, refs->refBase());
843        obj->incStrong(mProcess.get());
844        IF_LOG_REMOTEREFS() {
845            LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
846            obj->printRefs();
847        }
848        mOut.writeInt32(BC_ACQUIRE_DONE);
849        mOut.writeInt32((int32_t)refs);
850        mOut.writeInt32((int32_t)obj);
851        break;
852
853    case BR_RELEASE:
854        refs = (RefBase::weakref_type*)mIn.readInt32();
855        obj = (BBinder*)mIn.readInt32();
856        LOG_ASSERT(refs->refBase() == obj,
857                   "BR_RELEASE: object %p does not match cookie %p (expected %p)",
858                   refs, obj, refs->refBase());
859        IF_LOG_REMOTEREFS() {
860            LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
861            obj->printRefs();
862        }
863        mPendingStrongDerefs.push(obj);
864        break;
865
866    case BR_INCREFS:
867        refs = (RefBase::weakref_type*)mIn.readInt32();
868        obj = (BBinder*)mIn.readInt32();
869        refs->incWeak(mProcess.get());
870        mOut.writeInt32(BC_INCREFS_DONE);
871        mOut.writeInt32((int32_t)refs);
872        mOut.writeInt32((int32_t)obj);
873        break;
874
875    case BR_DECREFS:
876        refs = (RefBase::weakref_type*)mIn.readInt32();
877        obj = (BBinder*)mIn.readInt32();
878        // NOTE: This assertion is not valid, because the object may no
879        // longer exist (thus the (BBinder*)cast above resulting in a different
880        // memory address).
881        //LOG_ASSERT(refs->refBase() == obj,
882        //           "BR_DECREFS: object %p does not match cookie %p (expected %p)",
883        //           refs, obj, refs->refBase());
884        mPendingWeakDerefs.push(refs);
885        break;
886
887    case BR_ATTEMPT_ACQUIRE:
888        refs = (RefBase::weakref_type*)mIn.readInt32();
889        obj = (BBinder*)mIn.readInt32();
890
891        {
892            const bool success = refs->attemptIncStrong(mProcess.get());
893            LOG_ASSERT(success && refs->refBase() == obj,
894                       "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
895                       refs, obj, refs->refBase());
896
897            mOut.writeInt32(BC_ACQUIRE_RESULT);
898            mOut.writeInt32((int32_t)success);
899        }
900        break;
901
902    case BR_TRANSACTION:
903        {
904            binder_transaction_data tr;
905            result = mIn.read(&tr, sizeof(tr));
906            LOG_ASSERT(result == NO_ERROR,
907                "Not enough command data for brTRANSACTION");
908            if (result != NO_ERROR) break;
909
910            Parcel buffer;
911            buffer.ipcSetDataReference(
912                reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
913                tr.data_size,
914                reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
915                tr.offsets_size/sizeof(size_t), freeBuffer, this);
916
917            const pid_t origPid = mCallingPid;
918            const uid_t origUid = mCallingUid;
919
920            mCallingPid = tr.sender_pid;
921            mCallingUid = tr.sender_euid;
922
923            //LOGI(">>>> TRANSACT from pid %d uid %d\n", mCallingPid, mCallingUid);
924
925            Parcel reply;
926            IF_LOG_TRANSACTIONS() {
927                TextOutput::Bundle _b(alog);
928                alog << "BR_TRANSACTION thr " << (void*)pthread_self()
929                    << " / obj " << tr.target.ptr << " / code "
930                    << TypeCode(tr.code) << ": " << indent << buffer
931                    << dedent << endl
932                    << "Data addr = "
933                    << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
934                    << ", offsets addr="
935                    << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
936            }
937            if (tr.target.ptr) {
938                sp<BBinder> b((BBinder*)tr.cookie);
939                const status_t error = b->transact(tr.code, buffer, &reply, 0);
940                if (error < NO_ERROR) reply.setError(error);
941
942            } else {
943                const status_t error = the_context_object->transact(tr.code, buffer, &reply, 0);
944                if (error < NO_ERROR) reply.setError(error);
945            }
946
947            //LOGI("<<<< TRANSACT from pid %d restore pid %d uid %d\n",
948            //     mCallingPid, origPid, origUid);
949
950            if ((tr.flags & TF_ONE_WAY) == 0) {
951                LOG_ONEWAY("Sending reply to %d!", mCallingPid);
952                sendReply(reply, 0);
953            } else {
954                LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
955            }
956
957            mCallingPid = origPid;
958            mCallingUid = origUid;
959
960            IF_LOG_TRANSACTIONS() {
961                TextOutput::Bundle _b(alog);
962                alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
963                    << tr.target.ptr << ": " << indent << reply << dedent << endl;
964            }
965
966        }
967        break;
968
969    case BR_DEAD_BINDER:
970        {
971            BpBinder *proxy = (BpBinder*)mIn.readInt32();
972            proxy->sendObituary();
973            mOut.writeInt32(BC_DEAD_BINDER_DONE);
974            mOut.writeInt32((int32_t)proxy);
975        } break;
976
977    case BR_CLEAR_DEATH_NOTIFICATION_DONE:
978        {
979            BpBinder *proxy = (BpBinder*)mIn.readInt32();
980            proxy->getWeakRefs()->decWeak(proxy);
981        } break;
982
983    case BR_FINISHED:
984        result = TIMED_OUT;
985        break;
986
987    case BR_NOOP:
988        break;
989
990    case BR_SPAWN_LOOPER:
991        mProcess->spawnPooledThread(false);
992        break;
993
994    default:
995        printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
996        result = UNKNOWN_ERROR;
997        break;
998    }
999
1000    if (result != NO_ERROR) {
1001        mLastError = result;
1002    }
1003
1004    return result;
1005}
1006
1007void IPCThreadState::threadDestructor(void *st)
1008{
1009	IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1010	if (self) {
1011		self->flushCommands();
1012#if defined(HAVE_ANDROID_OS)
1013        ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1014#endif
1015		delete self;
1016	}
1017}
1018
1019
1020void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data, size_t dataSize,
1021                                const size_t* objects, size_t objectsSize,
1022                                void* cookie)
1023{
1024    //LOGI("Freeing parcel %p", &parcel);
1025    IF_LOG_COMMANDS() {
1026        alog << "Writing BC_FREE_BUFFER for " << data << endl;
1027    }
1028    LOG_ASSERT(data != NULL, "Called with NULL data");
1029    if (parcel != NULL) parcel->closeFileDescriptors();
1030    IPCThreadState* state = self();
1031    state->mOut.writeInt32(BC_FREE_BUFFER);
1032    state->mOut.writeInt32((int32_t)data);
1033}
1034
1035}; // namespace android
1036