blob: b2a7db8301b36e80e730efb93465228b461daef5 [file] [log] [blame]
Mathias Agopian7922fa22009-05-18 15:08:03 -07001/*
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
Jason Parks2b17f142009-11-03 12:14:38 -080017#define LOG_TAG "IPCThreadState"
18
Mathias Agopian16475702009-05-19 19:08:10 -070019#include <binder/IPCThreadState.h>
Mathias Agopian7922fa22009-05-18 15:08:03 -070020
Mathias Agopian16475702009-05-19 19:08:10 -070021#include <binder/Binder.h>
22#include <binder/BpBinder.h>
Jason Parks2b17f142009-11-03 12:14:38 -080023#include <cutils/sched_policy.h>
Mathias Agopian7922fa22009-05-18 15:08:03 -070024#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{
Marco Nelissenb4f35d02009-07-17 07:59:17 -0700372 mCallingPid = getpid();
373 mCallingUid = getuid();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700374}
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 }
Jason Parks2b17f142009-11-03 12:14:38 -0800424
Jason Parks2b17f142009-11-03 12:14:38 -0800425
Mathias Agopian7922fa22009-05-18 15:08:03 -0700426 result = executeCommand(cmd);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700427 }
428
Christopher Tate0d7c8be2009-11-08 14:29:02 -0800429 // After executing the command, ensure that the thread is returned to the
430 // default cgroup and priority before rejoining the pool. This is a failsafe
431 // in case the command implementation failed to properly restore the thread's
432 // scheduling parameters upon completion.
433 int my_id;
434#ifdef HAVE_GETTID
435 my_id = gettid();
436#else
437 my_id = getpid();
438#endif
439 if (!set_sched_policy(my_id, SP_FOREGROUND)) {
440 // success; reset the priority as well
441 setpriority(PRIO_PROCESS, my_id, ANDROID_PRIORITY_NORMAL);
442 }
443
Mathias Agopian7922fa22009-05-18 15:08:03 -0700444 // Let this thread exit the thread pool if it is no longer
445 // needed and it is not the main process thread.
446 if(result == TIMED_OUT && !isMain) {
447 break;
448 }
449 } while (result != -ECONNREFUSED && result != -EBADF);
450
451 LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%p\n",
452 (void*)pthread_self(), getpid(), (void*)result);
453
454 mOut.writeInt32(BC_EXIT_LOOPER);
455 talkWithDriver(false);
456}
457
458void IPCThreadState::stopProcess(bool immediate)
459{
460 //LOGI("**** STOPPING PROCESS");
461 flushCommands();
462 int fd = mProcess->mDriverFD;
463 mProcess->mDriverFD = -1;
464 close(fd);
465 //kill(getpid(), SIGKILL);
466}
467
468status_t IPCThreadState::transact(int32_t handle,
469 uint32_t code, const Parcel& data,
470 Parcel* reply, uint32_t flags)
471{
472 status_t err = data.errorCheck();
473
474 flags |= TF_ACCEPT_FDS;
475
476 IF_LOG_TRANSACTIONS() {
477 TextOutput::Bundle _b(alog);
478 alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
479 << handle << " / code " << TypeCode(code) << ": "
480 << indent << data << dedent << endl;
481 }
482
483 if (err == NO_ERROR) {
484 LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
485 (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
486 err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);
487 }
488
489 if (err != NO_ERROR) {
490 if (reply) reply->setError(err);
491 return (mLastError = err);
492 }
493
494 if ((flags & TF_ONE_WAY) == 0) {
495 if (reply) {
496 err = waitForResponse(reply);
497 } else {
498 Parcel fakeReply;
499 err = waitForResponse(&fakeReply);
500 }
501
502 IF_LOG_TRANSACTIONS() {
503 TextOutput::Bundle _b(alog);
504 alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
505 << handle << ": ";
506 if (reply) alog << indent << *reply << dedent << endl;
507 else alog << "(none requested)" << endl;
508 }
509 } else {
510 err = waitForResponse(NULL, NULL);
511 }
512
513 return err;
514}
515
516void IPCThreadState::incStrongHandle(int32_t handle)
517{
518 LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
519 mOut.writeInt32(BC_ACQUIRE);
520 mOut.writeInt32(handle);
521}
522
523void IPCThreadState::decStrongHandle(int32_t handle)
524{
525 LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
526 mOut.writeInt32(BC_RELEASE);
527 mOut.writeInt32(handle);
528}
529
530void IPCThreadState::incWeakHandle(int32_t handle)
531{
532 LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
533 mOut.writeInt32(BC_INCREFS);
534 mOut.writeInt32(handle);
535}
536
537void IPCThreadState::decWeakHandle(int32_t handle)
538{
539 LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
540 mOut.writeInt32(BC_DECREFS);
541 mOut.writeInt32(handle);
542}
543
544status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
545{
546 mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
547 mOut.writeInt32(0); // xxx was thread priority
548 mOut.writeInt32(handle);
549 status_t result = UNKNOWN_ERROR;
550
551 waitForResponse(NULL, &result);
552
553#if LOG_REFCOUNTS
554 printf("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
555 handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
556#endif
557
558 return result;
559}
560
561void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
562{
563#if LOG_REFCOUNTS
564 printf("IPCThreadState::expungeHandle(%ld)\n", handle);
565#endif
566 self()->mProcess->expungeHandle(handle, binder);
567}
568
569status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
570{
571 mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
572 mOut.writeInt32((int32_t)handle);
573 mOut.writeInt32((int32_t)proxy);
574 return NO_ERROR;
575}
576
577status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
578{
579 mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
580 mOut.writeInt32((int32_t)handle);
581 mOut.writeInt32((int32_t)proxy);
582 return NO_ERROR;
583}
584
585IPCThreadState::IPCThreadState()
586 : mProcess(ProcessState::self())
587{
588 pthread_setspecific(gTLS, this);
589 clearCaller();
590 mIn.setDataCapacity(256);
591 mOut.setDataCapacity(256);
592}
593
594IPCThreadState::~IPCThreadState()
595{
596}
597
598status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
599{
600 status_t err;
601 status_t statusBuffer;
602 err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
603 if (err < NO_ERROR) return err;
604
605 return waitForResponse(NULL, NULL);
606}
607
608status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
609{
610 int32_t cmd;
611 int32_t err;
612
613 while (1) {
614 if ((err=talkWithDriver()) < NO_ERROR) break;
615 err = mIn.errorCheck();
616 if (err < NO_ERROR) break;
617 if (mIn.dataAvail() == 0) continue;
618
619 cmd = mIn.readInt32();
620
621 IF_LOG_COMMANDS() {
622 alog << "Processing waitForResponse Command: "
623 << getReturnString(cmd) << endl;
624 }
625
626 switch (cmd) {
627 case BR_TRANSACTION_COMPLETE:
628 if (!reply && !acquireResult) goto finish;
629 break;
630
631 case BR_DEAD_REPLY:
632 err = DEAD_OBJECT;
633 goto finish;
634
635 case BR_FAILED_REPLY:
636 err = FAILED_TRANSACTION;
637 goto finish;
638
639 case BR_ACQUIRE_RESULT:
640 {
641 LOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
642 const int32_t result = mIn.readInt32();
643 if (!acquireResult) continue;
644 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
645 }
646 goto finish;
647
648 case BR_REPLY:
649 {
650 binder_transaction_data tr;
651 err = mIn.read(&tr, sizeof(tr));
652 LOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
653 if (err != NO_ERROR) goto finish;
654
655 if (reply) {
656 if ((tr.flags & TF_STATUS_CODE) == 0) {
657 reply->ipcSetDataReference(
658 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
659 tr.data_size,
660 reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
661 tr.offsets_size/sizeof(size_t),
662 freeBuffer, this);
663 } else {
664 err = *static_cast<const status_t*>(tr.data.ptr.buffer);
665 freeBuffer(NULL,
666 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
667 tr.data_size,
668 reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
669 tr.offsets_size/sizeof(size_t), this);
670 }
671 } else {
672 freeBuffer(NULL,
673 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
674 tr.data_size,
675 reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
676 tr.offsets_size/sizeof(size_t), this);
677 continue;
678 }
679 }
680 goto finish;
681
682 default:
683 err = executeCommand(cmd);
684 if (err != NO_ERROR) goto finish;
685 break;
686 }
687 }
688
689finish:
690 if (err != NO_ERROR) {
691 if (acquireResult) *acquireResult = err;
692 if (reply) reply->setError(err);
693 mLastError = err;
694 }
695
696 return err;
697}
698
699status_t IPCThreadState::talkWithDriver(bool doReceive)
700{
701 LOG_ASSERT(mProcess->mDriverFD >= 0, "Binder driver is not opened");
702
703 binder_write_read bwr;
704
705 // Is the read buffer empty?
706 const bool needRead = mIn.dataPosition() >= mIn.dataSize();
707
708 // We don't want to write anything if we are still reading
709 // from data left in the input buffer and the caller
710 // has requested to read the next data.
711 const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
712
713 bwr.write_size = outAvail;
714 bwr.write_buffer = (long unsigned int)mOut.data();
715
716 // This is what we'll read.
717 if (doReceive && needRead) {
718 bwr.read_size = mIn.dataCapacity();
719 bwr.read_buffer = (long unsigned int)mIn.data();
720 } else {
721 bwr.read_size = 0;
722 }
723
724 IF_LOG_COMMANDS() {
725 TextOutput::Bundle _b(alog);
726 if (outAvail != 0) {
727 alog << "Sending commands to driver: " << indent;
728 const void* cmds = (const void*)bwr.write_buffer;
729 const void* end = ((const uint8_t*)cmds)+bwr.write_size;
730 alog << HexDump(cmds, bwr.write_size) << endl;
731 while (cmds < end) cmds = printCommand(alog, cmds);
732 alog << dedent;
733 }
734 alog << "Size of receive buffer: " << bwr.read_size
735 << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
736 }
737
738 // Return immediately if there is nothing to do.
739 if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
740
741 bwr.write_consumed = 0;
742 bwr.read_consumed = 0;
743 status_t err;
744 do {
745 IF_LOG_COMMANDS() {
746 alog << "About to read/write, write size = " << mOut.dataSize() << endl;
747 }
748#if defined(HAVE_ANDROID_OS)
749 if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
750 err = NO_ERROR;
751 else
752 err = -errno;
753#else
754 err = INVALID_OPERATION;
755#endif
756 IF_LOG_COMMANDS() {
757 alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
758 }
759 } while (err == -EINTR);
760
761 IF_LOG_COMMANDS() {
762 alog << "Our err: " << (void*)err << ", write consumed: "
763 << bwr.write_consumed << " (of " << mOut.dataSize()
764 << "), read consumed: " << bwr.read_consumed << endl;
765 }
766
767 if (err >= NO_ERROR) {
768 if (bwr.write_consumed > 0) {
769 if (bwr.write_consumed < (ssize_t)mOut.dataSize())
770 mOut.remove(0, bwr.write_consumed);
771 else
772 mOut.setDataSize(0);
773 }
774 if (bwr.read_consumed > 0) {
775 mIn.setDataSize(bwr.read_consumed);
776 mIn.setDataPosition(0);
777 }
778 IF_LOG_COMMANDS() {
779 TextOutput::Bundle _b(alog);
780 alog << "Remaining data size: " << mOut.dataSize() << endl;
781 alog << "Received commands from driver: " << indent;
782 const void* cmds = mIn.data();
783 const void* end = mIn.data() + mIn.dataSize();
784 alog << HexDump(cmds, mIn.dataSize()) << endl;
785 while (cmds < end) cmds = printReturnCommand(alog, cmds);
786 alog << dedent;
787 }
788 return NO_ERROR;
789 }
790
791 return err;
792}
793
794status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
795 int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
796{
797 binder_transaction_data tr;
798
799 tr.target.handle = handle;
800 tr.code = code;
801 tr.flags = binderFlags;
802
803 const status_t err = data.errorCheck();
804 if (err == NO_ERROR) {
805 tr.data_size = data.ipcDataSize();
806 tr.data.ptr.buffer = data.ipcData();
807 tr.offsets_size = data.ipcObjectsCount()*sizeof(size_t);
808 tr.data.ptr.offsets = data.ipcObjects();
809 } else if (statusBuffer) {
810 tr.flags |= TF_STATUS_CODE;
811 *statusBuffer = err;
812 tr.data_size = sizeof(status_t);
813 tr.data.ptr.buffer = statusBuffer;
814 tr.offsets_size = 0;
815 tr.data.ptr.offsets = NULL;
816 } else {
817 return (mLastError = err);
818 }
819
820 mOut.writeInt32(cmd);
821 mOut.write(&tr, sizeof(tr));
822
823 return NO_ERROR;
824}
825
826sp<BBinder> the_context_object;
827
828void setTheContextObject(sp<BBinder> obj)
829{
830 the_context_object = obj;
831}
832
833status_t IPCThreadState::executeCommand(int32_t cmd)
834{
835 BBinder* obj;
836 RefBase::weakref_type* refs;
837 status_t result = NO_ERROR;
838
839 switch (cmd) {
840 case BR_ERROR:
841 result = mIn.readInt32();
842 break;
843
844 case BR_OK:
845 break;
846
847 case BR_ACQUIRE:
848 refs = (RefBase::weakref_type*)mIn.readInt32();
849 obj = (BBinder*)mIn.readInt32();
850 LOG_ASSERT(refs->refBase() == obj,
851 "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
852 refs, obj, refs->refBase());
853 obj->incStrong(mProcess.get());
854 IF_LOG_REMOTEREFS() {
855 LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
856 obj->printRefs();
857 }
858 mOut.writeInt32(BC_ACQUIRE_DONE);
859 mOut.writeInt32((int32_t)refs);
860 mOut.writeInt32((int32_t)obj);
861 break;
862
863 case BR_RELEASE:
864 refs = (RefBase::weakref_type*)mIn.readInt32();
865 obj = (BBinder*)mIn.readInt32();
866 LOG_ASSERT(refs->refBase() == obj,
867 "BR_RELEASE: object %p does not match cookie %p (expected %p)",
868 refs, obj, refs->refBase());
869 IF_LOG_REMOTEREFS() {
870 LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
871 obj->printRefs();
872 }
873 mPendingStrongDerefs.push(obj);
874 break;
875
876 case BR_INCREFS:
877 refs = (RefBase::weakref_type*)mIn.readInt32();
878 obj = (BBinder*)mIn.readInt32();
879 refs->incWeak(mProcess.get());
880 mOut.writeInt32(BC_INCREFS_DONE);
881 mOut.writeInt32((int32_t)refs);
882 mOut.writeInt32((int32_t)obj);
883 break;
884
885 case BR_DECREFS:
886 refs = (RefBase::weakref_type*)mIn.readInt32();
887 obj = (BBinder*)mIn.readInt32();
888 // NOTE: This assertion is not valid, because the object may no
889 // longer exist (thus the (BBinder*)cast above resulting in a different
890 // memory address).
891 //LOG_ASSERT(refs->refBase() == obj,
892 // "BR_DECREFS: object %p does not match cookie %p (expected %p)",
893 // refs, obj, refs->refBase());
894 mPendingWeakDerefs.push(refs);
895 break;
896
897 case BR_ATTEMPT_ACQUIRE:
898 refs = (RefBase::weakref_type*)mIn.readInt32();
899 obj = (BBinder*)mIn.readInt32();
900
901 {
902 const bool success = refs->attemptIncStrong(mProcess.get());
903 LOG_ASSERT(success && refs->refBase() == obj,
904 "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
905 refs, obj, refs->refBase());
906
907 mOut.writeInt32(BC_ACQUIRE_RESULT);
908 mOut.writeInt32((int32_t)success);
909 }
910 break;
911
912 case BR_TRANSACTION:
913 {
914 binder_transaction_data tr;
915 result = mIn.read(&tr, sizeof(tr));
916 LOG_ASSERT(result == NO_ERROR,
917 "Not enough command data for brTRANSACTION");
918 if (result != NO_ERROR) break;
919
920 Parcel buffer;
921 buffer.ipcSetDataReference(
922 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
923 tr.data_size,
924 reinterpret_cast<const size_t*>(tr.data.ptr.offsets),
925 tr.offsets_size/sizeof(size_t), freeBuffer, this);
926
927 const pid_t origPid = mCallingPid;
928 const uid_t origUid = mCallingUid;
929
930 mCallingPid = tr.sender_pid;
931 mCallingUid = tr.sender_euid;
932
933 //LOGI(">>>> TRANSACT from pid %d uid %d\n", mCallingPid, mCallingUid);
934
935 Parcel reply;
936 IF_LOG_TRANSACTIONS() {
937 TextOutput::Bundle _b(alog);
938 alog << "BR_TRANSACTION thr " << (void*)pthread_self()
939 << " / obj " << tr.target.ptr << " / code "
940 << TypeCode(tr.code) << ": " << indent << buffer
941 << dedent << endl
942 << "Data addr = "
943 << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
944 << ", offsets addr="
945 << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
946 }
947 if (tr.target.ptr) {
948 sp<BBinder> b((BBinder*)tr.cookie);
949 const status_t error = b->transact(tr.code, buffer, &reply, 0);
950 if (error < NO_ERROR) reply.setError(error);
951
952 } else {
953 const status_t error = the_context_object->transact(tr.code, buffer, &reply, 0);
954 if (error < NO_ERROR) reply.setError(error);
955 }
956
957 //LOGI("<<<< TRANSACT from pid %d restore pid %d uid %d\n",
958 // mCallingPid, origPid, origUid);
959
960 if ((tr.flags & TF_ONE_WAY) == 0) {
961 LOG_ONEWAY("Sending reply to %d!", mCallingPid);
962 sendReply(reply, 0);
963 } else {
964 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
965 }
966
967 mCallingPid = origPid;
968 mCallingUid = origUid;
969
970 IF_LOG_TRANSACTIONS() {
971 TextOutput::Bundle _b(alog);
972 alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
973 << tr.target.ptr << ": " << indent << reply << dedent << endl;
974 }
975
976 }
977 break;
978
979 case BR_DEAD_BINDER:
980 {
981 BpBinder *proxy = (BpBinder*)mIn.readInt32();
982 proxy->sendObituary();
983 mOut.writeInt32(BC_DEAD_BINDER_DONE);
984 mOut.writeInt32((int32_t)proxy);
985 } break;
986
987 case BR_CLEAR_DEATH_NOTIFICATION_DONE:
988 {
989 BpBinder *proxy = (BpBinder*)mIn.readInt32();
990 proxy->getWeakRefs()->decWeak(proxy);
991 } break;
992
993 case BR_FINISHED:
994 result = TIMED_OUT;
995 break;
996
997 case BR_NOOP:
998 break;
999
1000 case BR_SPAWN_LOOPER:
1001 mProcess->spawnPooledThread(false);
1002 break;
1003
1004 default:
1005 printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
1006 result = UNKNOWN_ERROR;
1007 break;
1008 }
1009
1010 if (result != NO_ERROR) {
1011 mLastError = result;
1012 }
1013
1014 return result;
1015}
1016
1017void IPCThreadState::threadDestructor(void *st)
1018{
1019 IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1020 if (self) {
1021 self->flushCommands();
1022#if defined(HAVE_ANDROID_OS)
1023 ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1024#endif
1025 delete self;
1026 }
1027}
1028
1029
1030void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data, size_t dataSize,
1031 const size_t* objects, size_t objectsSize,
1032 void* cookie)
1033{
1034 //LOGI("Freeing parcel %p", &parcel);
1035 IF_LOG_COMMANDS() {
1036 alog << "Writing BC_FREE_BUFFER for " << data << endl;
1037 }
1038 LOG_ASSERT(data != NULL, "Called with NULL data");
1039 if (parcel != NULL) parcel->closeFileDescriptors();
1040 IPCThreadState* state = self();
1041 state->mOut.writeInt32(BC_FREE_BUFFER);
1042 state->mOut.writeInt32((int32_t)data);
1043}
1044
1045}; // namespace android