blob: 1cbcfe4de5ffcb114cbdce6a70386d29a7679393 [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>
Mathias Agopian4ea13dc2013-05-06 20:20:50 -070023#include <binder/TextOutput.h>
24
Glenn Kastencb5e2422012-03-16 07:15:23 -070025#include <cutils/sched_policy.h>
Mathias Agopian7922fa22009-05-18 15:08:03 -070026#include <utils/Log.h>
Mathias Agopian7922fa22009-05-18 15:08:03 -070027#include <utils/threads.h>
28
29#include <private/binder/binder_module.h>
30#include <private/binder/Static.h>
31
Mathias Agopian7922fa22009-05-18 15:08:03 -070032#include <errno.h>
Mathias Agopian7922fa22009-05-18 15:08:03 -070033#include <pthread.h>
34#include <sched.h>
Yabin Cuibbef2ba2015-01-26 19:45:47 -080035#include <signal.h>
36#include <stdio.h>
37#include <sys/ioctl.h>
Mathias Agopian7922fa22009-05-18 15:08:03 -070038#include <sys/resource.h>
Yabin Cuibbef2ba2015-01-26 19:45:47 -080039#include <unistd.h>
Mathias Agopian7922fa22009-05-18 15:08:03 -070040
41#if LOG_NDEBUG
42
43#define IF_LOG_TRANSACTIONS() if (false)
44#define IF_LOG_COMMANDS() if (false)
45#define LOG_REMOTEREFS(...)
46#define IF_LOG_REMOTEREFS() if (false)
47#define LOG_THREADPOOL(...)
48#define LOG_ONEWAY(...)
49
50#else
51
Steve Block5854b912011-10-12 17:27:03 +010052#define IF_LOG_TRANSACTIONS() IF_ALOG(LOG_VERBOSE, "transact")
53#define IF_LOG_COMMANDS() IF_ALOG(LOG_VERBOSE, "ipc")
54#define LOG_REMOTEREFS(...) ALOG(LOG_DEBUG, "remoterefs", __VA_ARGS__)
55#define IF_LOG_REMOTEREFS() IF_ALOG(LOG_DEBUG, "remoterefs")
56#define LOG_THREADPOOL(...) ALOG(LOG_DEBUG, "threadpool", __VA_ARGS__)
57#define LOG_ONEWAY(...) ALOG(LOG_DEBUG, "ipc", __VA_ARGS__)
Mathias Agopian7922fa22009-05-18 15:08:03 -070058
59#endif
60
61// ---------------------------------------------------------------------------
62
63namespace android {
64
65static const char* getReturnString(size_t idx);
Mathias Agopian7922fa22009-05-18 15:08:03 -070066static const void* printReturnCommand(TextOutput& out, const void* _cmd);
67static const void* printCommand(TextOutput& out, const void* _cmd);
68
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -070069// Static const and functions will be optimized out if not used,
70// when LOG_NDEBUG and references in IF_LOG_COMMANDS() are optimized out.
Mathias Agopian7922fa22009-05-18 15:08:03 -070071static const char *kReturnStrings[] = {
Andy McFadden457d51f2011-08-31 07:43:40 -070072 "BR_ERROR",
Mathias Agopian7922fa22009-05-18 15:08:03 -070073 "BR_OK",
Mathias Agopian7922fa22009-05-18 15:08:03 -070074 "BR_TRANSACTION",
75 "BR_REPLY",
76 "BR_ACQUIRE_RESULT",
77 "BR_DEAD_REPLY",
78 "BR_TRANSACTION_COMPLETE",
79 "BR_INCREFS",
80 "BR_ACQUIRE",
81 "BR_RELEASE",
82 "BR_DECREFS",
83 "BR_ATTEMPT_ACQUIRE",
Mathias Agopian7922fa22009-05-18 15:08:03 -070084 "BR_NOOP",
85 "BR_SPAWN_LOOPER",
86 "BR_FINISHED",
87 "BR_DEAD_BINDER",
Andy McFadden457d51f2011-08-31 07:43:40 -070088 "BR_CLEAR_DEATH_NOTIFICATION_DONE",
89 "BR_FAILED_REPLY"
Mathias Agopian7922fa22009-05-18 15:08:03 -070090};
91
92static const char *kCommandStrings[] = {
Mathias Agopian7922fa22009-05-18 15:08:03 -070093 "BC_TRANSACTION",
94 "BC_REPLY",
95 "BC_ACQUIRE_RESULT",
96 "BC_FREE_BUFFER",
Mathias Agopian7922fa22009-05-18 15:08:03 -070097 "BC_INCREFS",
98 "BC_ACQUIRE",
99 "BC_RELEASE",
100 "BC_DECREFS",
101 "BC_INCREFS_DONE",
102 "BC_ACQUIRE_DONE",
103 "BC_ATTEMPT_ACQUIRE",
Mathias Agopian7922fa22009-05-18 15:08:03 -0700104 "BC_REGISTER_LOOPER",
105 "BC_ENTER_LOOPER",
106 "BC_EXIT_LOOPER",
Mathias Agopian7922fa22009-05-18 15:08:03 -0700107 "BC_REQUEST_DEATH_NOTIFICATION",
108 "BC_CLEAR_DEATH_NOTIFICATION",
109 "BC_DEAD_BINDER_DONE"
Mathias Agopian7922fa22009-05-18 15:08:03 -0700110};
111
112static const char* getReturnString(size_t idx)
113{
114 if (idx < sizeof(kReturnStrings) / sizeof(kReturnStrings[0]))
115 return kReturnStrings[idx];
116 else
117 return "unknown";
118}
119
Mathias Agopian7922fa22009-05-18 15:08:03 -0700120static const void* printBinderTransactionData(TextOutput& out, const void* data)
121{
122 const binder_transaction_data* btd =
123 (const binder_transaction_data*)data;
Andy McFadden457d51f2011-08-31 07:43:40 -0700124 if (btd->target.handle < 1024) {
125 /* want to print descriptors in decimal; guess based on value */
126 out << "target.desc=" << btd->target.handle;
127 } else {
128 out << "target.ptr=" << btd->target.ptr;
129 }
130 out << " (cookie " << btd->cookie << ")" << endl
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700131 << "code=" << TypeCode(btd->code) << ", flags=" << (void*)(long)btd->flags << endl
Mathias Agopian7922fa22009-05-18 15:08:03 -0700132 << "data=" << btd->data.ptr.buffer << " (" << (void*)btd->data_size
133 << " bytes)" << endl
134 << "offsets=" << btd->data.ptr.offsets << " (" << (void*)btd->offsets_size
Andy McFadden457d51f2011-08-31 07:43:40 -0700135 << " bytes)";
Mathias Agopian7922fa22009-05-18 15:08:03 -0700136 return btd+1;
137}
138
139static const void* printReturnCommand(TextOutput& out, const void* _cmd)
140{
Andy McFadden457d51f2011-08-31 07:43:40 -0700141 static const size_t N = sizeof(kReturnStrings)/sizeof(kReturnStrings[0]);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700142 const int32_t* cmd = (const int32_t*)_cmd;
Bernhard Rosenkränzerb184ed02014-11-25 21:55:33 +0100143 uint32_t code = (uint32_t)*cmd++;
Andy McFadden457d51f2011-08-31 07:43:40 -0700144 size_t cmdIndex = code & 0xff;
Bernhard Rosenkränzerb184ed02014-11-25 21:55:33 +0100145 if (code == BR_ERROR) {
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700146 out << "BR_ERROR: " << (void*)(long)(*cmd++) << endl;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700147 return cmd;
Andy McFadden457d51f2011-08-31 07:43:40 -0700148 } else if (cmdIndex >= N) {
Mathias Agopian7922fa22009-05-18 15:08:03 -0700149 out << "Unknown reply: " << code << endl;
150 return cmd;
151 }
Andy McFadden457d51f2011-08-31 07:43:40 -0700152 out << kReturnStrings[cmdIndex];
Mathias Agopian7922fa22009-05-18 15:08:03 -0700153
Mathias Agopian7922fa22009-05-18 15:08:03 -0700154 switch (code) {
155 case BR_TRANSACTION:
156 case BR_REPLY: {
157 out << ": " << indent;
158 cmd = (const int32_t *)printBinderTransactionData(out, cmd);
159 out << dedent;
160 } break;
161
162 case BR_ACQUIRE_RESULT: {
163 const int32_t res = *cmd++;
164 out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
165 } break;
166
167 case BR_INCREFS:
168 case BR_ACQUIRE:
169 case BR_RELEASE:
170 case BR_DECREFS: {
171 const int32_t b = *cmd++;
172 const int32_t c = *cmd++;
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700173 out << ": target=" << (void*)(long)b << " (cookie " << (void*)(long)c << ")";
Mathias Agopian7922fa22009-05-18 15:08:03 -0700174 } break;
175
176 case BR_ATTEMPT_ACQUIRE: {
177 const int32_t p = *cmd++;
178 const int32_t b = *cmd++;
179 const int32_t c = *cmd++;
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700180 out << ": target=" << (void*)(long)b << " (cookie " << (void*)(long)c
Mathias Agopian7922fa22009-05-18 15:08:03 -0700181 << "), pri=" << p;
182 } break;
183
184 case BR_DEAD_BINDER:
185 case BR_CLEAR_DEATH_NOTIFICATION_DONE: {
186 const int32_t c = *cmd++;
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700187 out << ": death cookie " << (void*)(long)c;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700188 } break;
Andy McFadden457d51f2011-08-31 07:43:40 -0700189
190 default:
191 // no details to show for: BR_OK, BR_DEAD_REPLY,
192 // BR_TRANSACTION_COMPLETE, BR_FINISHED
193 break;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700194 }
195
196 out << endl;
197 return cmd;
198}
199
200static const void* printCommand(TextOutput& out, const void* _cmd)
201{
Andy McFadden457d51f2011-08-31 07:43:40 -0700202 static const size_t N = sizeof(kCommandStrings)/sizeof(kCommandStrings[0]);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700203 const int32_t* cmd = (const int32_t*)_cmd;
Bernhard Rosenkränzerb184ed02014-11-25 21:55:33 +0100204 uint32_t code = (uint32_t)*cmd++;
Andy McFadden457d51f2011-08-31 07:43:40 -0700205 size_t cmdIndex = code & 0xff;
206
207 if (cmdIndex >= N) {
Mathias Agopian7922fa22009-05-18 15:08:03 -0700208 out << "Unknown command: " << code << endl;
209 return cmd;
210 }
Andy McFadden457d51f2011-08-31 07:43:40 -0700211 out << kCommandStrings[cmdIndex];
212
Mathias Agopian7922fa22009-05-18 15:08:03 -0700213 switch (code) {
214 case BC_TRANSACTION:
215 case BC_REPLY: {
216 out << ": " << indent;
217 cmd = (const int32_t *)printBinderTransactionData(out, cmd);
218 out << dedent;
219 } break;
220
221 case BC_ACQUIRE_RESULT: {
222 const int32_t res = *cmd++;
223 out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
224 } break;
225
226 case BC_FREE_BUFFER: {
227 const int32_t buf = *cmd++;
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700228 out << ": buffer=" << (void*)(long)buf;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700229 } break;
230
231 case BC_INCREFS:
232 case BC_ACQUIRE:
233 case BC_RELEASE:
234 case BC_DECREFS: {
235 const int32_t d = *cmd++;
Andy McFadden457d51f2011-08-31 07:43:40 -0700236 out << ": desc=" << d;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700237 } break;
238
239 case BC_INCREFS_DONE:
240 case BC_ACQUIRE_DONE: {
241 const int32_t b = *cmd++;
242 const int32_t c = *cmd++;
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700243 out << ": target=" << (void*)(long)b << " (cookie " << (void*)(long)c << ")";
Mathias Agopian7922fa22009-05-18 15:08:03 -0700244 } break;
245
246 case BC_ATTEMPT_ACQUIRE: {
247 const int32_t p = *cmd++;
248 const int32_t d = *cmd++;
Andy McFadden457d51f2011-08-31 07:43:40 -0700249 out << ": desc=" << d << ", pri=" << p;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700250 } break;
251
252 case BC_REQUEST_DEATH_NOTIFICATION:
253 case BC_CLEAR_DEATH_NOTIFICATION: {
254 const int32_t h = *cmd++;
255 const int32_t c = *cmd++;
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700256 out << ": handle=" << h << " (death cookie " << (void*)(long)c << ")";
Mathias Agopian7922fa22009-05-18 15:08:03 -0700257 } break;
258
259 case BC_DEAD_BINDER_DONE: {
260 const int32_t c = *cmd++;
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700261 out << ": death cookie " << (void*)(long)c;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700262 } break;
Andy McFadden457d51f2011-08-31 07:43:40 -0700263
264 default:
265 // no details to show for: BC_REGISTER_LOOPER, BC_ENTER_LOOPER,
266 // BC_EXIT_LOOPER
267 break;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700268 }
269
270 out << endl;
271 return cmd;
272}
Mathias Agopian7922fa22009-05-18 15:08:03 -0700273
274static pthread_mutex_t gTLSMutex = PTHREAD_MUTEX_INITIALIZER;
275static bool gHaveTLS = false;
276static pthread_key_t gTLS = 0;
277static bool gShutdown = false;
Dianne Hackborn5f4d7e82009-12-07 17:59:37 -0800278static bool gDisableBackgroundScheduling = false;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700279
280IPCThreadState* IPCThreadState::self()
281{
282 if (gHaveTLS) {
283restart:
284 const pthread_key_t k = gTLS;
285 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
286 if (st) return st;
287 return new IPCThreadState;
288 }
289
Andreas Gampe1d5dc2b2016-02-01 13:21:56 -0800290 if (gShutdown) {
291 ALOGW("Calling IPCThreadState::self() during shutdown is dangerous, expect a crash.\n");
292 return NULL;
293 }
Mathias Agopian7922fa22009-05-18 15:08:03 -0700294
295 pthread_mutex_lock(&gTLSMutex);
296 if (!gHaveTLS) {
Andreas Gampe1d5dc2b2016-02-01 13:21:56 -0800297 int key_create_value = pthread_key_create(&gTLS, threadDestructor);
298 if (key_create_value != 0) {
Mathias Agopian7922fa22009-05-18 15:08:03 -0700299 pthread_mutex_unlock(&gTLSMutex);
Andreas Gampe1d5dc2b2016-02-01 13:21:56 -0800300 ALOGW("IPCThreadState::self() unable to create TLS key, expect a crash: %s\n",
301 strerror(key_create_value));
Mathias Agopian7922fa22009-05-18 15:08:03 -0700302 return NULL;
303 }
304 gHaveTLS = true;
305 }
306 pthread_mutex_unlock(&gTLSMutex);
307 goto restart;
308}
309
Brad Fitzpatrick77949942010-12-13 16:52:35 -0800310IPCThreadState* IPCThreadState::selfOrNull()
311{
312 if (gHaveTLS) {
313 const pthread_key_t k = gTLS;
314 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
315 return st;
316 }
317 return NULL;
318}
319
Mathias Agopian7922fa22009-05-18 15:08:03 -0700320void 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
Dianne Hackborn5f4d7e82009-12-07 17:59:37 -0800335void IPCThreadState::disableBackgroundScheduling(bool disable)
336{
337 gDisableBackgroundScheduling = disable;
338}
339
Mathias Agopian7922fa22009-05-18 15:08:03 -0700340sp<ProcessState> IPCThreadState::process()
341{
342 return mProcess;
343}
344
345status_t IPCThreadState::clearLastError()
346{
347 const status_t err = mLastError;
348 mLastError = NO_ERROR;
349 return err;
350}
351
Dan Stozae8da8a42014-11-26 12:23:23 -0800352pid_t IPCThreadState::getCallingPid() const
Mathias Agopian7922fa22009-05-18 15:08:03 -0700353{
354 return mCallingPid;
355}
356
Dan Stozae8da8a42014-11-26 12:23:23 -0800357uid_t IPCThreadState::getCallingUid() const
Mathias Agopian7922fa22009-05-18 15:08:03 -0700358{
359 return mCallingUid;
360}
361
362int64_t IPCThreadState::clearCallingIdentity()
363{
364 int64_t token = ((int64_t)mCallingUid<<32) | mCallingPid;
365 clearCaller();
366 return token;
367}
368
Brad Fitzpatrick94c36342010-06-18 13:07:53 -0700369void IPCThreadState::setStrictModePolicy(int32_t policy)
370{
371 mStrictModePolicy = policy;
372}
373
Brad Fitzpatrick3f4ef592010-07-07 16:06:39 -0700374int32_t IPCThreadState::getStrictModePolicy() const
375{
Brad Fitzpatrick94c36342010-06-18 13:07:53 -0700376 return mStrictModePolicy;
377}
378
Brad Fitzpatrick24f8bca2010-08-30 16:01:16 -0700379void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
380{
381 mLastTransactionBinderFlags = flags;
382}
383
384int32_t IPCThreadState::getLastTransactionBinderFlags() const
385{
386 return mLastTransactionBinderFlags;
387}
388
Mathias Agopian7922fa22009-05-18 15:08:03 -0700389void IPCThreadState::restoreCallingIdentity(int64_t token)
390{
391 mCallingUid = (int)(token>>32);
392 mCallingPid = (int)token;
393}
394
395void IPCThreadState::clearCaller()
396{
Marco Nelissenb4f35d02009-07-17 07:59:17 -0700397 mCallingPid = getpid();
398 mCallingUid = getuid();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700399}
400
401void IPCThreadState::flushCommands()
402{
403 if (mProcess->mDriverFD <= 0)
404 return;
405 talkWithDriver(false);
406}
407
Wale Ogunwale2e604f02015-04-13 16:16:10 -0700408void IPCThreadState::blockUntilThreadAvailable()
409{
410 pthread_mutex_lock(&mProcess->mThreadCountLock);
411 while (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads) {
Wale Ogunwale319900a2015-04-21 12:29:50 -0700412 ALOGW("Waiting for thread to be free. mExecutingThreadsCount=%lu mMaxThreads=%lu\n",
413 static_cast<unsigned long>(mProcess->mExecutingThreadsCount),
414 static_cast<unsigned long>(mProcess->mMaxThreads));
Wale Ogunwale2e604f02015-04-13 16:16:10 -0700415 pthread_cond_wait(&mProcess->mThreadCountDecrement, &mProcess->mThreadCountLock);
416 }
417 pthread_mutex_unlock(&mProcess->mThreadCountLock);
418}
419
Todd Poynor0646cb02013-06-25 19:12:18 -0700420status_t IPCThreadState::getAndExecuteCommand()
421{
422 status_t result;
423 int32_t cmd;
424
425 result = talkWithDriver();
426 if (result >= NO_ERROR) {
427 size_t IN = mIn.dataAvail();
428 if (IN < sizeof(int32_t)) return result;
429 cmd = mIn.readInt32();
430 IF_LOG_COMMANDS() {
431 alog << "Processing top-level Command: "
432 << getReturnString(cmd) << endl;
433 }
434
Wale Ogunwale2e604f02015-04-13 16:16:10 -0700435 pthread_mutex_lock(&mProcess->mThreadCountLock);
436 mProcess->mExecutingThreadsCount++;
437 pthread_mutex_unlock(&mProcess->mThreadCountLock);
438
Todd Poynor0646cb02013-06-25 19:12:18 -0700439 result = executeCommand(cmd);
440
Wale Ogunwale2e604f02015-04-13 16:16:10 -0700441 pthread_mutex_lock(&mProcess->mThreadCountLock);
442 mProcess->mExecutingThreadsCount--;
443 pthread_cond_broadcast(&mProcess->mThreadCountDecrement);
444 pthread_mutex_unlock(&mProcess->mThreadCountLock);
445
Todd Poynor0646cb02013-06-25 19:12:18 -0700446 // After executing the command, ensure that the thread is returned to the
447 // foreground cgroup before rejoining the pool. The driver takes care of
448 // restoring the priority, but doesn't do anything with cgroups so we
449 // need to take care of that here in userspace. Note that we do make
450 // sure to go in the foreground after executing a transaction, but
451 // there are other callbacks into user code that could have changed
452 // our group so we want to make absolutely sure it is put back.
453 set_sched_policy(mMyThreadId, SP_FOREGROUND);
454 }
455
456 return result;
457}
458
459// When we've cleared the incoming command queue, process any pending derefs
460void IPCThreadState::processPendingDerefs()
461{
462 if (mIn.dataPosition() >= mIn.dataSize()) {
463 size_t numPending = mPendingWeakDerefs.size();
464 if (numPending > 0) {
465 for (size_t i = 0; i < numPending; i++) {
466 RefBase::weakref_type* refs = mPendingWeakDerefs[i];
467 refs->decWeak(mProcess.get());
468 }
469 mPendingWeakDerefs.clear();
470 }
471
472 numPending = mPendingStrongDerefs.size();
473 if (numPending > 0) {
474 for (size_t i = 0; i < numPending; i++) {
475 BBinder* obj = mPendingStrongDerefs[i];
476 obj->decStrong(mProcess.get());
477 }
478 mPendingStrongDerefs.clear();
479 }
480 }
481}
482
Mathias Agopian7922fa22009-05-18 15:08:03 -0700483void IPCThreadState::joinThreadPool(bool isMain)
484{
485 LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
486
487 mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
488
Dianne Hackborn5f4d7e82009-12-07 17:59:37 -0800489 // This thread may have been spawned by a thread that was in the background
Glenn Kastencb5e2422012-03-16 07:15:23 -0700490 // scheduling group, so first we will make sure it is in the foreground
Dianne Hackborn5f4d7e82009-12-07 17:59:37 -0800491 // one to avoid performing an initial transaction in the background.
Glenn Kastencb5e2422012-03-16 07:15:23 -0700492 set_sched_policy(mMyThreadId, SP_FOREGROUND);
Dianne Hackborn5f4d7e82009-12-07 17:59:37 -0800493
Mathias Agopian7922fa22009-05-18 15:08:03 -0700494 status_t result;
495 do {
Todd Poynor0646cb02013-06-25 19:12:18 -0700496 processPendingDerefs();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700497 // now get the next command to be processed, waiting if necessary
Todd Poynor0646cb02013-06-25 19:12:18 -0700498 result = getAndExecuteCommand();
Jason Parks2b17f142009-11-03 12:14:38 -0800499
Todd Poynor0646cb02013-06-25 19:12:18 -0700500 if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
501 ALOGE("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
Jeff Tinkeree711ec2013-06-11 11:30:21 -0700502 mProcess->mDriverFD, result);
503 abort();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700504 }
505
Mathias Agopian7922fa22009-05-18 15:08:03 -0700506 // Let this thread exit the thread pool if it is no longer
507 // needed and it is not the main process thread.
508 if(result == TIMED_OUT && !isMain) {
509 break;
510 }
511 } while (result != -ECONNREFUSED && result != -EBADF);
512
513 LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%p\n",
514 (void*)pthread_self(), getpid(), (void*)result);
515
516 mOut.writeInt32(BC_EXIT_LOOPER);
517 talkWithDriver(false);
518}
519
Todd Poynor0646cb02013-06-25 19:12:18 -0700520int IPCThreadState::setupPolling(int* fd)
521{
522 if (mProcess->mDriverFD <= 0) {
523 return -EBADF;
524 }
525
526 mOut.writeInt32(BC_ENTER_LOOPER);
527 *fd = mProcess->mDriverFD;
528 return 0;
529}
530
531status_t IPCThreadState::handlePolledCommands()
532{
533 status_t result;
534
535 do {
536 result = getAndExecuteCommand();
537 } while (mIn.dataPosition() < mIn.dataSize());
538
539 processPendingDerefs();
540 flushCommands();
541 return result;
542}
543
Colin Crossf0487982014-02-05 17:42:44 -0800544void IPCThreadState::stopProcess(bool /*immediate*/)
Mathias Agopian7922fa22009-05-18 15:08:03 -0700545{
Steve Block93cf8542012-01-04 20:05:49 +0000546 //ALOGI("**** STOPPING PROCESS");
Mathias Agopian7922fa22009-05-18 15:08:03 -0700547 flushCommands();
548 int fd = mProcess->mDriverFD;
549 mProcess->mDriverFD = -1;
550 close(fd);
551 //kill(getpid(), SIGKILL);
552}
553
554status_t IPCThreadState::transact(int32_t handle,
555 uint32_t code, const Parcel& data,
556 Parcel* reply, uint32_t flags)
557{
558 status_t err = data.errorCheck();
559
560 flags |= TF_ACCEPT_FDS;
561
562 IF_LOG_TRANSACTIONS() {
563 TextOutput::Bundle _b(alog);
564 alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
565 << handle << " / code " << TypeCode(code) << ": "
566 << indent << data << dedent << endl;
567 }
568
569 if (err == NO_ERROR) {
570 LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
571 (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
572 err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);
573 }
574
575 if (err != NO_ERROR) {
576 if (reply) reply->setError(err);
577 return (mLastError = err);
578 }
579
580 if ((flags & TF_ONE_WAY) == 0) {
Dianne Hackborn98878262010-09-24 11:16:23 -0700581 #if 0
582 if (code == 4) { // relayout
Steve Block93cf8542012-01-04 20:05:49 +0000583 ALOGI(">>>>>> CALLING transaction 4");
Dianne Hackborn98878262010-09-24 11:16:23 -0700584 } else {
Steve Block93cf8542012-01-04 20:05:49 +0000585 ALOGI(">>>>>> CALLING transaction %d", code);
Dianne Hackborn98878262010-09-24 11:16:23 -0700586 }
587 #endif
Mathias Agopian7922fa22009-05-18 15:08:03 -0700588 if (reply) {
589 err = waitForResponse(reply);
590 } else {
591 Parcel fakeReply;
592 err = waitForResponse(&fakeReply);
593 }
Dianne Hackborn98878262010-09-24 11:16:23 -0700594 #if 0
595 if (code == 4) { // relayout
Steve Block93cf8542012-01-04 20:05:49 +0000596 ALOGI("<<<<<< RETURNING transaction 4");
Dianne Hackborn98878262010-09-24 11:16:23 -0700597 } else {
Steve Block93cf8542012-01-04 20:05:49 +0000598 ALOGI("<<<<<< RETURNING transaction %d", code);
Dianne Hackborn98878262010-09-24 11:16:23 -0700599 }
600 #endif
Mathias Agopian7922fa22009-05-18 15:08:03 -0700601
602 IF_LOG_TRANSACTIONS() {
603 TextOutput::Bundle _b(alog);
604 alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
605 << handle << ": ";
606 if (reply) alog << indent << *reply << dedent << endl;
607 else alog << "(none requested)" << endl;
608 }
609 } else {
610 err = waitForResponse(NULL, NULL);
611 }
612
613 return err;
614}
615
616void IPCThreadState::incStrongHandle(int32_t handle)
617{
618 LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
619 mOut.writeInt32(BC_ACQUIRE);
620 mOut.writeInt32(handle);
621}
622
623void IPCThreadState::decStrongHandle(int32_t handle)
624{
625 LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
626 mOut.writeInt32(BC_RELEASE);
627 mOut.writeInt32(handle);
628}
629
630void IPCThreadState::incWeakHandle(int32_t handle)
631{
632 LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
633 mOut.writeInt32(BC_INCREFS);
634 mOut.writeInt32(handle);
635}
636
637void IPCThreadState::decWeakHandle(int32_t handle)
638{
639 LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
640 mOut.writeInt32(BC_DECREFS);
641 mOut.writeInt32(handle);
642}
643
644status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
645{
Arve Hjønnevåg304dcae2014-02-14 20:14:02 -0800646#if HAS_BC_ATTEMPT_ACQUIRE
Andy McFadden457d51f2011-08-31 07:43:40 -0700647 LOG_REMOTEREFS("IPCThreadState::attemptIncStrongHandle(%d)\n", handle);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700648 mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
649 mOut.writeInt32(0); // xxx was thread priority
650 mOut.writeInt32(handle);
651 status_t result = UNKNOWN_ERROR;
652
653 waitForResponse(NULL, &result);
654
655#if LOG_REFCOUNTS
656 printf("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
657 handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
658#endif
659
660 return result;
Arve Hjønnevåg304dcae2014-02-14 20:14:02 -0800661#else
662 (void)handle;
663 ALOGE("%s(%d): Not supported\n", __func__, handle);
664 return INVALID_OPERATION;
665#endif
Mathias Agopian7922fa22009-05-18 15:08:03 -0700666}
667
668void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
669{
670#if LOG_REFCOUNTS
671 printf("IPCThreadState::expungeHandle(%ld)\n", handle);
672#endif
673 self()->mProcess->expungeHandle(handle, binder);
674}
675
676status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
677{
678 mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
679 mOut.writeInt32((int32_t)handle);
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +0000680 mOut.writePointer((uintptr_t)proxy);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700681 return NO_ERROR;
682}
683
684status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
685{
686 mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
687 mOut.writeInt32((int32_t)handle);
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +0000688 mOut.writePointer((uintptr_t)proxy);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700689 return NO_ERROR;
690}
691
692IPCThreadState::IPCThreadState()
Brad Fitzpatrick24f8bca2010-08-30 16:01:16 -0700693 : mProcess(ProcessState::self()),
Elliott Hughes07cf48a2014-08-18 10:38:38 -0700694 mMyThreadId(gettid()),
Brad Fitzpatrick24f8bca2010-08-30 16:01:16 -0700695 mStrictModePolicy(0),
696 mLastTransactionBinderFlags(0)
Mathias Agopian7922fa22009-05-18 15:08:03 -0700697{
698 pthread_setspecific(gTLS, this);
Dianne Hackborn5f4d7e82009-12-07 17:59:37 -0800699 clearCaller();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700700 mIn.setDataCapacity(256);
701 mOut.setDataCapacity(256);
702}
703
704IPCThreadState::~IPCThreadState()
705{
706}
707
708status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
709{
710 status_t err;
711 status_t statusBuffer;
712 err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
713 if (err < NO_ERROR) return err;
714
715 return waitForResponse(NULL, NULL);
716}
717
718status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
719{
Bernhard Rosenkränzerb184ed02014-11-25 21:55:33 +0100720 uint32_t cmd;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700721 int32_t err;
722
723 while (1) {
724 if ((err=talkWithDriver()) < NO_ERROR) break;
725 err = mIn.errorCheck();
726 if (err < NO_ERROR) break;
727 if (mIn.dataAvail() == 0) continue;
728
Bernhard Rosenkränzerb184ed02014-11-25 21:55:33 +0100729 cmd = (uint32_t)mIn.readInt32();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700730
731 IF_LOG_COMMANDS() {
732 alog << "Processing waitForResponse Command: "
733 << getReturnString(cmd) << endl;
734 }
735
736 switch (cmd) {
737 case BR_TRANSACTION_COMPLETE:
738 if (!reply && !acquireResult) goto finish;
739 break;
740
741 case BR_DEAD_REPLY:
742 err = DEAD_OBJECT;
743 goto finish;
744
745 case BR_FAILED_REPLY:
746 err = FAILED_TRANSACTION;
747 goto finish;
748
749 case BR_ACQUIRE_RESULT:
750 {
Steve Blockd0bfabc2012-01-09 18:35:44 +0000751 ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
Mathias Agopian7922fa22009-05-18 15:08:03 -0700752 const int32_t result = mIn.readInt32();
753 if (!acquireResult) continue;
754 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
755 }
756 goto finish;
757
758 case BR_REPLY:
759 {
760 binder_transaction_data tr;
761 err = mIn.read(&tr, sizeof(tr));
Steve Blockd0bfabc2012-01-09 18:35:44 +0000762 ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
Mathias Agopian7922fa22009-05-18 15:08:03 -0700763 if (err != NO_ERROR) goto finish;
764
765 if (reply) {
766 if ((tr.flags & TF_STATUS_CODE) == 0) {
767 reply->ipcSetDataReference(
768 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
769 tr.data_size,
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800770 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
771 tr.offsets_size/sizeof(binder_size_t),
Mathias Agopian7922fa22009-05-18 15:08:03 -0700772 freeBuffer, this);
773 } else {
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800774 err = *reinterpret_cast<const status_t*>(tr.data.ptr.buffer);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700775 freeBuffer(NULL,
776 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
777 tr.data_size,
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800778 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
779 tr.offsets_size/sizeof(binder_size_t), this);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700780 }
781 } else {
782 freeBuffer(NULL,
783 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
784 tr.data_size,
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800785 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
786 tr.offsets_size/sizeof(binder_size_t), this);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700787 continue;
788 }
789 }
790 goto finish;
791
792 default:
793 err = executeCommand(cmd);
794 if (err != NO_ERROR) goto finish;
795 break;
796 }
797 }
798
799finish:
800 if (err != NO_ERROR) {
801 if (acquireResult) *acquireResult = err;
802 if (reply) reply->setError(err);
803 mLastError = err;
804 }
805
806 return err;
807}
808
809status_t IPCThreadState::talkWithDriver(bool doReceive)
810{
Johannes Carlsson597a3c72011-02-17 14:06:53 +0100811 if (mProcess->mDriverFD <= 0) {
812 return -EBADF;
813 }
Mathias Agopian7922fa22009-05-18 15:08:03 -0700814
815 binder_write_read bwr;
816
817 // Is the read buffer empty?
818 const bool needRead = mIn.dataPosition() >= mIn.dataSize();
819
820 // We don't want to write anything if we are still reading
821 // from data left in the input buffer and the caller
822 // has requested to read the next data.
823 const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
824
825 bwr.write_size = outAvail;
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800826 bwr.write_buffer = (uintptr_t)mOut.data();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700827
828 // This is what we'll read.
829 if (doReceive && needRead) {
830 bwr.read_size = mIn.dataCapacity();
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800831 bwr.read_buffer = (uintptr_t)mIn.data();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700832 } else {
833 bwr.read_size = 0;
Ben Cheng455a70a2011-12-01 17:11:32 -0800834 bwr.read_buffer = 0;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700835 }
Andy McFadden457d51f2011-08-31 07:43:40 -0700836
Mathias Agopian7922fa22009-05-18 15:08:03 -0700837 IF_LOG_COMMANDS() {
838 TextOutput::Bundle _b(alog);
839 if (outAvail != 0) {
840 alog << "Sending commands to driver: " << indent;
841 const void* cmds = (const void*)bwr.write_buffer;
842 const void* end = ((const uint8_t*)cmds)+bwr.write_size;
843 alog << HexDump(cmds, bwr.write_size) << endl;
844 while (cmds < end) cmds = printCommand(alog, cmds);
845 alog << dedent;
846 }
847 alog << "Size of receive buffer: " << bwr.read_size
848 << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
849 }
850
851 // Return immediately if there is nothing to do.
852 if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
Andy McFadden457d51f2011-08-31 07:43:40 -0700853
Mathias Agopian7922fa22009-05-18 15:08:03 -0700854 bwr.write_consumed = 0;
855 bwr.read_consumed = 0;
856 status_t err;
857 do {
858 IF_LOG_COMMANDS() {
859 alog << "About to read/write, write size = " << mOut.dataSize() << endl;
860 }
Elliott Hughese5e70552015-08-12 15:27:47 -0700861#if defined(__ANDROID__)
Mathias Agopian7922fa22009-05-18 15:08:03 -0700862 if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
863 err = NO_ERROR;
864 else
865 err = -errno;
866#else
867 err = INVALID_OPERATION;
868#endif
Johannes Carlsson597a3c72011-02-17 14:06:53 +0100869 if (mProcess->mDriverFD <= 0) {
870 err = -EBADF;
871 }
Mathias Agopian7922fa22009-05-18 15:08:03 -0700872 IF_LOG_COMMANDS() {
873 alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
874 }
875 } while (err == -EINTR);
Andy McFadden457d51f2011-08-31 07:43:40 -0700876
Mathias Agopian7922fa22009-05-18 15:08:03 -0700877 IF_LOG_COMMANDS() {
Colin Crossf0487982014-02-05 17:42:44 -0800878 alog << "Our err: " << (void*)(intptr_t)err << ", write consumed: "
Mathias Agopian7922fa22009-05-18 15:08:03 -0700879 << bwr.write_consumed << " (of " << mOut.dataSize()
Todd Poynor0646cb02013-06-25 19:12:18 -0700880 << "), read consumed: " << bwr.read_consumed << endl;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700881 }
882
883 if (err >= NO_ERROR) {
884 if (bwr.write_consumed > 0) {
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800885 if (bwr.write_consumed < mOut.dataSize())
Mathias Agopian7922fa22009-05-18 15:08:03 -0700886 mOut.remove(0, bwr.write_consumed);
887 else
888 mOut.setDataSize(0);
889 }
890 if (bwr.read_consumed > 0) {
891 mIn.setDataSize(bwr.read_consumed);
892 mIn.setDataPosition(0);
893 }
894 IF_LOG_COMMANDS() {
895 TextOutput::Bundle _b(alog);
896 alog << "Remaining data size: " << mOut.dataSize() << endl;
897 alog << "Received commands from driver: " << indent;
898 const void* cmds = mIn.data();
899 const void* end = mIn.data() + mIn.dataSize();
900 alog << HexDump(cmds, mIn.dataSize()) << endl;
901 while (cmds < end) cmds = printReturnCommand(alog, cmds);
902 alog << dedent;
903 }
904 return NO_ERROR;
905 }
906
907 return err;
908}
909
910status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
911 int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
912{
913 binder_transaction_data tr;
914
Arve Hjønnevågea8e05d2014-02-18 21:10:29 -0800915 tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
Mathias Agopian7922fa22009-05-18 15:08:03 -0700916 tr.target.handle = handle;
917 tr.code = code;
918 tr.flags = binderFlags;
Evgeniy Stepanov68c8a652011-04-21 14:15:00 +0400919 tr.cookie = 0;
920 tr.sender_pid = 0;
921 tr.sender_euid = 0;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700922
923 const status_t err = data.errorCheck();
924 if (err == NO_ERROR) {
925 tr.data_size = data.ipcDataSize();
926 tr.data.ptr.buffer = data.ipcData();
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800927 tr.offsets_size = data.ipcObjectsCount()*sizeof(binder_size_t);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700928 tr.data.ptr.offsets = data.ipcObjects();
929 } else if (statusBuffer) {
930 tr.flags |= TF_STATUS_CODE;
931 *statusBuffer = err;
932 tr.data_size = sizeof(status_t);
Arve Hjønnevåg4bdf7e92014-02-18 21:04:31 -0800933 tr.data.ptr.buffer = reinterpret_cast<uintptr_t>(statusBuffer);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700934 tr.offsets_size = 0;
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800935 tr.data.ptr.offsets = 0;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700936 } else {
937 return (mLastError = err);
938 }
939
940 mOut.writeInt32(cmd);
941 mOut.write(&tr, sizeof(tr));
942
943 return NO_ERROR;
944}
945
946sp<BBinder> the_context_object;
947
948void setTheContextObject(sp<BBinder> obj)
949{
950 the_context_object = obj;
951}
952
953status_t IPCThreadState::executeCommand(int32_t cmd)
954{
955 BBinder* obj;
956 RefBase::weakref_type* refs;
957 status_t result = NO_ERROR;
958
Bernhard Rosenkränzerb184ed02014-11-25 21:55:33 +0100959 switch ((uint32_t)cmd) {
Mathias Agopian7922fa22009-05-18 15:08:03 -0700960 case BR_ERROR:
961 result = mIn.readInt32();
962 break;
963
964 case BR_OK:
965 break;
966
967 case BR_ACQUIRE:
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +0000968 refs = (RefBase::weakref_type*)mIn.readPointer();
969 obj = (BBinder*)mIn.readPointer();
Steve Blockd0bfabc2012-01-09 18:35:44 +0000970 ALOG_ASSERT(refs->refBase() == obj,
Mathias Agopian7922fa22009-05-18 15:08:03 -0700971 "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
972 refs, obj, refs->refBase());
973 obj->incStrong(mProcess.get());
974 IF_LOG_REMOTEREFS() {
975 LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
976 obj->printRefs();
977 }
978 mOut.writeInt32(BC_ACQUIRE_DONE);
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +0000979 mOut.writePointer((uintptr_t)refs);
980 mOut.writePointer((uintptr_t)obj);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700981 break;
982
983 case BR_RELEASE:
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +0000984 refs = (RefBase::weakref_type*)mIn.readPointer();
985 obj = (BBinder*)mIn.readPointer();
Steve Blockd0bfabc2012-01-09 18:35:44 +0000986 ALOG_ASSERT(refs->refBase() == obj,
Mathias Agopian7922fa22009-05-18 15:08:03 -0700987 "BR_RELEASE: object %p does not match cookie %p (expected %p)",
988 refs, obj, refs->refBase());
989 IF_LOG_REMOTEREFS() {
990 LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
991 obj->printRefs();
992 }
993 mPendingStrongDerefs.push(obj);
994 break;
995
996 case BR_INCREFS:
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +0000997 refs = (RefBase::weakref_type*)mIn.readPointer();
998 obj = (BBinder*)mIn.readPointer();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700999 refs->incWeak(mProcess.get());
1000 mOut.writeInt32(BC_INCREFS_DONE);
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +00001001 mOut.writePointer((uintptr_t)refs);
1002 mOut.writePointer((uintptr_t)obj);
Mathias Agopian7922fa22009-05-18 15:08:03 -07001003 break;
1004
1005 case BR_DECREFS:
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +00001006 refs = (RefBase::weakref_type*)mIn.readPointer();
1007 obj = (BBinder*)mIn.readPointer();
Mathias Agopian7922fa22009-05-18 15:08:03 -07001008 // NOTE: This assertion is not valid, because the object may no
1009 // longer exist (thus the (BBinder*)cast above resulting in a different
1010 // memory address).
Steve Blockd0bfabc2012-01-09 18:35:44 +00001011 //ALOG_ASSERT(refs->refBase() == obj,
Mathias Agopian7922fa22009-05-18 15:08:03 -07001012 // "BR_DECREFS: object %p does not match cookie %p (expected %p)",
1013 // refs, obj, refs->refBase());
1014 mPendingWeakDerefs.push(refs);
1015 break;
1016
1017 case BR_ATTEMPT_ACQUIRE:
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +00001018 refs = (RefBase::weakref_type*)mIn.readPointer();
1019 obj = (BBinder*)mIn.readPointer();
Mathias Agopian7922fa22009-05-18 15:08:03 -07001020
1021 {
1022 const bool success = refs->attemptIncStrong(mProcess.get());
Steve Blockd0bfabc2012-01-09 18:35:44 +00001023 ALOG_ASSERT(success && refs->refBase() == obj,
Mathias Agopian7922fa22009-05-18 15:08:03 -07001024 "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
1025 refs, obj, refs->refBase());
1026
1027 mOut.writeInt32(BC_ACQUIRE_RESULT);
1028 mOut.writeInt32((int32_t)success);
1029 }
1030 break;
1031
1032 case BR_TRANSACTION:
1033 {
1034 binder_transaction_data tr;
1035 result = mIn.read(&tr, sizeof(tr));
Steve Blockd0bfabc2012-01-09 18:35:44 +00001036 ALOG_ASSERT(result == NO_ERROR,
Mathias Agopian7922fa22009-05-18 15:08:03 -07001037 "Not enough command data for brTRANSACTION");
1038 if (result != NO_ERROR) break;
1039
1040 Parcel buffer;
1041 buffer.ipcSetDataReference(
1042 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1043 tr.data_size,
Arve Hjønnevåga5440702014-01-28 20:12:59 -08001044 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1045 tr.offsets_size/sizeof(binder_size_t), freeBuffer, this);
Mathias Agopian7922fa22009-05-18 15:08:03 -07001046
1047 const pid_t origPid = mCallingPid;
1048 const uid_t origUid = mCallingUid;
Dianne Hackbornf99aec62014-09-30 11:30:03 -07001049 const int32_t origStrictModePolicy = mStrictModePolicy;
1050 const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
1051
Mathias Agopian7922fa22009-05-18 15:08:03 -07001052 mCallingPid = tr.sender_pid;
1053 mCallingUid = tr.sender_euid;
Dianne Hackbornf99aec62014-09-30 11:30:03 -07001054 mLastTransactionBinderFlags = tr.flags;
1055
Christopher Tate7c4dfec2010-03-18 17:55:03 -07001056 int curPrio = getpriority(PRIO_PROCESS, mMyThreadId);
1057 if (gDisableBackgroundScheduling) {
1058 if (curPrio > ANDROID_PRIORITY_NORMAL) {
1059 // We have inherited a reduced priority from the caller, but do not
1060 // want to run in that state in this process. The driver set our
1061 // priority already (though not our scheduling class), so bounce
1062 // it back to the default before invoking the transaction.
1063 setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL);
1064 }
1065 } else {
1066 if (curPrio >= ANDROID_PRIORITY_BACKGROUND) {
1067 // We want to use the inherited priority from the caller.
1068 // Ensure this thread is in the background scheduling class,
1069 // since the driver won't modify scheduling classes for us.
1070 // The scheduling group is reset to default by the caller
1071 // once this method returns after the transaction is complete.
Glenn Kastencb5e2422012-03-16 07:15:23 -07001072 set_sched_policy(mMyThreadId, SP_BACKGROUND);
Christopher Tate7c4dfec2010-03-18 17:55:03 -07001073 }
Dianne Hackborn5f4d7e82009-12-07 17:59:37 -08001074 }
Christopher Tate7c4dfec2010-03-18 17:55:03 -07001075
Steve Block93cf8542012-01-04 20:05:49 +00001076 //ALOGI(">>>> TRANSACT from pid %d uid %d\n", mCallingPid, mCallingUid);
Dianne Hackbornf99aec62014-09-30 11:30:03 -07001077
Mathias Agopian7922fa22009-05-18 15:08:03 -07001078 Parcel reply;
Dianne Hackbornf99aec62014-09-30 11:30:03 -07001079 status_t error;
Mathias Agopian7922fa22009-05-18 15:08:03 -07001080 IF_LOG_TRANSACTIONS() {
1081 TextOutput::Bundle _b(alog);
1082 alog << "BR_TRANSACTION thr " << (void*)pthread_self()
1083 << " / obj " << tr.target.ptr << " / code "
1084 << TypeCode(tr.code) << ": " << indent << buffer
1085 << dedent << endl
1086 << "Data addr = "
1087 << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1088 << ", offsets addr="
1089 << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
1090 }
1091 if (tr.target.ptr) {
Dianne Hackborn839f7072016-03-21 10:36:54 -07001092 // We only have a weak reference on the target object, so we must first try to
1093 // safely acquire a strong reference before doing anything else with it.
1094 if (reinterpret_cast<RefBase::weakref_type*>(
1095 tr.target.ptr)->attemptIncStrong(this)) {
1096 error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,
1097 &reply, tr.flags);
1098 reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);
1099 } else {
1100 error = UNKNOWN_TRANSACTION;
1101 }
Brad Fitzpatrick24f8bca2010-08-30 16:01:16 -07001102
Mathias Agopian7922fa22009-05-18 15:08:03 -07001103 } else {
Dianne Hackbornf99aec62014-09-30 11:30:03 -07001104 error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
Mathias Agopian7922fa22009-05-18 15:08:03 -07001105 }
Dianne Hackbornf99aec62014-09-30 11:30:03 -07001106
Steve Block93cf8542012-01-04 20:05:49 +00001107 //ALOGI("<<<< TRANSACT from pid %d restore pid %d uid %d\n",
Mathias Agopian7922fa22009-05-18 15:08:03 -07001108 // mCallingPid, origPid, origUid);
1109
1110 if ((tr.flags & TF_ONE_WAY) == 0) {
1111 LOG_ONEWAY("Sending reply to %d!", mCallingPid);
Dianne Hackbornf99aec62014-09-30 11:30:03 -07001112 if (error < NO_ERROR) reply.setError(error);
Mathias Agopian7922fa22009-05-18 15:08:03 -07001113 sendReply(reply, 0);
1114 } else {
1115 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1116 }
1117
1118 mCallingPid = origPid;
1119 mCallingUid = origUid;
Dianne Hackbornf99aec62014-09-30 11:30:03 -07001120 mStrictModePolicy = origStrictModePolicy;
1121 mLastTransactionBinderFlags = origTransactionBinderFlags;
Christopher Tate7c4dfec2010-03-18 17:55:03 -07001122
Mathias Agopian7922fa22009-05-18 15:08:03 -07001123 IF_LOG_TRANSACTIONS() {
1124 TextOutput::Bundle _b(alog);
1125 alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
1126 << tr.target.ptr << ": " << indent << reply << dedent << endl;
1127 }
1128
1129 }
1130 break;
1131
1132 case BR_DEAD_BINDER:
1133 {
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +00001134 BpBinder *proxy = (BpBinder*)mIn.readPointer();
Mathias Agopian7922fa22009-05-18 15:08:03 -07001135 proxy->sendObituary();
1136 mOut.writeInt32(BC_DEAD_BINDER_DONE);
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +00001137 mOut.writePointer((uintptr_t)proxy);
Mathias Agopian7922fa22009-05-18 15:08:03 -07001138 } break;
1139
1140 case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1141 {
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +00001142 BpBinder *proxy = (BpBinder*)mIn.readPointer();
Mathias Agopian7922fa22009-05-18 15:08:03 -07001143 proxy->getWeakRefs()->decWeak(proxy);
1144 } break;
1145
1146 case BR_FINISHED:
1147 result = TIMED_OUT;
1148 break;
1149
1150 case BR_NOOP:
1151 break;
1152
1153 case BR_SPAWN_LOOPER:
1154 mProcess->spawnPooledThread(false);
1155 break;
1156
1157 default:
1158 printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
1159 result = UNKNOWN_ERROR;
1160 break;
1161 }
1162
1163 if (result != NO_ERROR) {
1164 mLastError = result;
1165 }
1166
1167 return result;
1168}
1169
1170void IPCThreadState::threadDestructor(void *st)
1171{
Todd Poynor0646cb02013-06-25 19:12:18 -07001172 IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1173 if (self) {
1174 self->flushCommands();
Elliott Hughese5e70552015-08-12 15:27:47 -07001175#if defined(__ANDROID__)
Johannes Carlsson597a3c72011-02-17 14:06:53 +01001176 if (self->mProcess->mDriverFD > 0) {
1177 ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1178 }
Mathias Agopian7922fa22009-05-18 15:08:03 -07001179#endif
Todd Poynor0646cb02013-06-25 19:12:18 -07001180 delete self;
1181 }
Mathias Agopian7922fa22009-05-18 15:08:03 -07001182}
1183
1184
Colin Crossf0487982014-02-05 17:42:44 -08001185void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data,
1186 size_t /*dataSize*/,
1187 const binder_size_t* /*objects*/,
1188 size_t /*objectsSize*/, void* /*cookie*/)
Mathias Agopian7922fa22009-05-18 15:08:03 -07001189{
Steve Block93cf8542012-01-04 20:05:49 +00001190 //ALOGI("Freeing parcel %p", &parcel);
Mathias Agopian7922fa22009-05-18 15:08:03 -07001191 IF_LOG_COMMANDS() {
1192 alog << "Writing BC_FREE_BUFFER for " << data << endl;
1193 }
Steve Blockd0bfabc2012-01-09 18:35:44 +00001194 ALOG_ASSERT(data != NULL, "Called with NULL data");
Mathias Agopian7922fa22009-05-18 15:08:03 -07001195 if (parcel != NULL) parcel->closeFileDescriptors();
1196 IPCThreadState* state = self();
1197 state->mOut.writeInt32(BC_FREE_BUFFER);
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +00001198 state->mOut.writePointer((uintptr_t)data);
Mathias Agopian7922fa22009-05-18 15:08:03 -07001199}
1200
1201}; // namespace android