blob: 1437e5cdb3b20997a7cacfccd8b002e1a2d89adb [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
Martijn Coenen4080edc2016-05-04 14:17:02 +020019#include <hwbinder/IPCThreadState.h>
Mathias Agopian7922fa22009-05-18 15:08:03 -070020
Martijn Coenen4080edc2016-05-04 14:17:02 +020021#include <hwbinder/Binder.h>
22#include <hwbinder/BpBinder.h>
23#include <hwbinder/TextOutput.h>
Chia-I Wu0e72fd52016-10-06 14:20:41 +080024#include <hwbinder/binder_kernel.h>
Mathias Agopian4ea13dc2013-05-06 20:20:50 -070025
Glenn Kastencb5e2422012-03-16 07:15:23 -070026#include <cutils/sched_policy.h>
Mathias Agopian7922fa22009-05-18 15:08:03 -070027#include <utils/Log.h>
Colin Crossb1dc6542016-04-15 14:29:55 -070028#include <utils/SystemClock.h>
Mathias Agopian7922fa22009-05-18 15:08:03 -070029#include <utils/threads.h>
30
31#include <private/binder/binder_module.h>
Martijn Coenene01f4f22016-05-12 12:33:28 +020032#include <hwbinder/Static.h>
Mathias Agopian7922fa22009-05-18 15:08:03 -070033
Mathias Agopian7922fa22009-05-18 15:08:03 -070034#include <errno.h>
Colin Crossb1dc6542016-04-15 14:29:55 -070035#include <inttypes.h>
Mathias Agopian7922fa22009-05-18 15:08:03 -070036#include <pthread.h>
37#include <sched.h>
Yabin Cuibbef2ba2015-01-26 19:45:47 -080038#include <signal.h>
39#include <stdio.h>
40#include <sys/ioctl.h>
Mathias Agopian7922fa22009-05-18 15:08:03 -070041#include <sys/resource.h>
Yabin Cuibbef2ba2015-01-26 19:45:47 -080042#include <unistd.h>
Mathias Agopian7922fa22009-05-18 15:08:03 -070043
44#if LOG_NDEBUG
45
46#define IF_LOG_TRANSACTIONS() if (false)
47#define IF_LOG_COMMANDS() if (false)
48#define LOG_REMOTEREFS(...)
49#define IF_LOG_REMOTEREFS() if (false)
50#define LOG_THREADPOOL(...)
51#define LOG_ONEWAY(...)
52
53#else
54
Steve Block5854b912011-10-12 17:27:03 +010055#define IF_LOG_TRANSACTIONS() IF_ALOG(LOG_VERBOSE, "transact")
56#define IF_LOG_COMMANDS() IF_ALOG(LOG_VERBOSE, "ipc")
57#define LOG_REMOTEREFS(...) ALOG(LOG_DEBUG, "remoterefs", __VA_ARGS__)
58#define IF_LOG_REMOTEREFS() IF_ALOG(LOG_DEBUG, "remoterefs")
59#define LOG_THREADPOOL(...) ALOG(LOG_DEBUG, "threadpool", __VA_ARGS__)
60#define LOG_ONEWAY(...) ALOG(LOG_DEBUG, "ipc", __VA_ARGS__)
Mathias Agopian7922fa22009-05-18 15:08:03 -070061
62#endif
63
64// ---------------------------------------------------------------------------
65
66namespace android {
Martijn Coenenf75a23d2016-08-01 11:55:17 +020067namespace hardware {
Mathias Agopian7922fa22009-05-18 15:08:03 -070068
69static const char* getReturnString(size_t idx);
Mathias Agopian7922fa22009-05-18 15:08:03 -070070static const void* printReturnCommand(TextOutput& out, const void* _cmd);
71static const void* printCommand(TextOutput& out, const void* _cmd);
72
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -070073// Static const and functions will be optimized out if not used,
74// when LOG_NDEBUG and references in IF_LOG_COMMANDS() are optimized out.
Mathias Agopian7922fa22009-05-18 15:08:03 -070075static const char *kReturnStrings[] = {
Andy McFadden457d51f2011-08-31 07:43:40 -070076 "BR_ERROR",
Mathias Agopian7922fa22009-05-18 15:08:03 -070077 "BR_OK",
Mathias Agopian7922fa22009-05-18 15:08:03 -070078 "BR_TRANSACTION",
79 "BR_REPLY",
80 "BR_ACQUIRE_RESULT",
81 "BR_DEAD_REPLY",
82 "BR_TRANSACTION_COMPLETE",
83 "BR_INCREFS",
84 "BR_ACQUIRE",
85 "BR_RELEASE",
86 "BR_DECREFS",
87 "BR_ATTEMPT_ACQUIRE",
Mathias Agopian7922fa22009-05-18 15:08:03 -070088 "BR_NOOP",
89 "BR_SPAWN_LOOPER",
90 "BR_FINISHED",
91 "BR_DEAD_BINDER",
Andy McFadden457d51f2011-08-31 07:43:40 -070092 "BR_CLEAR_DEATH_NOTIFICATION_DONE",
93 "BR_FAILED_REPLY"
Mathias Agopian7922fa22009-05-18 15:08:03 -070094};
95
96static const char *kCommandStrings[] = {
Mathias Agopian7922fa22009-05-18 15:08:03 -070097 "BC_TRANSACTION",
98 "BC_REPLY",
99 "BC_ACQUIRE_RESULT",
100 "BC_FREE_BUFFER",
Mathias Agopian7922fa22009-05-18 15:08:03 -0700101 "BC_INCREFS",
102 "BC_ACQUIRE",
103 "BC_RELEASE",
104 "BC_DECREFS",
105 "BC_INCREFS_DONE",
106 "BC_ACQUIRE_DONE",
107 "BC_ATTEMPT_ACQUIRE",
Mathias Agopian7922fa22009-05-18 15:08:03 -0700108 "BC_REGISTER_LOOPER",
109 "BC_ENTER_LOOPER",
110 "BC_EXIT_LOOPER",
Mathias Agopian7922fa22009-05-18 15:08:03 -0700111 "BC_REQUEST_DEATH_NOTIFICATION",
112 "BC_CLEAR_DEATH_NOTIFICATION",
113 "BC_DEAD_BINDER_DONE"
Mathias Agopian7922fa22009-05-18 15:08:03 -0700114};
115
116static const char* getReturnString(size_t idx)
117{
118 if (idx < sizeof(kReturnStrings) / sizeof(kReturnStrings[0]))
119 return kReturnStrings[idx];
120 else
121 return "unknown";
122}
123
Mathias Agopian7922fa22009-05-18 15:08:03 -0700124static const void* printBinderTransactionData(TextOutput& out, const void* data)
125{
126 const binder_transaction_data* btd =
127 (const binder_transaction_data*)data;
Andy McFadden457d51f2011-08-31 07:43:40 -0700128 if (btd->target.handle < 1024) {
129 /* want to print descriptors in decimal; guess based on value */
130 out << "target.desc=" << btd->target.handle;
131 } else {
132 out << "target.ptr=" << btd->target.ptr;
133 }
134 out << " (cookie " << btd->cookie << ")" << endl
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700135 << "code=" << TypeCode(btd->code) << ", flags=" << (void*)(long)btd->flags << endl
Mathias Agopian7922fa22009-05-18 15:08:03 -0700136 << "data=" << btd->data.ptr.buffer << " (" << (void*)btd->data_size
137 << " bytes)" << endl
138 << "offsets=" << btd->data.ptr.offsets << " (" << (void*)btd->offsets_size
Andy McFadden457d51f2011-08-31 07:43:40 -0700139 << " bytes)";
Mathias Agopian7922fa22009-05-18 15:08:03 -0700140 return btd+1;
141}
142
143static const void* printReturnCommand(TextOutput& out, const void* _cmd)
144{
Andy McFadden457d51f2011-08-31 07:43:40 -0700145 static const size_t N = sizeof(kReturnStrings)/sizeof(kReturnStrings[0]);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700146 const int32_t* cmd = (const int32_t*)_cmd;
Bernhard Rosenkränzerb184ed02014-11-25 21:55:33 +0100147 uint32_t code = (uint32_t)*cmd++;
Andy McFadden457d51f2011-08-31 07:43:40 -0700148 size_t cmdIndex = code & 0xff;
Bernhard Rosenkränzerb184ed02014-11-25 21:55:33 +0100149 if (code == BR_ERROR) {
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700150 out << "BR_ERROR: " << (void*)(long)(*cmd++) << endl;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700151 return cmd;
Andy McFadden457d51f2011-08-31 07:43:40 -0700152 } else if (cmdIndex >= N) {
Mathias Agopian7922fa22009-05-18 15:08:03 -0700153 out << "Unknown reply: " << code << endl;
154 return cmd;
155 }
Andy McFadden457d51f2011-08-31 07:43:40 -0700156 out << kReturnStrings[cmdIndex];
Mathias Agopian7922fa22009-05-18 15:08:03 -0700157
Mathias Agopian7922fa22009-05-18 15:08:03 -0700158 switch (code) {
159 case BR_TRANSACTION:
160 case BR_REPLY: {
161 out << ": " << indent;
162 cmd = (const int32_t *)printBinderTransactionData(out, cmd);
163 out << dedent;
164 } break;
165
166 case BR_ACQUIRE_RESULT: {
167 const int32_t res = *cmd++;
168 out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
169 } break;
170
171 case BR_INCREFS:
172 case BR_ACQUIRE:
173 case BR_RELEASE:
174 case BR_DECREFS: {
175 const int32_t b = *cmd++;
176 const int32_t c = *cmd++;
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700177 out << ": target=" << (void*)(long)b << " (cookie " << (void*)(long)c << ")";
Mathias Agopian7922fa22009-05-18 15:08:03 -0700178 } break;
179
180 case BR_ATTEMPT_ACQUIRE: {
181 const int32_t p = *cmd++;
182 const int32_t b = *cmd++;
183 const int32_t c = *cmd++;
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700184 out << ": target=" << (void*)(long)b << " (cookie " << (void*)(long)c
Mathias Agopian7922fa22009-05-18 15:08:03 -0700185 << "), pri=" << p;
186 } break;
187
188 case BR_DEAD_BINDER:
189 case BR_CLEAR_DEATH_NOTIFICATION_DONE: {
190 const int32_t c = *cmd++;
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700191 out << ": death cookie " << (void*)(long)c;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700192 } break;
Andy McFadden457d51f2011-08-31 07:43:40 -0700193
194 default:
195 // no details to show for: BR_OK, BR_DEAD_REPLY,
196 // BR_TRANSACTION_COMPLETE, BR_FINISHED
197 break;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700198 }
199
200 out << endl;
201 return cmd;
202}
203
204static const void* printCommand(TextOutput& out, const void* _cmd)
205{
Andy McFadden457d51f2011-08-31 07:43:40 -0700206 static const size_t N = sizeof(kCommandStrings)/sizeof(kCommandStrings[0]);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700207 const int32_t* cmd = (const int32_t*)_cmd;
Bernhard Rosenkränzerb184ed02014-11-25 21:55:33 +0100208 uint32_t code = (uint32_t)*cmd++;
Andy McFadden457d51f2011-08-31 07:43:40 -0700209 size_t cmdIndex = code & 0xff;
210
211 if (cmdIndex >= N) {
Mathias Agopian7922fa22009-05-18 15:08:03 -0700212 out << "Unknown command: " << code << endl;
213 return cmd;
214 }
Andy McFadden457d51f2011-08-31 07:43:40 -0700215 out << kCommandStrings[cmdIndex];
216
Mathias Agopian7922fa22009-05-18 15:08:03 -0700217 switch (code) {
218 case BC_TRANSACTION:
219 case BC_REPLY: {
220 out << ": " << indent;
221 cmd = (const int32_t *)printBinderTransactionData(out, cmd);
222 out << dedent;
223 } break;
224
225 case BC_ACQUIRE_RESULT: {
226 const int32_t res = *cmd++;
227 out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
228 } break;
229
230 case BC_FREE_BUFFER: {
231 const int32_t buf = *cmd++;
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700232 out << ": buffer=" << (void*)(long)buf;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700233 } break;
234
235 case BC_INCREFS:
236 case BC_ACQUIRE:
237 case BC_RELEASE:
238 case BC_DECREFS: {
239 const int32_t d = *cmd++;
Andy McFadden457d51f2011-08-31 07:43:40 -0700240 out << ": desc=" << d;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700241 } break;
242
243 case BC_INCREFS_DONE:
244 case BC_ACQUIRE_DONE: {
245 const int32_t b = *cmd++;
246 const int32_t c = *cmd++;
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700247 out << ": target=" << (void*)(long)b << " (cookie " << (void*)(long)c << ")";
Mathias Agopian7922fa22009-05-18 15:08:03 -0700248 } break;
249
250 case BC_ATTEMPT_ACQUIRE: {
251 const int32_t p = *cmd++;
252 const int32_t d = *cmd++;
Andy McFadden457d51f2011-08-31 07:43:40 -0700253 out << ": desc=" << d << ", pri=" << p;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700254 } break;
255
256 case BC_REQUEST_DEATH_NOTIFICATION:
257 case BC_CLEAR_DEATH_NOTIFICATION: {
258 const int32_t h = *cmd++;
259 const int32_t c = *cmd++;
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700260 out << ": handle=" << h << " (death cookie " << (void*)(long)c << ")";
Mathias Agopian7922fa22009-05-18 15:08:03 -0700261 } break;
262
263 case BC_DEAD_BINDER_DONE: {
264 const int32_t c = *cmd++;
Chih-Hung Hsieh30dcad72014-10-24 14:10:09 -0700265 out << ": death cookie " << (void*)(long)c;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700266 } break;
Andy McFadden457d51f2011-08-31 07:43:40 -0700267
268 default:
269 // no details to show for: BC_REGISTER_LOOPER, BC_ENTER_LOOPER,
270 // BC_EXIT_LOOPER
271 break;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700272 }
273
274 out << endl;
275 return cmd;
276}
Mathias Agopian7922fa22009-05-18 15:08:03 -0700277
278static pthread_mutex_t gTLSMutex = PTHREAD_MUTEX_INITIALIZER;
279static bool gHaveTLS = false;
280static pthread_key_t gTLS = 0;
281static bool gShutdown = false;
Dianne Hackborn5f4d7e82009-12-07 17:59:37 -0800282static bool gDisableBackgroundScheduling = false;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700283
284IPCThreadState* IPCThreadState::self()
285{
286 if (gHaveTLS) {
287restart:
288 const pthread_key_t k = gTLS;
289 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
290 if (st) return st;
291 return new IPCThreadState;
292 }
293
Andreas Gampe1d5dc2b2016-02-01 13:21:56 -0800294 if (gShutdown) {
295 ALOGW("Calling IPCThreadState::self() during shutdown is dangerous, expect a crash.\n");
296 return NULL;
297 }
Mathias Agopian7922fa22009-05-18 15:08:03 -0700298
299 pthread_mutex_lock(&gTLSMutex);
300 if (!gHaveTLS) {
Andreas Gampe1d5dc2b2016-02-01 13:21:56 -0800301 int key_create_value = pthread_key_create(&gTLS, threadDestructor);
302 if (key_create_value != 0) {
Mathias Agopian7922fa22009-05-18 15:08:03 -0700303 pthread_mutex_unlock(&gTLSMutex);
Andreas Gampe1d5dc2b2016-02-01 13:21:56 -0800304 ALOGW("IPCThreadState::self() unable to create TLS key, expect a crash: %s\n",
305 strerror(key_create_value));
Mathias Agopian7922fa22009-05-18 15:08:03 -0700306 return NULL;
307 }
308 gHaveTLS = true;
309 }
310 pthread_mutex_unlock(&gTLSMutex);
311 goto restart;
312}
313
Brad Fitzpatrick77949942010-12-13 16:52:35 -0800314IPCThreadState* IPCThreadState::selfOrNull()
315{
316 if (gHaveTLS) {
317 const pthread_key_t k = gTLS;
318 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
319 return st;
320 }
321 return NULL;
322}
323
Mathias Agopian7922fa22009-05-18 15:08:03 -0700324void IPCThreadState::shutdown()
325{
326 gShutdown = true;
327
328 if (gHaveTLS) {
329 // XXX Need to wait for all thread pool threads to exit!
330 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(gTLS);
331 if (st) {
332 delete st;
333 pthread_setspecific(gTLS, NULL);
334 }
zhongjie8e8a0252016-03-09 15:05:04 +0800335 pthread_key_delete(gTLS);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700336 gHaveTLS = false;
337 }
338}
339
Dianne Hackborn5f4d7e82009-12-07 17:59:37 -0800340void IPCThreadState::disableBackgroundScheduling(bool disable)
341{
342 gDisableBackgroundScheduling = disable;
343}
344
Mathias Agopian7922fa22009-05-18 15:08:03 -0700345sp<ProcessState> IPCThreadState::process()
346{
347 return mProcess;
348}
349
350status_t IPCThreadState::clearLastError()
351{
352 const status_t err = mLastError;
353 mLastError = NO_ERROR;
354 return err;
355}
356
Dan Stozae8da8a42014-11-26 12:23:23 -0800357pid_t IPCThreadState::getCallingPid() const
Mathias Agopian7922fa22009-05-18 15:08:03 -0700358{
359 return mCallingPid;
360}
361
Dan Stozae8da8a42014-11-26 12:23:23 -0800362uid_t IPCThreadState::getCallingUid() const
Mathias Agopian7922fa22009-05-18 15:08:03 -0700363{
364 return mCallingUid;
365}
366
367int64_t IPCThreadState::clearCallingIdentity()
368{
369 int64_t token = ((int64_t)mCallingUid<<32) | mCallingPid;
370 clearCaller();
371 return token;
372}
373
Brad Fitzpatrick94c36342010-06-18 13:07:53 -0700374void IPCThreadState::setStrictModePolicy(int32_t policy)
375{
376 mStrictModePolicy = policy;
377}
378
Brad Fitzpatrick3f4ef592010-07-07 16:06:39 -0700379int32_t IPCThreadState::getStrictModePolicy() const
380{
Brad Fitzpatrick94c36342010-06-18 13:07:53 -0700381 return mStrictModePolicy;
382}
383
Brad Fitzpatrick24f8bca2010-08-30 16:01:16 -0700384void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
385{
386 mLastTransactionBinderFlags = flags;
387}
388
389int32_t IPCThreadState::getLastTransactionBinderFlags() const
390{
391 return mLastTransactionBinderFlags;
392}
393
Mathias Agopian7922fa22009-05-18 15:08:03 -0700394void IPCThreadState::restoreCallingIdentity(int64_t token)
395{
396 mCallingUid = (int)(token>>32);
397 mCallingPid = (int)token;
398}
399
400void IPCThreadState::clearCaller()
401{
Marco Nelissenb4f35d02009-07-17 07:59:17 -0700402 mCallingPid = getpid();
403 mCallingUid = getuid();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700404}
405
406void IPCThreadState::flushCommands()
407{
408 if (mProcess->mDriverFD <= 0)
409 return;
410 talkWithDriver(false);
411}
412
Wale Ogunwale2e604f02015-04-13 16:16:10 -0700413void IPCThreadState::blockUntilThreadAvailable()
414{
415 pthread_mutex_lock(&mProcess->mThreadCountLock);
416 while (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads) {
Wale Ogunwale319900a2015-04-21 12:29:50 -0700417 ALOGW("Waiting for thread to be free. mExecutingThreadsCount=%lu mMaxThreads=%lu\n",
418 static_cast<unsigned long>(mProcess->mExecutingThreadsCount),
419 static_cast<unsigned long>(mProcess->mMaxThreads));
Wale Ogunwale2e604f02015-04-13 16:16:10 -0700420 pthread_cond_wait(&mProcess->mThreadCountDecrement, &mProcess->mThreadCountLock);
421 }
422 pthread_mutex_unlock(&mProcess->mThreadCountLock);
423}
424
Todd Poynor0646cb02013-06-25 19:12:18 -0700425status_t IPCThreadState::getAndExecuteCommand()
426{
427 status_t result;
428 int32_t cmd;
429
430 result = talkWithDriver();
431 if (result >= NO_ERROR) {
432 size_t IN = mIn.dataAvail();
433 if (IN < sizeof(int32_t)) return result;
434 cmd = mIn.readInt32();
435 IF_LOG_COMMANDS() {
436 alog << "Processing top-level Command: "
437 << getReturnString(cmd) << endl;
438 }
439
Wale Ogunwale2e604f02015-04-13 16:16:10 -0700440 pthread_mutex_lock(&mProcess->mThreadCountLock);
441 mProcess->mExecutingThreadsCount++;
Colin Crossb1dc6542016-04-15 14:29:55 -0700442 if (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads &&
443 mProcess->mStarvationStartTimeMs == 0) {
444 mProcess->mStarvationStartTimeMs = uptimeMillis();
445 }
Wale Ogunwale2e604f02015-04-13 16:16:10 -0700446 pthread_mutex_unlock(&mProcess->mThreadCountLock);
447
Todd Poynor0646cb02013-06-25 19:12:18 -0700448 result = executeCommand(cmd);
449
Wale Ogunwale2e604f02015-04-13 16:16:10 -0700450 pthread_mutex_lock(&mProcess->mThreadCountLock);
451 mProcess->mExecutingThreadsCount--;
Colin Crossb1dc6542016-04-15 14:29:55 -0700452 if (mProcess->mExecutingThreadsCount < mProcess->mMaxThreads &&
453 mProcess->mStarvationStartTimeMs != 0) {
454 int64_t starvationTimeMs = uptimeMillis() - mProcess->mStarvationStartTimeMs;
455 if (starvationTimeMs > 100) {
456 ALOGE("binder thread pool (%zu threads) starved for %" PRId64 " ms",
457 mProcess->mMaxThreads, starvationTimeMs);
458 }
459 mProcess->mStarvationStartTimeMs = 0;
460 }
Wale Ogunwale2e604f02015-04-13 16:16:10 -0700461 pthread_cond_broadcast(&mProcess->mThreadCountDecrement);
462 pthread_mutex_unlock(&mProcess->mThreadCountLock);
463
Todd Poynor0646cb02013-06-25 19:12:18 -0700464 // After executing the command, ensure that the thread is returned to the
465 // foreground cgroup before rejoining the pool. The driver takes care of
466 // restoring the priority, but doesn't do anything with cgroups so we
467 // need to take care of that here in userspace. Note that we do make
468 // sure to go in the foreground after executing a transaction, but
469 // there are other callbacks into user code that could have changed
470 // our group so we want to make absolutely sure it is put back.
471 set_sched_policy(mMyThreadId, SP_FOREGROUND);
472 }
473
474 return result;
475}
476
477// When we've cleared the incoming command queue, process any pending derefs
478void IPCThreadState::processPendingDerefs()
479{
480 if (mIn.dataPosition() >= mIn.dataSize()) {
481 size_t numPending = mPendingWeakDerefs.size();
482 if (numPending > 0) {
483 for (size_t i = 0; i < numPending; i++) {
484 RefBase::weakref_type* refs = mPendingWeakDerefs[i];
485 refs->decWeak(mProcess.get());
486 }
487 mPendingWeakDerefs.clear();
488 }
489
490 numPending = mPendingStrongDerefs.size();
491 if (numPending > 0) {
492 for (size_t i = 0; i < numPending; i++) {
493 BBinder* obj = mPendingStrongDerefs[i];
494 obj->decStrong(mProcess.get());
495 }
496 mPendingStrongDerefs.clear();
497 }
498 }
499}
500
Mathias Agopian7922fa22009-05-18 15:08:03 -0700501void IPCThreadState::joinThreadPool(bool isMain)
502{
503 LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
504
505 mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
506
Dianne Hackborn5f4d7e82009-12-07 17:59:37 -0800507 // This thread may have been spawned by a thread that was in the background
Glenn Kastencb5e2422012-03-16 07:15:23 -0700508 // scheduling group, so first we will make sure it is in the foreground
Dianne Hackborn5f4d7e82009-12-07 17:59:37 -0800509 // one to avoid performing an initial transaction in the background.
Glenn Kastencb5e2422012-03-16 07:15:23 -0700510 set_sched_policy(mMyThreadId, SP_FOREGROUND);
Dianne Hackborn5f4d7e82009-12-07 17:59:37 -0800511
Mathias Agopian7922fa22009-05-18 15:08:03 -0700512 status_t result;
513 do {
Todd Poynor0646cb02013-06-25 19:12:18 -0700514 processPendingDerefs();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700515 // now get the next command to be processed, waiting if necessary
Todd Poynor0646cb02013-06-25 19:12:18 -0700516 result = getAndExecuteCommand();
Jason Parks2b17f142009-11-03 12:14:38 -0800517
Todd Poynor0646cb02013-06-25 19:12:18 -0700518 if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
519 ALOGE("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
Jeff Tinkeree711ec2013-06-11 11:30:21 -0700520 mProcess->mDriverFD, result);
521 abort();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700522 }
523
Mathias Agopian7922fa22009-05-18 15:08:03 -0700524 // Let this thread exit the thread pool if it is no longer
525 // needed and it is not the main process thread.
526 if(result == TIMED_OUT && !isMain) {
527 break;
528 }
529 } while (result != -ECONNREFUSED && result != -EBADF);
530
531 LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%p\n",
532 (void*)pthread_self(), getpid(), (void*)result);
533
534 mOut.writeInt32(BC_EXIT_LOOPER);
535 talkWithDriver(false);
536}
537
Todd Poynor0646cb02013-06-25 19:12:18 -0700538int IPCThreadState::setupPolling(int* fd)
539{
540 if (mProcess->mDriverFD <= 0) {
541 return -EBADF;
542 }
543
544 mOut.writeInt32(BC_ENTER_LOOPER);
545 *fd = mProcess->mDriverFD;
546 return 0;
547}
548
549status_t IPCThreadState::handlePolledCommands()
550{
551 status_t result;
552
553 do {
554 result = getAndExecuteCommand();
555 } while (mIn.dataPosition() < mIn.dataSize());
556
557 processPendingDerefs();
558 flushCommands();
559 return result;
560}
561
Colin Crossf0487982014-02-05 17:42:44 -0800562void IPCThreadState::stopProcess(bool /*immediate*/)
Mathias Agopian7922fa22009-05-18 15:08:03 -0700563{
Steve Block93cf8542012-01-04 20:05:49 +0000564 //ALOGI("**** STOPPING PROCESS");
Mathias Agopian7922fa22009-05-18 15:08:03 -0700565 flushCommands();
566 int fd = mProcess->mDriverFD;
567 mProcess->mDriverFD = -1;
568 close(fd);
569 //kill(getpid(), SIGKILL);
570}
571
572status_t IPCThreadState::transact(int32_t handle,
573 uint32_t code, const Parcel& data,
574 Parcel* reply, uint32_t flags)
575{
576 status_t err = data.errorCheck();
577
578 flags |= TF_ACCEPT_FDS;
579
580 IF_LOG_TRANSACTIONS() {
Mathias Agopian7922fa22009-05-18 15:08:03 -0700581 alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
582 << handle << " / code " << TypeCode(code) << ": "
583 << indent << data << dedent << endl;
584 }
585
586 if (err == NO_ERROR) {
587 LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
588 (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
Martijn Coenend39a1682016-06-03 21:27:28 +0200589 err = writeTransactionData(BC_TRANSACTION_SG, flags, handle, code, data, NULL);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700590 }
591
592 if (err != NO_ERROR) {
593 if (reply) reply->setError(err);
594 return (mLastError = err);
595 }
596
597 if ((flags & TF_ONE_WAY) == 0) {
Dianne Hackborn98878262010-09-24 11:16:23 -0700598 #if 0
599 if (code == 4) { // relayout
Steve Block93cf8542012-01-04 20:05:49 +0000600 ALOGI(">>>>>> CALLING transaction 4");
Dianne Hackborn98878262010-09-24 11:16:23 -0700601 } else {
Steve Block93cf8542012-01-04 20:05:49 +0000602 ALOGI(">>>>>> CALLING transaction %d", code);
Dianne Hackborn98878262010-09-24 11:16:23 -0700603 }
604 #endif
Mathias Agopian7922fa22009-05-18 15:08:03 -0700605 if (reply) {
606 err = waitForResponse(reply);
607 } else {
608 Parcel fakeReply;
609 err = waitForResponse(&fakeReply);
610 }
Dianne Hackborn98878262010-09-24 11:16:23 -0700611 #if 0
612 if (code == 4) { // relayout
Steve Block93cf8542012-01-04 20:05:49 +0000613 ALOGI("<<<<<< RETURNING transaction 4");
Dianne Hackborn98878262010-09-24 11:16:23 -0700614 } else {
Steve Block93cf8542012-01-04 20:05:49 +0000615 ALOGI("<<<<<< RETURNING transaction %d", code);
Dianne Hackborn98878262010-09-24 11:16:23 -0700616 }
617 #endif
Mathias Agopian7922fa22009-05-18 15:08:03 -0700618
619 IF_LOG_TRANSACTIONS() {
Mathias Agopian7922fa22009-05-18 15:08:03 -0700620 alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
621 << handle << ": ";
622 if (reply) alog << indent << *reply << dedent << endl;
623 else alog << "(none requested)" << endl;
624 }
625 } else {
626 err = waitForResponse(NULL, NULL);
627 }
628
629 return err;
630}
631
632void IPCThreadState::incStrongHandle(int32_t handle)
633{
634 LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
635 mOut.writeInt32(BC_ACQUIRE);
636 mOut.writeInt32(handle);
637}
638
639void IPCThreadState::decStrongHandle(int32_t handle)
640{
641 LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
642 mOut.writeInt32(BC_RELEASE);
643 mOut.writeInt32(handle);
644}
645
646void IPCThreadState::incWeakHandle(int32_t handle)
647{
648 LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
649 mOut.writeInt32(BC_INCREFS);
650 mOut.writeInt32(handle);
651}
652
653void IPCThreadState::decWeakHandle(int32_t handle)
654{
655 LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
656 mOut.writeInt32(BC_DECREFS);
657 mOut.writeInt32(handle);
658}
659
660status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
661{
Arve Hjønnevåg304dcae2014-02-14 20:14:02 -0800662#if HAS_BC_ATTEMPT_ACQUIRE
Andy McFadden457d51f2011-08-31 07:43:40 -0700663 LOG_REMOTEREFS("IPCThreadState::attemptIncStrongHandle(%d)\n", handle);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700664 mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
665 mOut.writeInt32(0); // xxx was thread priority
666 mOut.writeInt32(handle);
667 status_t result = UNKNOWN_ERROR;
668
669 waitForResponse(NULL, &result);
670
671#if LOG_REFCOUNTS
672 printf("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
673 handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
674#endif
675
676 return result;
Arve Hjønnevåg304dcae2014-02-14 20:14:02 -0800677#else
678 (void)handle;
679 ALOGE("%s(%d): Not supported\n", __func__, handle);
680 return INVALID_OPERATION;
681#endif
Mathias Agopian7922fa22009-05-18 15:08:03 -0700682}
683
684void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
685{
686#if LOG_REFCOUNTS
687 printf("IPCThreadState::expungeHandle(%ld)\n", handle);
688#endif
689 self()->mProcess->expungeHandle(handle, binder);
690}
691
692status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
693{
694 mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
695 mOut.writeInt32((int32_t)handle);
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +0000696 mOut.writePointer((uintptr_t)proxy);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700697 return NO_ERROR;
698}
699
700status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
701{
702 mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
703 mOut.writeInt32((int32_t)handle);
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +0000704 mOut.writePointer((uintptr_t)proxy);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700705 return NO_ERROR;
706}
707
708IPCThreadState::IPCThreadState()
Brad Fitzpatrick24f8bca2010-08-30 16:01:16 -0700709 : mProcess(ProcessState::self()),
Elliott Hughes07cf48a2014-08-18 10:38:38 -0700710 mMyThreadId(gettid()),
Brad Fitzpatrick24f8bca2010-08-30 16:01:16 -0700711 mStrictModePolicy(0),
712 mLastTransactionBinderFlags(0)
Mathias Agopian7922fa22009-05-18 15:08:03 -0700713{
714 pthread_setspecific(gTLS, this);
Dianne Hackborn5f4d7e82009-12-07 17:59:37 -0800715 clearCaller();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700716 mIn.setDataCapacity(256);
717 mOut.setDataCapacity(256);
718}
719
720IPCThreadState::~IPCThreadState()
721{
722}
723
724status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
725{
726 status_t err;
727 status_t statusBuffer;
Martijn Coenend39a1682016-06-03 21:27:28 +0200728 err = writeTransactionData(BC_REPLY_SG, flags, -1, 0, reply, &statusBuffer);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700729 if (err < NO_ERROR) return err;
730
731 return waitForResponse(NULL, NULL);
732}
733
734status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
735{
Bernhard Rosenkränzerb184ed02014-11-25 21:55:33 +0100736 uint32_t cmd;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700737 int32_t err;
738
739 while (1) {
740 if ((err=talkWithDriver()) < NO_ERROR) break;
741 err = mIn.errorCheck();
742 if (err < NO_ERROR) break;
743 if (mIn.dataAvail() == 0) continue;
744
Bernhard Rosenkränzerb184ed02014-11-25 21:55:33 +0100745 cmd = (uint32_t)mIn.readInt32();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700746
747 IF_LOG_COMMANDS() {
748 alog << "Processing waitForResponse Command: "
749 << getReturnString(cmd) << endl;
750 }
751
752 switch (cmd) {
753 case BR_TRANSACTION_COMPLETE:
754 if (!reply && !acquireResult) goto finish;
755 break;
756
757 case BR_DEAD_REPLY:
758 err = DEAD_OBJECT;
759 goto finish;
760
761 case BR_FAILED_REPLY:
762 err = FAILED_TRANSACTION;
763 goto finish;
764
765 case BR_ACQUIRE_RESULT:
766 {
Steve Blockd0bfabc2012-01-09 18:35:44 +0000767 ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
Mathias Agopian7922fa22009-05-18 15:08:03 -0700768 const int32_t result = mIn.readInt32();
769 if (!acquireResult) continue;
770 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
771 }
772 goto finish;
773
774 case BR_REPLY:
775 {
776 binder_transaction_data tr;
777 err = mIn.read(&tr, sizeof(tr));
Steve Blockd0bfabc2012-01-09 18:35:44 +0000778 ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
Mathias Agopian7922fa22009-05-18 15:08:03 -0700779 if (err != NO_ERROR) goto finish;
780
781 if (reply) {
782 if ((tr.flags & TF_STATUS_CODE) == 0) {
783 reply->ipcSetDataReference(
784 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
785 tr.data_size,
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800786 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
787 tr.offsets_size/sizeof(binder_size_t),
Mathias Agopian7922fa22009-05-18 15:08:03 -0700788 freeBuffer, this);
789 } else {
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800790 err = *reinterpret_cast<const status_t*>(tr.data.ptr.buffer);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700791 freeBuffer(NULL,
792 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
793 tr.data_size,
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800794 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
795 tr.offsets_size/sizeof(binder_size_t), this);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700796 }
797 } else {
798 freeBuffer(NULL,
799 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
800 tr.data_size,
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800801 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
802 tr.offsets_size/sizeof(binder_size_t), this);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700803 continue;
804 }
805 }
806 goto finish;
807
808 default:
809 err = executeCommand(cmd);
810 if (err != NO_ERROR) goto finish;
811 break;
812 }
813 }
814
815finish:
816 if (err != NO_ERROR) {
817 if (acquireResult) *acquireResult = err;
818 if (reply) reply->setError(err);
819 mLastError = err;
820 }
821
822 return err;
823}
824
825status_t IPCThreadState::talkWithDriver(bool doReceive)
826{
Johannes Carlsson597a3c72011-02-17 14:06:53 +0100827 if (mProcess->mDriverFD <= 0) {
828 return -EBADF;
829 }
Mathias Agopian7922fa22009-05-18 15:08:03 -0700830
831 binder_write_read bwr;
832
833 // Is the read buffer empty?
834 const bool needRead = mIn.dataPosition() >= mIn.dataSize();
835
836 // We don't want to write anything if we are still reading
837 // from data left in the input buffer and the caller
838 // has requested to read the next data.
839 const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
840
841 bwr.write_size = outAvail;
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800842 bwr.write_buffer = (uintptr_t)mOut.data();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700843
844 // This is what we'll read.
845 if (doReceive && needRead) {
846 bwr.read_size = mIn.dataCapacity();
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800847 bwr.read_buffer = (uintptr_t)mIn.data();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700848 } else {
849 bwr.read_size = 0;
Ben Cheng455a70a2011-12-01 17:11:32 -0800850 bwr.read_buffer = 0;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700851 }
Andy McFadden457d51f2011-08-31 07:43:40 -0700852
Mathias Agopian7922fa22009-05-18 15:08:03 -0700853 IF_LOG_COMMANDS() {
Mathias Agopian7922fa22009-05-18 15:08:03 -0700854 if (outAvail != 0) {
855 alog << "Sending commands to driver: " << indent;
856 const void* cmds = (const void*)bwr.write_buffer;
857 const void* end = ((const uint8_t*)cmds)+bwr.write_size;
858 alog << HexDump(cmds, bwr.write_size) << endl;
859 while (cmds < end) cmds = printCommand(alog, cmds);
860 alog << dedent;
861 }
862 alog << "Size of receive buffer: " << bwr.read_size
863 << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
864 }
865
866 // Return immediately if there is nothing to do.
867 if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
Andy McFadden457d51f2011-08-31 07:43:40 -0700868
Mathias Agopian7922fa22009-05-18 15:08:03 -0700869 bwr.write_consumed = 0;
870 bwr.read_consumed = 0;
871 status_t err;
872 do {
873 IF_LOG_COMMANDS() {
874 alog << "About to read/write, write size = " << mOut.dataSize() << endl;
875 }
Elliott Hughese5e70552015-08-12 15:27:47 -0700876#if defined(__ANDROID__)
Mathias Agopian7922fa22009-05-18 15:08:03 -0700877 if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
878 err = NO_ERROR;
879 else
880 err = -errno;
881#else
882 err = INVALID_OPERATION;
883#endif
Johannes Carlsson597a3c72011-02-17 14:06:53 +0100884 if (mProcess->mDriverFD <= 0) {
885 err = -EBADF;
886 }
Mathias Agopian7922fa22009-05-18 15:08:03 -0700887 IF_LOG_COMMANDS() {
888 alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
889 }
890 } while (err == -EINTR);
Andy McFadden457d51f2011-08-31 07:43:40 -0700891
Mathias Agopian7922fa22009-05-18 15:08:03 -0700892 IF_LOG_COMMANDS() {
Colin Crossf0487982014-02-05 17:42:44 -0800893 alog << "Our err: " << (void*)(intptr_t)err << ", write consumed: "
Mathias Agopian7922fa22009-05-18 15:08:03 -0700894 << bwr.write_consumed << " (of " << mOut.dataSize()
Todd Poynor0646cb02013-06-25 19:12:18 -0700895 << "), read consumed: " << bwr.read_consumed << endl;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700896 }
897
898 if (err >= NO_ERROR) {
899 if (bwr.write_consumed > 0) {
Arve Hjønnevåga5440702014-01-28 20:12:59 -0800900 if (bwr.write_consumed < mOut.dataSize())
Mathias Agopian7922fa22009-05-18 15:08:03 -0700901 mOut.remove(0, bwr.write_consumed);
902 else
903 mOut.setDataSize(0);
904 }
905 if (bwr.read_consumed > 0) {
906 mIn.setDataSize(bwr.read_consumed);
907 mIn.setDataPosition(0);
908 }
909 IF_LOG_COMMANDS() {
Mathias Agopian7922fa22009-05-18 15:08:03 -0700910 alog << "Remaining data size: " << mOut.dataSize() << endl;
911 alog << "Received commands from driver: " << indent;
912 const void* cmds = mIn.data();
913 const void* end = mIn.data() + mIn.dataSize();
914 alog << HexDump(cmds, mIn.dataSize()) << endl;
915 while (cmds < end) cmds = printReturnCommand(alog, cmds);
916 alog << dedent;
917 }
918 return NO_ERROR;
919 }
920
921 return err;
922}
923
924status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
925 int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
926{
Martijn Coenenfd51ebb2016-07-05 17:00:39 +0200927 binder_transaction_data_sg tr_sg;
928 tr_sg.tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
929 tr_sg.tr.target.handle = handle;
930 tr_sg.tr.code = code;
931 tr_sg.tr.flags = binderFlags;
932 tr_sg.tr.cookie = 0;
933 tr_sg.tr.sender_pid = 0;
934 tr_sg.tr.sender_euid = 0;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700935
936 const status_t err = data.errorCheck();
937 if (err == NO_ERROR) {
Martijn Coenenfd51ebb2016-07-05 17:00:39 +0200938 tr_sg.tr.data_size = data.ipcDataSize();
939 tr_sg.tr.data.ptr.buffer = data.ipcData();
940 tr_sg.tr.offsets_size = data.ipcObjectsCount()*sizeof(binder_size_t);
941 tr_sg.tr.data.ptr.offsets = data.ipcObjects();
942 tr_sg.buffers_size = data.ipcBufferSize();
Mathias Agopian7922fa22009-05-18 15:08:03 -0700943 } else if (statusBuffer) {
Martijn Coenenfd51ebb2016-07-05 17:00:39 +0200944 tr_sg.tr.flags |= TF_STATUS_CODE;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700945 *statusBuffer = err;
Martijn Coenenfd51ebb2016-07-05 17:00:39 +0200946 tr_sg.tr.data_size = sizeof(status_t);
947 tr_sg.tr.data.ptr.buffer = reinterpret_cast<uintptr_t>(statusBuffer);
948 tr_sg.tr.offsets_size = 0;
949 tr_sg.tr.data.ptr.offsets = 0;
950 tr_sg.buffers_size = 0;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700951 } else {
952 return (mLastError = err);
953 }
954
955 mOut.writeInt32(cmd);
Martijn Coenenfd51ebb2016-07-05 17:00:39 +0200956 mOut.write(&tr_sg, sizeof(tr_sg));
Mathias Agopian7922fa22009-05-18 15:08:03 -0700957
958 return NO_ERROR;
959}
960
Martijn Coenena660cbc2016-05-12 11:29:23 +0200961void IPCThreadState::setTheContextObject(sp<BBinder> obj)
Mathias Agopian7922fa22009-05-18 15:08:03 -0700962{
Martijn Coenena660cbc2016-05-12 11:29:23 +0200963 mContextObject = obj;
Mathias Agopian7922fa22009-05-18 15:08:03 -0700964}
965
966status_t IPCThreadState::executeCommand(int32_t cmd)
967{
968 BBinder* obj;
969 RefBase::weakref_type* refs;
970 status_t result = NO_ERROR;
Bernhard Rosenkränzerb184ed02014-11-25 21:55:33 +0100971 switch ((uint32_t)cmd) {
Mathias Agopian7922fa22009-05-18 15:08:03 -0700972 case BR_ERROR:
973 result = mIn.readInt32();
974 break;
975
976 case BR_OK:
977 break;
978
979 case BR_ACQUIRE:
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +0000980 refs = (RefBase::weakref_type*)mIn.readPointer();
981 obj = (BBinder*)mIn.readPointer();
Steve Blockd0bfabc2012-01-09 18:35:44 +0000982 ALOG_ASSERT(refs->refBase() == obj,
Mathias Agopian7922fa22009-05-18 15:08:03 -0700983 "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
984 refs, obj, refs->refBase());
985 obj->incStrong(mProcess.get());
986 IF_LOG_REMOTEREFS() {
987 LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
988 obj->printRefs();
989 }
990 mOut.writeInt32(BC_ACQUIRE_DONE);
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +0000991 mOut.writePointer((uintptr_t)refs);
992 mOut.writePointer((uintptr_t)obj);
Mathias Agopian7922fa22009-05-18 15:08:03 -0700993 break;
994
995 case BR_RELEASE:
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +0000996 refs = (RefBase::weakref_type*)mIn.readPointer();
997 obj = (BBinder*)mIn.readPointer();
Steve Blockd0bfabc2012-01-09 18:35:44 +0000998 ALOG_ASSERT(refs->refBase() == obj,
Mathias Agopian7922fa22009-05-18 15:08:03 -0700999 "BR_RELEASE: object %p does not match cookie %p (expected %p)",
1000 refs, obj, refs->refBase());
1001 IF_LOG_REMOTEREFS() {
1002 LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
1003 obj->printRefs();
1004 }
1005 mPendingStrongDerefs.push(obj);
1006 break;
1007
1008 case BR_INCREFS:
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +00001009 refs = (RefBase::weakref_type*)mIn.readPointer();
1010 obj = (BBinder*)mIn.readPointer();
Mathias Agopian7922fa22009-05-18 15:08:03 -07001011 refs->incWeak(mProcess.get());
1012 mOut.writeInt32(BC_INCREFS_DONE);
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +00001013 mOut.writePointer((uintptr_t)refs);
1014 mOut.writePointer((uintptr_t)obj);
Mathias Agopian7922fa22009-05-18 15:08:03 -07001015 break;
1016
1017 case BR_DECREFS:
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 // NOTE: This assertion is not valid, because the object may no
1021 // longer exist (thus the (BBinder*)cast above resulting in a different
1022 // memory address).
Steve Blockd0bfabc2012-01-09 18:35:44 +00001023 //ALOG_ASSERT(refs->refBase() == obj,
Mathias Agopian7922fa22009-05-18 15:08:03 -07001024 // "BR_DECREFS: object %p does not match cookie %p (expected %p)",
1025 // refs, obj, refs->refBase());
1026 mPendingWeakDerefs.push(refs);
1027 break;
1028
1029 case BR_ATTEMPT_ACQUIRE:
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +00001030 refs = (RefBase::weakref_type*)mIn.readPointer();
1031 obj = (BBinder*)mIn.readPointer();
Mathias Agopian7922fa22009-05-18 15:08:03 -07001032
1033 {
1034 const bool success = refs->attemptIncStrong(mProcess.get());
Steve Blockd0bfabc2012-01-09 18:35:44 +00001035 ALOG_ASSERT(success && refs->refBase() == obj,
Mathias Agopian7922fa22009-05-18 15:08:03 -07001036 "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
1037 refs, obj, refs->refBase());
1038
1039 mOut.writeInt32(BC_ACQUIRE_RESULT);
1040 mOut.writeInt32((int32_t)success);
1041 }
1042 break;
1043
1044 case BR_TRANSACTION:
1045 {
1046 binder_transaction_data tr;
1047 result = mIn.read(&tr, sizeof(tr));
Steve Blockd0bfabc2012-01-09 18:35:44 +00001048 ALOG_ASSERT(result == NO_ERROR,
Mathias Agopian7922fa22009-05-18 15:08:03 -07001049 "Not enough command data for brTRANSACTION");
1050 if (result != NO_ERROR) break;
1051
1052 Parcel buffer;
1053 buffer.ipcSetDataReference(
1054 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1055 tr.data_size,
Arve Hjønnevåga5440702014-01-28 20:12:59 -08001056 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1057 tr.offsets_size/sizeof(binder_size_t), freeBuffer, this);
Mathias Agopian7922fa22009-05-18 15:08:03 -07001058
1059 const pid_t origPid = mCallingPid;
1060 const uid_t origUid = mCallingUid;
Dianne Hackbornf99aec62014-09-30 11:30:03 -07001061 const int32_t origStrictModePolicy = mStrictModePolicy;
1062 const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
1063
Mathias Agopian7922fa22009-05-18 15:08:03 -07001064 mCallingPid = tr.sender_pid;
1065 mCallingUid = tr.sender_euid;
Dianne Hackbornf99aec62014-09-30 11:30:03 -07001066 mLastTransactionBinderFlags = tr.flags;
1067
Christopher Tate7c4dfec2010-03-18 17:55:03 -07001068 int curPrio = getpriority(PRIO_PROCESS, mMyThreadId);
1069 if (gDisableBackgroundScheduling) {
1070 if (curPrio > ANDROID_PRIORITY_NORMAL) {
1071 // We have inherited a reduced priority from the caller, but do not
1072 // want to run in that state in this process. The driver set our
1073 // priority already (though not our scheduling class), so bounce
1074 // it back to the default before invoking the transaction.
1075 setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL);
1076 }
1077 } else {
1078 if (curPrio >= ANDROID_PRIORITY_BACKGROUND) {
1079 // We want to use the inherited priority from the caller.
1080 // Ensure this thread is in the background scheduling class,
1081 // since the driver won't modify scheduling classes for us.
1082 // The scheduling group is reset to default by the caller
1083 // once this method returns after the transaction is complete.
Glenn Kastencb5e2422012-03-16 07:15:23 -07001084 set_sched_policy(mMyThreadId, SP_BACKGROUND);
Christopher Tate7c4dfec2010-03-18 17:55:03 -07001085 }
Dianne Hackborn5f4d7e82009-12-07 17:59:37 -08001086 }
Christopher Tate7c4dfec2010-03-18 17:55:03 -07001087
Steve Block93cf8542012-01-04 20:05:49 +00001088 //ALOGI(">>>> TRANSACT from pid %d uid %d\n", mCallingPid, mCallingUid);
Dianne Hackbornf99aec62014-09-30 11:30:03 -07001089
Mathias Agopian7922fa22009-05-18 15:08:03 -07001090 Parcel reply;
Dianne Hackbornf99aec62014-09-30 11:30:03 -07001091 status_t error;
Martijn Coenen79c2f4d2016-05-20 10:55:59 +02001092 bool reply_sent = false;
Mathias Agopian7922fa22009-05-18 15:08:03 -07001093 IF_LOG_TRANSACTIONS() {
Mathias Agopian7922fa22009-05-18 15:08:03 -07001094 alog << "BR_TRANSACTION thr " << (void*)pthread_self()
1095 << " / obj " << tr.target.ptr << " / code "
1096 << TypeCode(tr.code) << ": " << indent << buffer
1097 << dedent << endl
1098 << "Data addr = "
1099 << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1100 << ", offsets addr="
1101 << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
1102 }
Martijn Coenen79c2f4d2016-05-20 10:55:59 +02001103
1104 auto reply_callback = [&] (auto &replyParcel) {
1105 if (reply_sent) {
1106 // Reply was sent earlier, ignore it.
1107 ALOGE("Dropping binder reply, it was sent already.");
1108 return;
1109 }
1110 reply_sent = true;
1111 if ((tr.flags & TF_ONE_WAY) == 0) {
1112 replyParcel.setError(NO_ERROR);
1113 sendReply(replyParcel, 0);
1114 } else {
1115 ALOGE("Not sending reply in one-way transaction");
1116 }
1117 };
1118
Mathias Agopian7922fa22009-05-18 15:08:03 -07001119 if (tr.target.ptr) {
Dianne Hackborn839f7072016-03-21 10:36:54 -07001120 // We only have a weak reference on the target object, so we must first try to
1121 // safely acquire a strong reference before doing anything else with it.
1122 if (reinterpret_cast<RefBase::weakref_type*>(
1123 tr.target.ptr)->attemptIncStrong(this)) {
1124 error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,
Martijn Coenen79c2f4d2016-05-20 10:55:59 +02001125 &reply, tr.flags, reply_callback);
Dianne Hackborn839f7072016-03-21 10:36:54 -07001126 reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);
1127 } else {
1128 error = UNKNOWN_TRANSACTION;
1129 }
Brad Fitzpatrick24f8bca2010-08-30 16:01:16 -07001130
Mathias Agopian7922fa22009-05-18 15:08:03 -07001131 } else {
Martijn Coenena660cbc2016-05-12 11:29:23 +02001132 error = mContextObject->transact(tr.code, buffer, &reply, tr.flags, reply_callback);
Martijn Coenen79c2f4d2016-05-20 10:55:59 +02001133 }
1134
1135 if ((tr.flags & TF_ONE_WAY) == 0) {
1136 if (!reply_sent) {
1137 // Should have been a reply but there wasn't, so there
1138 // must have been an error instead.
1139 reply.setError(error);
1140 sendReply(reply, 0);
1141 } else {
1142 if (error != NO_ERROR) {
1143 ALOGE("transact() returned error after sending reply.");
1144 } else {
1145 // Ok, reply sent and transact didn't return an error.
1146 }
1147 }
1148 } else {
1149 // One-way transaction, don't care about return value or reply.
Mathias Agopian7922fa22009-05-18 15:08:03 -07001150 }
Dianne Hackbornf99aec62014-09-30 11:30:03 -07001151
Steve Block93cf8542012-01-04 20:05:49 +00001152 //ALOGI("<<<< TRANSACT from pid %d restore pid %d uid %d\n",
Mathias Agopian7922fa22009-05-18 15:08:03 -07001153 // mCallingPid, origPid, origUid);
Martijn Coenen79c2f4d2016-05-20 10:55:59 +02001154
Mathias Agopian7922fa22009-05-18 15:08:03 -07001155
1156 mCallingPid = origPid;
1157 mCallingUid = origUid;
Dianne Hackbornf99aec62014-09-30 11:30:03 -07001158 mStrictModePolicy = origStrictModePolicy;
1159 mLastTransactionBinderFlags = origTransactionBinderFlags;
Christopher Tate7c4dfec2010-03-18 17:55:03 -07001160
Mathias Agopian7922fa22009-05-18 15:08:03 -07001161 IF_LOG_TRANSACTIONS() {
Mathias Agopian7922fa22009-05-18 15:08:03 -07001162 alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
1163 << tr.target.ptr << ": " << indent << reply << dedent << endl;
1164 }
1165
1166 }
1167 break;
1168
1169 case BR_DEAD_BINDER:
1170 {
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +00001171 BpBinder *proxy = (BpBinder*)mIn.readPointer();
Mathias Agopian7922fa22009-05-18 15:08:03 -07001172 proxy->sendObituary();
1173 mOut.writeInt32(BC_DEAD_BINDER_DONE);
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +00001174 mOut.writePointer((uintptr_t)proxy);
Mathias Agopian7922fa22009-05-18 15:08:03 -07001175 } break;
1176
1177 case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1178 {
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +00001179 BpBinder *proxy = (BpBinder*)mIn.readPointer();
Mathias Agopian7922fa22009-05-18 15:08:03 -07001180 proxy->getWeakRefs()->decWeak(proxy);
1181 } break;
1182
1183 case BR_FINISHED:
1184 result = TIMED_OUT;
1185 break;
1186
1187 case BR_NOOP:
1188 break;
1189
1190 case BR_SPAWN_LOOPER:
1191 mProcess->spawnPooledThread(false);
1192 break;
1193
1194 default:
1195 printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
1196 result = UNKNOWN_ERROR;
1197 break;
1198 }
1199
1200 if (result != NO_ERROR) {
1201 mLastError = result;
1202 }
1203
1204 return result;
1205}
1206
1207void IPCThreadState::threadDestructor(void *st)
1208{
Todd Poynor0646cb02013-06-25 19:12:18 -07001209 IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1210 if (self) {
1211 self->flushCommands();
Elliott Hughese5e70552015-08-12 15:27:47 -07001212#if defined(__ANDROID__)
Johannes Carlsson597a3c72011-02-17 14:06:53 +01001213 if (self->mProcess->mDriverFD > 0) {
1214 ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1215 }
Mathias Agopian7922fa22009-05-18 15:08:03 -07001216#endif
Todd Poynor0646cb02013-06-25 19:12:18 -07001217 delete self;
1218 }
Mathias Agopian7922fa22009-05-18 15:08:03 -07001219}
1220
1221
Colin Crossf0487982014-02-05 17:42:44 -08001222void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data,
1223 size_t /*dataSize*/,
1224 const binder_size_t* /*objects*/,
1225 size_t /*objectsSize*/, void* /*cookie*/)
Mathias Agopian7922fa22009-05-18 15:08:03 -07001226{
Steve Block93cf8542012-01-04 20:05:49 +00001227 //ALOGI("Freeing parcel %p", &parcel);
Mathias Agopian7922fa22009-05-18 15:08:03 -07001228 IF_LOG_COMMANDS() {
1229 alog << "Writing BC_FREE_BUFFER for " << data << endl;
1230 }
Steve Blockd0bfabc2012-01-09 18:35:44 +00001231 ALOG_ASSERT(data != NULL, "Called with NULL data");
Mathias Agopian7922fa22009-05-18 15:08:03 -07001232 if (parcel != NULL) parcel->closeFileDescriptors();
1233 IPCThreadState* state = self();
1234 state->mOut.writeInt32(BC_FREE_BUFFER);
Serban Constantinescu4ca5baf2013-11-05 16:53:55 +00001235 state->mOut.writePointer((uintptr_t)data);
Mathias Agopian7922fa22009-05-18 15:08:03 -07001236}
1237
Martijn Coenenf75a23d2016-08-01 11:55:17 +02001238}; // namespace hardware
Mathias Agopian7922fa22009-05-18 15:08:03 -07001239}; // namespace android