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