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