blob: d453ac7532be6c3c0eb4ad56cb8ad5a193515bc3 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
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 Parksdcd39582009-11-03 12:14:38 -080017#define LOG_TAG "IPCThreadState"
18
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070019#include <binder/IPCThreadState.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070021#include <binder/Binder.h>
22#include <binder/BpBinder.h>
Mathias Agopian002e1e52013-05-06 20:20:50 -070023#include <binder/TextOutput.h>
24
Steven Moreland7732a092019-01-02 17:54:16 -080025#include <android-base/macros.h>
Glenn Kastena26e1cf2012-03-16 07:15:23 -070026#include <cutils/sched_policy.h>
Steven Moreland7732a092019-01-02 17:54:16 -080027#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080028#include <utils/Log.h>
Colin Cross96e83222016-04-15 14:29:55 -070029#include <utils/SystemClock.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
Hans Boehma997b232019-04-12 16:59:00 -070031#include <atomic>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032#include <errno.h>
Colin Cross96e83222016-04-15 14:29:55 -070033#include <inttypes.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080034#include <pthread.h>
35#include <sched.h>
Yabin Cui8fb2d252015-01-26 19:45:47 -080036#include <signal.h>
37#include <stdio.h>
38#include <sys/ioctl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080039#include <sys/resource.h>
Yabin Cui8fb2d252015-01-26 19:45:47 -080040#include <unistd.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080041
Steven Morelanda4853cd2019-07-12 15:44:37 -070042#include "Static.h"
Steven Moreland6ba5a252021-05-04 22:49:00 +000043#include "binder_module.h"
Steven Morelanda4853cd2019-07-12 15:44:37 -070044
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080045#if LOG_NDEBUG
46
47#define IF_LOG_TRANSACTIONS() if (false)
48#define IF_LOG_COMMANDS() if (false)
49#define LOG_REMOTEREFS(...)
50#define IF_LOG_REMOTEREFS() if (false)
Tim Murrayd429f4a2017-03-07 09:31:09 -080051
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080052#define LOG_THREADPOOL(...)
53#define LOG_ONEWAY(...)
54
55#else
56
Steve Block9f760152011-10-12 17:27:03 +010057#define IF_LOG_TRANSACTIONS() IF_ALOG(LOG_VERBOSE, "transact")
58#define IF_LOG_COMMANDS() IF_ALOG(LOG_VERBOSE, "ipc")
59#define LOG_REMOTEREFS(...) ALOG(LOG_DEBUG, "remoterefs", __VA_ARGS__)
60#define IF_LOG_REMOTEREFS() IF_ALOG(LOG_DEBUG, "remoterefs")
61#define LOG_THREADPOOL(...) ALOG(LOG_DEBUG, "threadpool", __VA_ARGS__)
62#define LOG_ONEWAY(...) ALOG(LOG_DEBUG, "ipc", __VA_ARGS__)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
64#endif
65
66// ---------------------------------------------------------------------------
67
68namespace android {
69
Chih-Hung Hsieh8e5337d2014-10-24 14:10:09 -070070// Static const and functions will be optimized out if not used,
71// when LOG_NDEBUG and references in IF_LOG_COMMANDS() are optimized out.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072static const char *kReturnStrings[] = {
Andy McFaddenaefc9cd2011-08-31 07:43:40 -070073 "BR_ERROR",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074 "BR_OK",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075 "BR_TRANSACTION",
76 "BR_REPLY",
77 "BR_ACQUIRE_RESULT",
78 "BR_DEAD_REPLY",
79 "BR_TRANSACTION_COMPLETE",
80 "BR_INCREFS",
81 "BR_ACQUIRE",
82 "BR_RELEASE",
83 "BR_DECREFS",
84 "BR_ATTEMPT_ACQUIRE",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085 "BR_NOOP",
86 "BR_SPAWN_LOOPER",
87 "BR_FINISHED",
88 "BR_DEAD_BINDER",
Andy McFaddenaefc9cd2011-08-31 07:43:40 -070089 "BR_CLEAR_DEATH_NOTIFICATION_DONE",
Steven Morelandf0212002018-12-26 13:59:23 -080090 "BR_FAILED_REPLY",
Hang Lub185ac02021-03-24 13:17:22 +080091 "BR_FROZEN_REPLY",
92 "BR_ONEWAY_SPAM_SUSPECT",
Steven Morelandf0212002018-12-26 13:59:23 -080093 "BR_TRANSACTION_SEC_CTX",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094};
95
96static const char *kCommandStrings[] = {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080097 "BC_TRANSACTION",
98 "BC_REPLY",
99 "BC_ACQUIRE_RESULT",
100 "BC_FREE_BUFFER",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101 "BC_INCREFS",
102 "BC_ACQUIRE",
103 "BC_RELEASE",
104 "BC_DECREFS",
105 "BC_INCREFS_DONE",
106 "BC_ACQUIRE_DONE",
107 "BC_ATTEMPT_ACQUIRE",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108 "BC_REGISTER_LOOPER",
109 "BC_ENTER_LOOPER",
110 "BC_EXIT_LOOPER",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800111 "BC_REQUEST_DEATH_NOTIFICATION",
112 "BC_CLEAR_DEATH_NOTIFICATION",
113 "BC_DEAD_BINDER_DONE"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800114};
115
Olivier Gaillard91a04802018-11-14 17:32:41 +0000116static const int64_t kWorkSourcePropagatedBitIndex = 32;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100117
songjinshi73a7dde2016-10-18 21:05:56 +0800118static const char* getReturnString(uint32_t cmd)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800119{
songjinshi8e486c62019-04-04 11:22:52 +0800120 size_t idx = cmd & _IOC_NRMASK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800121 if (idx < sizeof(kReturnStrings) / sizeof(kReturnStrings[0]))
122 return kReturnStrings[idx];
123 else
124 return "unknown";
125}
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127static const void* printBinderTransactionData(TextOutput& out, const void* data)
128{
129 const binder_transaction_data* btd =
130 (const binder_transaction_data*)data;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700131 if (btd->target.handle < 1024) {
132 /* want to print descriptors in decimal; guess based on value */
133 out << "target.desc=" << btd->target.handle;
134 } else {
135 out << "target.ptr=" << btd->target.ptr;
136 }
137 out << " (cookie " << btd->cookie << ")" << endl
Jiyong Park16c6e702020-11-13 20:53:12 +0900138 << "code=" << TypeCode(btd->code) << ", flags=" << (void*)(uint64_t)btd->flags << endl
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 << "data=" << btd->data.ptr.buffer << " (" << (void*)btd->data_size
140 << " bytes)" << endl
141 << "offsets=" << btd->data.ptr.offsets << " (" << (void*)btd->offsets_size
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700142 << " bytes)";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 return btd+1;
144}
145
146static const void* printReturnCommand(TextOutput& out, const void* _cmd)
147{
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700148 static const size_t N = sizeof(kReturnStrings)/sizeof(kReturnStrings[0]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800149 const int32_t* cmd = (const int32_t*)_cmd;
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100150 uint32_t code = (uint32_t)*cmd++;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700151 size_t cmdIndex = code & 0xff;
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100152 if (code == BR_ERROR) {
Jiyong Park16c6e702020-11-13 20:53:12 +0900153 out << "BR_ERROR: " << (void*)(uint64_t)(*cmd++) << endl;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800154 return cmd;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700155 } else if (cmdIndex >= N) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800156 out << "Unknown reply: " << code << endl;
157 return cmd;
158 }
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700159 out << kReturnStrings[cmdIndex];
Tim Murrayd429f4a2017-03-07 09:31:09 -0800160
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161 switch (code) {
162 case BR_TRANSACTION:
163 case BR_REPLY: {
164 out << ": " << indent;
165 cmd = (const int32_t *)printBinderTransactionData(out, cmd);
166 out << dedent;
167 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800168
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169 case BR_ACQUIRE_RESULT: {
170 const int32_t res = *cmd++;
171 out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
172 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800173
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174 case BR_INCREFS:
175 case BR_ACQUIRE:
176 case BR_RELEASE:
177 case BR_DECREFS: {
178 const int32_t b = *cmd++;
179 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900180 out << ": target=" << (void*)(uint64_t)b << " (cookie " << (void*)(uint64_t)c << ")";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800181 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800182
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183 case BR_ATTEMPT_ACQUIRE: {
184 const int32_t p = *cmd++;
185 const int32_t b = *cmd++;
186 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900187 out << ": target=" << (void*)(uint64_t)b << " (cookie " << (void*)(uint64_t)c
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800188 << "), pri=" << p;
189 } break;
190
191 case BR_DEAD_BINDER:
192 case BR_CLEAR_DEATH_NOTIFICATION_DONE: {
193 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900194 out << ": death cookie " << (void*)(uint64_t)c;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195 } break;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700196
197 default:
198 // no details to show for: BR_OK, BR_DEAD_REPLY,
199 // BR_TRANSACTION_COMPLETE, BR_FINISHED
200 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203 out << endl;
204 return cmd;
205}
206
207static const void* printCommand(TextOutput& out, const void* _cmd)
208{
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700209 static const size_t N = sizeof(kCommandStrings)/sizeof(kCommandStrings[0]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800210 const int32_t* cmd = (const int32_t*)_cmd;
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100211 uint32_t code = (uint32_t)*cmd++;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700212 size_t cmdIndex = code & 0xff;
213
214 if (cmdIndex >= N) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800215 out << "Unknown command: " << code << endl;
216 return cmd;
217 }
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700218 out << kCommandStrings[cmdIndex];
219
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220 switch (code) {
221 case BC_TRANSACTION:
222 case BC_REPLY: {
223 out << ": " << indent;
224 cmd = (const int32_t *)printBinderTransactionData(out, cmd);
225 out << dedent;
226 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800227
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228 case BC_ACQUIRE_RESULT: {
229 const int32_t res = *cmd++;
230 out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
231 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800232
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233 case BC_FREE_BUFFER: {
234 const int32_t buf = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900235 out << ": buffer=" << (void*)(uint64_t)buf;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800237
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800238 case BC_INCREFS:
239 case BC_ACQUIRE:
240 case BC_RELEASE:
241 case BC_DECREFS: {
242 const int32_t d = *cmd++;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700243 out << ": desc=" << d;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800245
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800246 case BC_INCREFS_DONE:
247 case BC_ACQUIRE_DONE: {
248 const int32_t b = *cmd++;
249 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900250 out << ": target=" << (void*)(uint64_t)b << " (cookie " << (void*)(uint64_t)c << ")";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800251 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800252
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 case BC_ATTEMPT_ACQUIRE: {
254 const int32_t p = *cmd++;
255 const int32_t d = *cmd++;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700256 out << ": desc=" << d << ", pri=" << p;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800258
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259 case BC_REQUEST_DEATH_NOTIFICATION:
260 case BC_CLEAR_DEATH_NOTIFICATION: {
261 const int32_t h = *cmd++;
262 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900263 out << ": handle=" << h << " (death cookie " << (void*)(uint64_t)c << ")";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800264 } break;
265
266 case BC_DEAD_BINDER_DONE: {
267 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900268 out << ": death cookie " << (void*)(uint64_t)c;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800269 } break;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700270
271 default:
272 // no details to show for: BC_REGISTER_LOOPER, BC_ENTER_LOOPER,
273 // BC_EXIT_LOOPER
274 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800276
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800277 out << endl;
278 return cmd;
279}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280
281static pthread_mutex_t gTLSMutex = PTHREAD_MUTEX_INITIALIZER;
Hans Boehma997b232019-04-12 16:59:00 -0700282static std::atomic<bool> gHaveTLS(false);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283static pthread_key_t gTLS = 0;
Hans Boehma997b232019-04-12 16:59:00 -0700284static std::atomic<bool> gShutdown = false;
285static std::atomic<bool> gDisableBackgroundScheduling = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286
287IPCThreadState* IPCThreadState::self()
288{
Hans Boehma997b232019-04-12 16:59:00 -0700289 if (gHaveTLS.load(std::memory_order_acquire)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290restart:
291 const pthread_key_t k = gTLS;
292 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
293 if (st) return st;
294 return new IPCThreadState;
295 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800296
Hans Boehma997b232019-04-12 16:59:00 -0700297 // Racey, heuristic test for simultaneous shutdown.
298 if (gShutdown.load(std::memory_order_relaxed)) {
Andreas Gampef31a3eb2016-02-01 13:21:56 -0800299 ALOGW("Calling IPCThreadState::self() during shutdown is dangerous, expect a crash.\n");
Yi Kongfdd8da92018-06-07 17:52:27 -0700300 return nullptr;
Andreas Gampef31a3eb2016-02-01 13:21:56 -0800301 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800302
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800303 pthread_mutex_lock(&gTLSMutex);
Hans Boehma997b232019-04-12 16:59:00 -0700304 if (!gHaveTLS.load(std::memory_order_relaxed)) {
Andreas Gampef31a3eb2016-02-01 13:21:56 -0800305 int key_create_value = pthread_key_create(&gTLS, threadDestructor);
306 if (key_create_value != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307 pthread_mutex_unlock(&gTLSMutex);
Andreas Gampef31a3eb2016-02-01 13:21:56 -0800308 ALOGW("IPCThreadState::self() unable to create TLS key, expect a crash: %s\n",
309 strerror(key_create_value));
Yi Kongfdd8da92018-06-07 17:52:27 -0700310 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800311 }
Hans Boehma997b232019-04-12 16:59:00 -0700312 gHaveTLS.store(true, std::memory_order_release);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800313 }
314 pthread_mutex_unlock(&gTLSMutex);
315 goto restart;
316}
317
Brad Fitzpatrick1b608432010-12-13 16:52:35 -0800318IPCThreadState* IPCThreadState::selfOrNull()
319{
Hans Boehma997b232019-04-12 16:59:00 -0700320 if (gHaveTLS.load(std::memory_order_acquire)) {
Brad Fitzpatrick1b608432010-12-13 16:52:35 -0800321 const pthread_key_t k = gTLS;
322 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
323 return st;
324 }
Yi Kongfdd8da92018-06-07 17:52:27 -0700325 return nullptr;
Brad Fitzpatrick1b608432010-12-13 16:52:35 -0800326}
327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800328void IPCThreadState::shutdown()
329{
Hans Boehma997b232019-04-12 16:59:00 -0700330 gShutdown.store(true, std::memory_order_relaxed);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800331
Hans Boehma997b232019-04-12 16:59:00 -0700332 if (gHaveTLS.load(std::memory_order_acquire)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800333 // XXX Need to wait for all thread pool threads to exit!
334 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(gTLS);
335 if (st) {
336 delete st;
Yi Kongfdd8da92018-06-07 17:52:27 -0700337 pthread_setspecific(gTLS, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 }
zhongjieff405782016-03-09 15:05:04 +0800339 pthread_key_delete(gTLS);
Hans Boehma997b232019-04-12 16:59:00 -0700340 gHaveTLS.store(false, std::memory_order_release);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800341 }
342}
343
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800344void IPCThreadState::disableBackgroundScheduling(bool disable)
345{
Hans Boehma997b232019-04-12 16:59:00 -0700346 gDisableBackgroundScheduling.store(disable, std::memory_order_relaxed);
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800347}
348
Martijn Coenen2b631742017-05-05 11:16:59 -0700349bool IPCThreadState::backgroundSchedulingDisabled()
350{
Hans Boehma997b232019-04-12 16:59:00 -0700351 return gDisableBackgroundScheduling.load(std::memory_order_relaxed);
Martijn Coenen2b631742017-05-05 11:16:59 -0700352}
353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354status_t IPCThreadState::clearLastError()
355{
356 const status_t err = mLastError;
357 mLastError = NO_ERROR;
358 return err;
359}
360
Dan Stoza9c634fd2014-11-26 12:23:23 -0800361pid_t IPCThreadState::getCallingPid() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800362{
Steven Moreland35626652021-05-15 01:32:04 +0000363 checkContextIsBinderForUse(__func__);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364 return mCallingPid;
365}
366
Steven Morelandf0212002018-12-26 13:59:23 -0800367const char* IPCThreadState::getCallingSid() const
368{
Steven Moreland35626652021-05-15 01:32:04 +0000369 checkContextIsBinderForUse(__func__);
Steven Morelandf0212002018-12-26 13:59:23 -0800370 return mCallingSid;
371}
372
Dan Stoza9c634fd2014-11-26 12:23:23 -0800373uid_t IPCThreadState::getCallingUid() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800374{
Steven Moreland35626652021-05-15 01:32:04 +0000375 checkContextIsBinderForUse(__func__);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376 return mCallingUid;
377}
378
Steven Moreland35626652021-05-15 01:32:04 +0000379const IPCThreadState::SpGuard* IPCThreadState::pushGetCallingSpGuard(const SpGuard* guard) {
380 const SpGuard* orig = mServingStackPointerGuard;
381 mServingStackPointerGuard = guard;
382 return orig;
383}
384
385void IPCThreadState::restoreGetCallingSpGuard(const SpGuard* guard) {
386 mServingStackPointerGuard = guard;
387}
388
389void IPCThreadState::checkContextIsBinderForUse(const char* use) const {
390 if (LIKELY(mServingStackPointerGuard == nullptr)) return;
391
392 if (!mServingStackPointer || mServingStackPointerGuard->address < mServingStackPointer) {
393 LOG_ALWAYS_FATAL("In context %s, %s does not make sense (binder sp: %p, guard: %p).",
394 mServingStackPointerGuard->context, use, mServingStackPointer,
395 mServingStackPointerGuard->address);
396 }
397
398 // in the case mServingStackPointer is deeper in the stack than the guard,
399 // we must be serving a binder transaction (maybe nested). This is a binder
400 // context, so we don't abort
401}
402
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800403int64_t IPCThreadState::clearCallingIdentity()
404{
Steven Morelandf0212002018-12-26 13:59:23 -0800405 // ignore mCallingSid for legacy reasons
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800406 int64_t token = ((int64_t)mCallingUid<<32) | mCallingPid;
407 clearCaller();
408 return token;
409}
410
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700411void IPCThreadState::setStrictModePolicy(int32_t policy)
412{
413 mStrictModePolicy = policy;
414}
415
Brad Fitzpatricka877cd82010-07-07 16:06:39 -0700416int32_t IPCThreadState::getStrictModePolicy() const
417{
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700418 return mStrictModePolicy;
419}
420
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000421int64_t IPCThreadState::setCallingWorkSourceUid(uid_t uid)
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100422{
Olivier Gaillard91a04802018-11-14 17:32:41 +0000423 int64_t token = setCallingWorkSourceUidWithoutPropagation(uid);
424 mPropagateWorkSource = true;
425 return token;
426}
427
428int64_t IPCThreadState::setCallingWorkSourceUidWithoutPropagation(uid_t uid)
429{
430 const int64_t propagatedBit = ((int64_t)mPropagateWorkSource) << kWorkSourcePropagatedBitIndex;
431 int64_t token = propagatedBit | mWorkSource;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100432 mWorkSource = uid;
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000433 return token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100434}
435
Olivier Gaillard91a04802018-11-14 17:32:41 +0000436void IPCThreadState::clearPropagateWorkSource()
437{
438 mPropagateWorkSource = false;
439}
440
441bool IPCThreadState::shouldPropagateWorkSource() const
442{
443 return mPropagateWorkSource;
444}
445
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000446uid_t IPCThreadState::getCallingWorkSourceUid() const
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100447{
448 return mWorkSource;
449}
450
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000451int64_t IPCThreadState::clearCallingWorkSource()
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100452{
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000453 return setCallingWorkSourceUid(kUnsetWorkSource);
454}
455
456void IPCThreadState::restoreCallingWorkSource(int64_t token)
457{
458 uid_t uid = (int)token;
Olivier Gaillard91a04802018-11-14 17:32:41 +0000459 setCallingWorkSourceUidWithoutPropagation(uid);
460 mPropagateWorkSource = ((token >> kWorkSourcePropagatedBitIndex) & 1) == 1;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100461}
462
Brad Fitzpatrick52736032010-08-30 16:01:16 -0700463void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
464{
465 mLastTransactionBinderFlags = flags;
466}
467
468int32_t IPCThreadState::getLastTransactionBinderFlags() const
469{
470 return mLastTransactionBinderFlags;
471}
472
Steven Moreland9514b202020-09-21 18:03:27 +0000473void IPCThreadState::setCallRestriction(ProcessState::CallRestriction restriction) {
474 mCallRestriction = restriction;
475}
476
477ProcessState::CallRestriction IPCThreadState::getCallRestriction() const {
478 return mCallRestriction;
479}
480
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800481void IPCThreadState::restoreCallingIdentity(int64_t token)
482{
483 mCallingUid = (int)(token>>32);
Steven Morelandf0212002018-12-26 13:59:23 -0800484 mCallingSid = nullptr; // not enough data to restore
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800485 mCallingPid = (int)token;
486}
487
488void IPCThreadState::clearCaller()
489{
Marco Nelissend43b1942009-07-17 07:59:17 -0700490 mCallingPid = getpid();
Steven Morelandf0212002018-12-26 13:59:23 -0800491 mCallingSid = nullptr; // expensive to lookup
Marco Nelissend43b1942009-07-17 07:59:17 -0700492 mCallingUid = getuid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800493}
494
495void IPCThreadState::flushCommands()
496{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -0200497 if (mProcess->mDriverFD < 0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800498 return;
499 talkWithDriver(false);
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700500 // The flush could have caused post-write refcount decrements to have
501 // been executed, which in turn could result in BC_RELEASE/BC_DECREFS
502 // being queued in mOut. So flush again, if we need to.
503 if (mOut.dataSize() > 0) {
504 talkWithDriver(false);
505 }
506 if (mOut.dataSize() > 0) {
507 ALOGW("mOut.dataSize() > 0 after flushCommands()");
508 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800509}
510
Martijn Coenen0442a862017-11-17 10:46:32 +0100511bool IPCThreadState::flushIfNeeded()
512{
Frankie Changf4c81372021-05-18 13:08:05 +0800513 if (mIsLooper || mServingStackPointer != nullptr || mIsFlushing) {
Martijn Coenen0442a862017-11-17 10:46:32 +0100514 return false;
515 }
Frankie Changf4c81372021-05-18 13:08:05 +0800516 mIsFlushing = true;
Martijn Coenen0442a862017-11-17 10:46:32 +0100517 // In case this thread is not a looper and is not currently serving a binder transaction,
518 // there's no guarantee that this thread will call back into the kernel driver any time
519 // soon. Therefore, flush pending commands such as BC_FREE_BUFFER, to prevent them from getting
520 // stuck in this thread's out buffer.
521 flushCommands();
Frankie Changf4c81372021-05-18 13:08:05 +0800522 mIsFlushing = false;
Martijn Coenen0442a862017-11-17 10:46:32 +0100523 return true;
524}
525
Wale Ogunwale376b8222015-04-13 16:16:10 -0700526void IPCThreadState::blockUntilThreadAvailable()
527{
528 pthread_mutex_lock(&mProcess->mThreadCountLock);
Steven Morelandc648a762021-01-16 02:39:45 +0000529 mProcess->mWaitingForThreads++;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700530 while (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads) {
Wale Ogunwalea3206e62015-04-21 12:29:50 -0700531 ALOGW("Waiting for thread to be free. mExecutingThreadsCount=%lu mMaxThreads=%lu\n",
532 static_cast<unsigned long>(mProcess->mExecutingThreadsCount),
533 static_cast<unsigned long>(mProcess->mMaxThreads));
Wale Ogunwale376b8222015-04-13 16:16:10 -0700534 pthread_cond_wait(&mProcess->mThreadCountDecrement, &mProcess->mThreadCountLock);
535 }
Steven Morelandc648a762021-01-16 02:39:45 +0000536 mProcess->mWaitingForThreads--;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700537 pthread_mutex_unlock(&mProcess->mThreadCountLock);
538}
539
Todd Poynor8d96cab2013-06-25 19:12:18 -0700540status_t IPCThreadState::getAndExecuteCommand()
541{
542 status_t result;
543 int32_t cmd;
544
545 result = talkWithDriver();
546 if (result >= NO_ERROR) {
547 size_t IN = mIn.dataAvail();
548 if (IN < sizeof(int32_t)) return result;
549 cmd = mIn.readInt32();
550 IF_LOG_COMMANDS() {
551 alog << "Processing top-level Command: "
552 << getReturnString(cmd) << endl;
553 }
554
Wale Ogunwale376b8222015-04-13 16:16:10 -0700555 pthread_mutex_lock(&mProcess->mThreadCountLock);
556 mProcess->mExecutingThreadsCount++;
Colin Cross96e83222016-04-15 14:29:55 -0700557 if (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads &&
558 mProcess->mStarvationStartTimeMs == 0) {
559 mProcess->mStarvationStartTimeMs = uptimeMillis();
560 }
Wale Ogunwale376b8222015-04-13 16:16:10 -0700561 pthread_mutex_unlock(&mProcess->mThreadCountLock);
562
Todd Poynor8d96cab2013-06-25 19:12:18 -0700563 result = executeCommand(cmd);
564
Wale Ogunwale376b8222015-04-13 16:16:10 -0700565 pthread_mutex_lock(&mProcess->mThreadCountLock);
566 mProcess->mExecutingThreadsCount--;
Colin Cross96e83222016-04-15 14:29:55 -0700567 if (mProcess->mExecutingThreadsCount < mProcess->mMaxThreads &&
568 mProcess->mStarvationStartTimeMs != 0) {
569 int64_t starvationTimeMs = uptimeMillis() - mProcess->mStarvationStartTimeMs;
570 if (starvationTimeMs > 100) {
571 ALOGE("binder thread pool (%zu threads) starved for %" PRId64 " ms",
572 mProcess->mMaxThreads, starvationTimeMs);
573 }
574 mProcess->mStarvationStartTimeMs = 0;
575 }
Steven Morelandc648a762021-01-16 02:39:45 +0000576
577 // Cond broadcast can be expensive, so don't send it every time a binder
578 // call is processed. b/168806193
579 if (mProcess->mWaitingForThreads > 0) {
580 pthread_cond_broadcast(&mProcess->mThreadCountDecrement);
581 }
Wale Ogunwale376b8222015-04-13 16:16:10 -0700582 pthread_mutex_unlock(&mProcess->mThreadCountLock);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700583 }
584
585 return result;
586}
587
588// When we've cleared the incoming command queue, process any pending derefs
589void IPCThreadState::processPendingDerefs()
590{
591 if (mIn.dataPosition() >= mIn.dataSize()) {
Martijn Coenen0791fbf2017-08-08 15:36:16 +0200592 /*
593 * The decWeak()/decStrong() calls may cause a destructor to run,
594 * which in turn could have initiated an outgoing transaction,
595 * which in turn could cause us to add to the pending refs
596 * vectors; so instead of simply iterating, loop until they're empty.
597 *
598 * We do this in an outer loop, because calling decStrong()
599 * may result in something being added to mPendingWeakDerefs,
600 * which could be delayed until the next incoming command
601 * from the driver if we don't process it now.
602 */
603 while (mPendingWeakDerefs.size() > 0 || mPendingStrongDerefs.size() > 0) {
604 while (mPendingWeakDerefs.size() > 0) {
605 RefBase::weakref_type* refs = mPendingWeakDerefs[0];
606 mPendingWeakDerefs.removeAt(0);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700607 refs->decWeak(mProcess.get());
608 }
Todd Poynor8d96cab2013-06-25 19:12:18 -0700609
Martijn Coenen0791fbf2017-08-08 15:36:16 +0200610 if (mPendingStrongDerefs.size() > 0) {
611 // We don't use while() here because we don't want to re-order
612 // strong and weak decs at all; if this decStrong() causes both a
613 // decWeak() and a decStrong() to be queued, we want to process
614 // the decWeak() first.
615 BBinder* obj = mPendingStrongDerefs[0];
616 mPendingStrongDerefs.removeAt(0);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700617 obj->decStrong(mProcess.get());
618 }
Todd Poynor8d96cab2013-06-25 19:12:18 -0700619 }
620 }
621}
622
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700623void IPCThreadState::processPostWriteDerefs()
624{
625 for (size_t i = 0; i < mPostWriteWeakDerefs.size(); i++) {
626 RefBase::weakref_type* refs = mPostWriteWeakDerefs[i];
627 refs->decWeak(mProcess.get());
628 }
629 mPostWriteWeakDerefs.clear();
630
631 for (size_t i = 0; i < mPostWriteStrongDerefs.size(); i++) {
632 RefBase* obj = mPostWriteStrongDerefs[i];
633 obj->decStrong(mProcess.get());
634 }
635 mPostWriteStrongDerefs.clear();
636}
637
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800638void IPCThreadState::joinThreadPool(bool isMain)
639{
640 LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
641
642 mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800643
Martijn Coenen0442a862017-11-17 10:46:32 +0100644 mIsLooper = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800645 status_t result;
646 do {
Todd Poynor8d96cab2013-06-25 19:12:18 -0700647 processPendingDerefs();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800648 // now get the next command to be processed, waiting if necessary
Todd Poynor8d96cab2013-06-25 19:12:18 -0700649 result = getAndExecuteCommand();
Jason Parksdcd39582009-11-03 12:14:38 -0800650
Todd Poynor8d96cab2013-06-25 19:12:18 -0700651 if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
Steven Moreland6adf33c2019-09-25 13:18:09 -0700652 LOG_ALWAYS_FATAL("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
Jeff Tinkeref073862013-06-11 11:30:21 -0700653 mProcess->mDriverFD, result);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800654 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800655
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800656 // Let this thread exit the thread pool if it is no longer
657 // needed and it is not the main process thread.
658 if(result == TIMED_OUT && !isMain) {
659 break;
660 }
661 } while (result != -ECONNREFUSED && result != -EBADF);
662
Wei Wangc7341432016-10-19 10:23:59 -0700663 LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%d\n",
664 (void*)pthread_self(), getpid(), result);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800665
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800666 mOut.writeInt32(BC_EXIT_LOOPER);
Martijn Coenen0442a862017-11-17 10:46:32 +0100667 mIsLooper = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800668 talkWithDriver(false);
669}
670
Steven Morelandd8c85672020-07-24 21:30:41 +0000671status_t IPCThreadState::setupPolling(int* fd)
Todd Poynor8d96cab2013-06-25 19:12:18 -0700672{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -0200673 if (mProcess->mDriverFD < 0) {
Todd Poynor8d96cab2013-06-25 19:12:18 -0700674 return -EBADF;
675 }
676
677 mOut.writeInt32(BC_ENTER_LOOPER);
Steven Morelandf210b502021-01-15 23:40:32 +0000678 flushCommands();
Todd Poynor8d96cab2013-06-25 19:12:18 -0700679 *fd = mProcess->mDriverFD;
680 return 0;
681}
682
683status_t IPCThreadState::handlePolledCommands()
684{
685 status_t result;
686
687 do {
688 result = getAndExecuteCommand();
689 } while (mIn.dataPosition() < mIn.dataSize());
690
691 processPendingDerefs();
692 flushCommands();
693 return result;
694}
695
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800696void IPCThreadState::stopProcess(bool /*immediate*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800697{
Steve Blocka19954a2012-01-04 20:05:49 +0000698 //ALOGI("**** STOPPING PROCESS");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800699 flushCommands();
700 int fd = mProcess->mDriverFD;
701 mProcess->mDriverFD = -1;
702 close(fd);
703 //kill(getpid(), SIGKILL);
704}
705
706status_t IPCThreadState::transact(int32_t handle,
707 uint32_t code, const Parcel& data,
708 Parcel* reply, uint32_t flags)
709{
Steven Moreland5553ac42020-11-11 02:14:45 +0000710 LOG_ALWAYS_FATAL_IF(data.isForRpc(), "Parcel constructed for RPC, but being used with binder.");
711
Ganesh Mahendran58e5daa2017-10-11 18:05:13 +0800712 status_t err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800713
714 flags |= TF_ACCEPT_FDS;
715
716 IF_LOG_TRANSACTIONS() {
717 TextOutput::Bundle _b(alog);
718 alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
719 << handle << " / code " << TypeCode(code) << ": "
720 << indent << data << dedent << endl;
721 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800722
Ganesh Mahendran58e5daa2017-10-11 18:05:13 +0800723 LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
724 (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
Yi Kongfdd8da92018-06-07 17:52:27 -0700725 err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, nullptr);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800726
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800727 if (err != NO_ERROR) {
728 if (reply) reply->setError(err);
729 return (mLastError = err);
730 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800731
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800732 if ((flags & TF_ONE_WAY) == 0) {
Steven Moreland7732a092019-01-02 17:54:16 -0800733 if (UNLIKELY(mCallRestriction != ProcessState::CallRestriction::NONE)) {
734 if (mCallRestriction == ProcessState::CallRestriction::ERROR_IF_NOT_ONEWAY) {
Steven Moreland8cb34fc2019-05-13 11:44:55 -0700735 ALOGE("Process making non-oneway call (code: %u) but is restricted.", code);
Steven Moreland7732a092019-01-02 17:54:16 -0800736 CallStack::logStack("non-oneway call", CallStack::getCurrent(10).get(),
737 ANDROID_LOG_ERROR);
738 } else /* FATAL_IF_NOT_ONEWAY */ {
Steven Morelandfcc77f12020-09-01 01:16:11 +0000739 LOG_ALWAYS_FATAL("Process may not make non-oneway calls (code: %u).", code);
Steven Moreland7732a092019-01-02 17:54:16 -0800740 }
741 }
742
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700743 #if 0
744 if (code == 4) { // relayout
Steve Blocka19954a2012-01-04 20:05:49 +0000745 ALOGI(">>>>>> CALLING transaction 4");
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700746 } else {
Steve Blocka19954a2012-01-04 20:05:49 +0000747 ALOGI(">>>>>> CALLING transaction %d", code);
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700748 }
749 #endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800750 if (reply) {
751 err = waitForResponse(reply);
752 } else {
753 Parcel fakeReply;
754 err = waitForResponse(&fakeReply);
755 }
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700756 #if 0
757 if (code == 4) { // relayout
Steve Blocka19954a2012-01-04 20:05:49 +0000758 ALOGI("<<<<<< RETURNING transaction 4");
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700759 } else {
Steve Blocka19954a2012-01-04 20:05:49 +0000760 ALOGI("<<<<<< RETURNING transaction %d", code);
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700761 }
762 #endif
Tim Murrayd429f4a2017-03-07 09:31:09 -0800763
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800764 IF_LOG_TRANSACTIONS() {
765 TextOutput::Bundle _b(alog);
766 alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
767 << handle << ": ";
768 if (reply) alog << indent << *reply << dedent << endl;
769 else alog << "(none requested)" << endl;
770 }
771 } else {
Yi Kongfdd8da92018-06-07 17:52:27 -0700772 err = waitForResponse(nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800773 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800774
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800775 return err;
776}
777
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700778void IPCThreadState::incStrongHandle(int32_t handle, BpBinder *proxy)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800779{
780 LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
781 mOut.writeInt32(BC_ACQUIRE);
782 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100783 if (!flushIfNeeded()) {
784 // Create a temp reference until the driver has handled this command.
785 proxy->incStrong(mProcess.get());
786 mPostWriteStrongDerefs.push(proxy);
787 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800788}
789
790void IPCThreadState::decStrongHandle(int32_t handle)
791{
792 LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
793 mOut.writeInt32(BC_RELEASE);
794 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100795 flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800796}
797
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700798void IPCThreadState::incWeakHandle(int32_t handle, BpBinder *proxy)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800799{
800 LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
801 mOut.writeInt32(BC_INCREFS);
802 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100803 if (!flushIfNeeded()) {
804 // Create a temp reference until the driver has handled this command.
805 proxy->getWeakRefs()->incWeak(mProcess.get());
806 mPostWriteWeakDerefs.push(proxy->getWeakRefs());
807 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800808}
809
810void IPCThreadState::decWeakHandle(int32_t handle)
811{
812 LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
813 mOut.writeInt32(BC_DECREFS);
814 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100815 flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800816}
817
818status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
819{
Arve HjønnevÄg11cfdcc2014-02-14 20:14:02 -0800820#if HAS_BC_ATTEMPT_ACQUIRE
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700821 LOG_REMOTEREFS("IPCThreadState::attemptIncStrongHandle(%d)\n", handle);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800822 mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
823 mOut.writeInt32(0); // xxx was thread priority
824 mOut.writeInt32(handle);
825 status_t result = UNKNOWN_ERROR;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800826
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800827 waitForResponse(NULL, &result);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800828
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800829#if LOG_REFCOUNTS
liangweikanga43ee152016-10-25 16:37:54 +0800830 ALOGV("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800831 handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
832#endif
Tim Murrayd429f4a2017-03-07 09:31:09 -0800833
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800834 return result;
Arve HjønnevÄg11cfdcc2014-02-14 20:14:02 -0800835#else
836 (void)handle;
837 ALOGE("%s(%d): Not supported\n", __func__, handle);
838 return INVALID_OPERATION;
839#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800840}
841
842void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
843{
844#if LOG_REFCOUNTS
liangweikanga43ee152016-10-25 16:37:54 +0800845 ALOGV("IPCThreadState::expungeHandle(%ld)\n", handle);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800846#endif
Manoj Gupta9cec85b2017-09-19 16:34:29 -0700847 self()->mProcess->expungeHandle(handle, binder); // NOLINT
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800848}
849
850status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
851{
852 mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
853 mOut.writeInt32((int32_t)handle);
Serban Constantinescuf683e012013-11-05 16:53:55 +0000854 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800855 return NO_ERROR;
856}
857
858status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
859{
860 mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
861 mOut.writeInt32((int32_t)handle);
Serban Constantinescuf683e012013-11-05 16:53:55 +0000862 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800863 return NO_ERROR;
864}
865
866IPCThreadState::IPCThreadState()
Steven Moreland35626652021-05-15 01:32:04 +0000867 : mProcess(ProcessState::self()),
868 mServingStackPointer(nullptr),
869 mServingStackPointerGuard(nullptr),
870 mWorkSource(kUnsetWorkSource),
871 mPropagateWorkSource(false),
872 mIsLooper(false),
Frankie Changf4c81372021-05-18 13:08:05 +0800873 mIsFlushing(false),
Steven Moreland35626652021-05-15 01:32:04 +0000874 mStrictModePolicy(0),
875 mLastTransactionBinderFlags(0),
876 mCallRestriction(mProcess->mCallRestriction) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800877 pthread_setspecific(gTLS, this);
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800878 clearCaller();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800879 mIn.setDataCapacity(256);
880 mOut.setDataCapacity(256);
881}
882
883IPCThreadState::~IPCThreadState()
884{
885}
886
Martijn Coenenea0090a2017-11-02 18:54:40 +0000887status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
888{
889 status_t err;
890 status_t statusBuffer;
891 err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
892 if (err < NO_ERROR) return err;
893
Yi Kongfdd8da92018-06-07 17:52:27 -0700894 return waitForResponse(nullptr, nullptr);
Martijn Coenenea0090a2017-11-02 18:54:40 +0000895}
896
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800897status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
898{
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100899 uint32_t cmd;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800900 int32_t err;
901
902 while (1) {
903 if ((err=talkWithDriver()) < NO_ERROR) break;
904 err = mIn.errorCheck();
905 if (err < NO_ERROR) break;
906 if (mIn.dataAvail() == 0) continue;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800907
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100908 cmd = (uint32_t)mIn.readInt32();
Tim Murrayd429f4a2017-03-07 09:31:09 -0800909
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800910 IF_LOG_COMMANDS() {
911 alog << "Processing waitForResponse Command: "
912 << getReturnString(cmd) << endl;
913 }
914
915 switch (cmd) {
Hang Lub185ac02021-03-24 13:17:22 +0800916 case BR_ONEWAY_SPAM_SUSPECT:
917 ALOGE("Process seems to be sending too many oneway calls.");
918 CallStack::logStack("oneway spamming", CallStack::getCurrent().get(),
919 ANDROID_LOG_ERROR);
920 [[fallthrough]];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800921 case BR_TRANSACTION_COMPLETE:
922 if (!reply && !acquireResult) goto finish;
923 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800924
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800925 case BR_DEAD_REPLY:
926 err = DEAD_OBJECT;
927 goto finish;
928
929 case BR_FAILED_REPLY:
930 err = FAILED_TRANSACTION;
931 goto finish;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800932
Marco Ballesio7ee17572020-09-08 10:30:03 -0700933 case BR_FROZEN_REPLY:
934 err = FAILED_TRANSACTION;
935 goto finish;
936
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800937 case BR_ACQUIRE_RESULT:
938 {
Steve Block67263472012-01-09 18:35:44 +0000939 ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800940 const int32_t result = mIn.readInt32();
941 if (!acquireResult) continue;
942 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
943 }
944 goto finish;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800945
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800946 case BR_REPLY:
947 {
948 binder_transaction_data tr;
949 err = mIn.read(&tr, sizeof(tr));
Steve Block67263472012-01-09 18:35:44 +0000950 ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800951 if (err != NO_ERROR) goto finish;
952
953 if (reply) {
954 if ((tr.flags & TF_STATUS_CODE) == 0) {
955 reply->ipcSetDataReference(
956 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
957 tr.data_size,
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800958 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
959 tr.offsets_size/sizeof(binder_size_t),
Steven Moreland161fe122020-11-12 23:16:47 +0000960 freeBuffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800961 } else {
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800962 err = *reinterpret_cast<const status_t*>(tr.data.ptr.buffer);
Yi Kongfdd8da92018-06-07 17:52:27 -0700963 freeBuffer(nullptr,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800964 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
965 tr.data_size,
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800966 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
Steven Moreland161fe122020-11-12 23:16:47 +0000967 tr.offsets_size/sizeof(binder_size_t));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800968 }
969 } else {
Yi Kongfdd8da92018-06-07 17:52:27 -0700970 freeBuffer(nullptr,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800971 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
972 tr.data_size,
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800973 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
Steven Moreland161fe122020-11-12 23:16:47 +0000974 tr.offsets_size/sizeof(binder_size_t));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800975 continue;
976 }
977 }
978 goto finish;
979
980 default:
981 err = executeCommand(cmd);
982 if (err != NO_ERROR) goto finish;
983 break;
984 }
985 }
986
987finish:
988 if (err != NO_ERROR) {
989 if (acquireResult) *acquireResult = err;
990 if (reply) reply->setError(err);
991 mLastError = err;
Carlos Llamasb235b122021-12-20 06:38:44 -0800992 logExtendedError();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800993 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800994
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800995 return err;
996}
997
998status_t IPCThreadState::talkWithDriver(bool doReceive)
999{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -02001000 if (mProcess->mDriverFD < 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +01001001 return -EBADF;
1002 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001003
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001004 binder_write_read bwr;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001005
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001006 // Is the read buffer empty?
1007 const bool needRead = mIn.dataPosition() >= mIn.dataSize();
Tim Murrayd429f4a2017-03-07 09:31:09 -08001008
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001009 // We don't want to write anything if we are still reading
1010 // from data left in the input buffer and the caller
1011 // has requested to read the next data.
1012 const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001013
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001014 bwr.write_size = outAvail;
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001015 bwr.write_buffer = (uintptr_t)mOut.data();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001016
1017 // This is what we'll read.
1018 if (doReceive && needRead) {
1019 bwr.read_size = mIn.dataCapacity();
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001020 bwr.read_buffer = (uintptr_t)mIn.data();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001021 } else {
1022 bwr.read_size = 0;
Ben Chengd640f892011-12-01 17:11:32 -08001023 bwr.read_buffer = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001024 }
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001025
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001026 IF_LOG_COMMANDS() {
1027 TextOutput::Bundle _b(alog);
1028 if (outAvail != 0) {
1029 alog << "Sending commands to driver: " << indent;
1030 const void* cmds = (const void*)bwr.write_buffer;
1031 const void* end = ((const uint8_t*)cmds)+bwr.write_size;
1032 alog << HexDump(cmds, bwr.write_size) << endl;
1033 while (cmds < end) cmds = printCommand(alog, cmds);
1034 alog << dedent;
1035 }
1036 alog << "Size of receive buffer: " << bwr.read_size
1037 << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
1038 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001039
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001040 // Return immediately if there is nothing to do.
1041 if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001042
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001043 bwr.write_consumed = 0;
1044 bwr.read_consumed = 0;
1045 status_t err;
1046 do {
1047 IF_LOG_COMMANDS() {
1048 alog << "About to read/write, write size = " << mOut.dataSize() << endl;
1049 }
Elliott Hughes6071da72015-08-12 15:27:47 -07001050#if defined(__ANDROID__)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001051 if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
1052 err = NO_ERROR;
1053 else
1054 err = -errno;
1055#else
1056 err = INVALID_OPERATION;
1057#endif
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -02001058 if (mProcess->mDriverFD < 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +01001059 err = -EBADF;
1060 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001061 IF_LOG_COMMANDS() {
1062 alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
1063 }
1064 } while (err == -EINTR);
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001065
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001066 IF_LOG_COMMANDS() {
Colin Cross6f4f3ab2014-02-05 17:42:44 -08001067 alog << "Our err: " << (void*)(intptr_t)err << ", write consumed: "
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001068 << bwr.write_consumed << " (of " << mOut.dataSize()
Todd Poynor8d96cab2013-06-25 19:12:18 -07001069 << "), read consumed: " << bwr.read_consumed << endl;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001070 }
1071
1072 if (err >= NO_ERROR) {
1073 if (bwr.write_consumed > 0) {
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001074 if (bwr.write_consumed < mOut.dataSize())
Steven Morelandb077deb2020-04-16 16:22:52 -07001075 LOG_ALWAYS_FATAL("Driver did not consume write buffer. "
1076 "err: %s consumed: %zu of %zu",
1077 statusToString(err).c_str(),
1078 (size_t)bwr.write_consumed,
1079 mOut.dataSize());
Martijn Coenen7c170bb2018-05-04 17:28:55 -07001080 else {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001081 mOut.setDataSize(0);
Martijn Coenen7c170bb2018-05-04 17:28:55 -07001082 processPostWriteDerefs();
1083 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001084 }
1085 if (bwr.read_consumed > 0) {
1086 mIn.setDataSize(bwr.read_consumed);
1087 mIn.setDataPosition(0);
1088 }
1089 IF_LOG_COMMANDS() {
1090 TextOutput::Bundle _b(alog);
1091 alog << "Remaining data size: " << mOut.dataSize() << endl;
1092 alog << "Received commands from driver: " << indent;
1093 const void* cmds = mIn.data();
1094 const void* end = mIn.data() + mIn.dataSize();
1095 alog << HexDump(cmds, mIn.dataSize()) << endl;
1096 while (cmds < end) cmds = printReturnCommand(alog, cmds);
1097 alog << dedent;
1098 }
1099 return NO_ERROR;
1100 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001102 return err;
1103}
1104
1105status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
1106 int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
1107{
1108 binder_transaction_data tr;
1109
Arve HjønnevÄg07fd0f12014-02-18 21:10:29 -08001110 tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001111 tr.target.handle = handle;
1112 tr.code = code;
1113 tr.flags = binderFlags;
Evgeniy Stepanovd5474322011-04-21 14:15:00 +04001114 tr.cookie = 0;
1115 tr.sender_pid = 0;
1116 tr.sender_euid = 0;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001117
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001118 const status_t err = data.errorCheck();
1119 if (err == NO_ERROR) {
1120 tr.data_size = data.ipcDataSize();
1121 tr.data.ptr.buffer = data.ipcData();
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001122 tr.offsets_size = data.ipcObjectsCount()*sizeof(binder_size_t);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001123 tr.data.ptr.offsets = data.ipcObjects();
1124 } else if (statusBuffer) {
1125 tr.flags |= TF_STATUS_CODE;
1126 *statusBuffer = err;
1127 tr.data_size = sizeof(status_t);
Arve HjønnevÄg87b30d02014-02-18 21:04:31 -08001128 tr.data.ptr.buffer = reinterpret_cast<uintptr_t>(statusBuffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001129 tr.offsets_size = 0;
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001130 tr.data.ptr.offsets = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001131 } else {
1132 return (mLastError = err);
1133 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001134
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001135 mOut.writeInt32(cmd);
1136 mOut.write(&tr, sizeof(tr));
Tim Murrayd429f4a2017-03-07 09:31:09 -08001137
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001138 return NO_ERROR;
1139}
1140
1141sp<BBinder> the_context_object;
1142
Jiyong Park384328e2020-11-13 17:16:48 +09001143void IPCThreadState::setTheContextObject(const sp<BBinder>& obj)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001144{
1145 the_context_object = obj;
1146}
1147
1148status_t IPCThreadState::executeCommand(int32_t cmd)
1149{
1150 BBinder* obj;
1151 RefBase::weakref_type* refs;
1152 status_t result = NO_ERROR;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001153
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +01001154 switch ((uint32_t)cmd) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001155 case BR_ERROR:
1156 result = mIn.readInt32();
1157 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001158
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001159 case BR_OK:
1160 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001161
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001162 case BR_ACQUIRE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001163 refs = (RefBase::weakref_type*)mIn.readPointer();
1164 obj = (BBinder*)mIn.readPointer();
Steve Block67263472012-01-09 18:35:44 +00001165 ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001166 "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
1167 refs, obj, refs->refBase());
1168 obj->incStrong(mProcess.get());
1169 IF_LOG_REMOTEREFS() {
1170 LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
1171 obj->printRefs();
1172 }
1173 mOut.writeInt32(BC_ACQUIRE_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001174 mOut.writePointer((uintptr_t)refs);
1175 mOut.writePointer((uintptr_t)obj);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001176 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001177
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001178 case BR_RELEASE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001179 refs = (RefBase::weakref_type*)mIn.readPointer();
1180 obj = (BBinder*)mIn.readPointer();
Steve Block67263472012-01-09 18:35:44 +00001181 ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001182 "BR_RELEASE: object %p does not match cookie %p (expected %p)",
1183 refs, obj, refs->refBase());
1184 IF_LOG_REMOTEREFS() {
1185 LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
1186 obj->printRefs();
1187 }
1188 mPendingStrongDerefs.push(obj);
1189 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001190
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001191 case BR_INCREFS:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001192 refs = (RefBase::weakref_type*)mIn.readPointer();
1193 obj = (BBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001194 refs->incWeak(mProcess.get());
1195 mOut.writeInt32(BC_INCREFS_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001196 mOut.writePointer((uintptr_t)refs);
1197 mOut.writePointer((uintptr_t)obj);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001198 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001199
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001200 case BR_DECREFS:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001201 refs = (RefBase::weakref_type*)mIn.readPointer();
Jiyong Park5970d0a2022-03-08 16:56:13 +09001202 // NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores)
1203 obj = (BBinder*)mIn.readPointer(); // consume
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001204 // NOTE: This assertion is not valid, because the object may no
1205 // longer exist (thus the (BBinder*)cast above resulting in a different
1206 // memory address).
Steve Block67263472012-01-09 18:35:44 +00001207 //ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001208 // "BR_DECREFS: object %p does not match cookie %p (expected %p)",
1209 // refs, obj, refs->refBase());
1210 mPendingWeakDerefs.push(refs);
1211 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001212
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001213 case BR_ATTEMPT_ACQUIRE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001214 refs = (RefBase::weakref_type*)mIn.readPointer();
1215 obj = (BBinder*)mIn.readPointer();
Tim Murrayd429f4a2017-03-07 09:31:09 -08001216
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001217 {
1218 const bool success = refs->attemptIncStrong(mProcess.get());
Steve Block67263472012-01-09 18:35:44 +00001219 ALOG_ASSERT(success && refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001220 "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
1221 refs, obj, refs->refBase());
Tim Murrayd429f4a2017-03-07 09:31:09 -08001222
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001223 mOut.writeInt32(BC_ACQUIRE_RESULT);
1224 mOut.writeInt32((int32_t)success);
1225 }
1226 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001227
Steven Morelandf0212002018-12-26 13:59:23 -08001228 case BR_TRANSACTION_SEC_CTX:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001229 case BR_TRANSACTION:
1230 {
Steven Morelandf0212002018-12-26 13:59:23 -08001231 binder_transaction_data_secctx tr_secctx;
1232 binder_transaction_data& tr = tr_secctx.transaction_data;
1233
1234 if (cmd == (int) BR_TRANSACTION_SEC_CTX) {
1235 result = mIn.read(&tr_secctx, sizeof(tr_secctx));
1236 } else {
1237 result = mIn.read(&tr, sizeof(tr));
1238 tr_secctx.secctx = 0;
1239 }
1240
Steve Block67263472012-01-09 18:35:44 +00001241 ALOG_ASSERT(result == NO_ERROR,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001242 "Not enough command data for brTRANSACTION");
1243 if (result != NO_ERROR) break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001244
Martijn Coenenea0090a2017-11-02 18:54:40 +00001245 Parcel buffer;
1246 buffer.ipcSetDataReference(
1247 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1248 tr.data_size,
1249 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
Steven Moreland161fe122020-11-12 23:16:47 +00001250 tr.offsets_size/sizeof(binder_size_t), freeBuffer);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001251
Steven Moreland39d887d2020-01-31 14:56:45 -08001252 const void* origServingStackPointer = mServingStackPointer;
Steven Moreland35626652021-05-15 01:32:04 +00001253 mServingStackPointer = __builtin_frame_address(0);
Steven Moreland39d887d2020-01-31 14:56:45 -08001254
Martijn Coenenea0090a2017-11-02 18:54:40 +00001255 const pid_t origPid = mCallingPid;
Steven Morelandf0212002018-12-26 13:59:23 -08001256 const char* origSid = mCallingSid;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001257 const uid_t origUid = mCallingUid;
1258 const int32_t origStrictModePolicy = mStrictModePolicy;
1259 const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001260 const int32_t origWorkSource = mWorkSource;
1261 const bool origPropagateWorkSet = mPropagateWorkSource;
1262 // Calling work source will be set by Parcel#enforceInterface. Parcel#enforceInterface
1263 // is only guaranteed to be called for AIDL-generated stubs so we reset the work source
1264 // here to never propagate it.
1265 clearCallingWorkSource();
1266 clearPropagateWorkSource();
Martijn Coenenea0090a2017-11-02 18:54:40 +00001267
1268 mCallingPid = tr.sender_pid;
Steven Morelandf0212002018-12-26 13:59:23 -08001269 mCallingSid = reinterpret_cast<const char*>(tr_secctx.secctx);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001270 mCallingUid = tr.sender_euid;
1271 mLastTransactionBinderFlags = tr.flags;
1272
Steven Morelandf0212002018-12-26 13:59:23 -08001273 // ALOGI(">>>> TRANSACT from pid %d sid %s uid %d\n", mCallingPid,
1274 // (mCallingSid ? mCallingSid : "<N/A>"), mCallingUid);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001275
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001276 Parcel reply;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001277 status_t error;
1278 IF_LOG_TRANSACTIONS() {
1279 TextOutput::Bundle _b(alog);
1280 alog << "BR_TRANSACTION thr " << (void*)pthread_self()
1281 << " / obj " << tr.target.ptr << " / code "
1282 << TypeCode(tr.code) << ": " << indent << buffer
1283 << dedent << endl
1284 << "Data addr = "
1285 << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1286 << ", offsets addr="
1287 << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
1288 }
1289 if (tr.target.ptr) {
1290 // We only have a weak reference on the target object, so we must first try to
1291 // safely acquire a strong reference before doing anything else with it.
1292 if (reinterpret_cast<RefBase::weakref_type*>(
1293 tr.target.ptr)->attemptIncStrong(this)) {
1294 error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,
1295 &reply, tr.flags);
1296 reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);
Dianne Hackbornc1114612016-03-21 10:36:54 -07001297 } else {
Martijn Coenenea0090a2017-11-02 18:54:40 +00001298 error = UNKNOWN_TRANSACTION;
Dianne Hackbornc1114612016-03-21 10:36:54 -07001299 }
Brad Fitzpatrick52736032010-08-30 16:01:16 -07001300
Martijn Coenenea0090a2017-11-02 18:54:40 +00001301 } else {
1302 error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001303 }
Dianne Hackborn5ee2c9d2014-09-30 11:30:03 -07001304
Steven Morelandf0212002018-12-26 13:59:23 -08001305 //ALOGI("<<<< TRANSACT from pid %d restore pid %d sid %s uid %d\n",
1306 // mCallingPid, origPid, (origSid ? origSid : "<N/A>"), origUid);
Tim Murrayd429f4a2017-03-07 09:31:09 -08001307
Martijn Coenenea0090a2017-11-02 18:54:40 +00001308 if ((tr.flags & TF_ONE_WAY) == 0) {
1309 LOG_ONEWAY("Sending reply to %d!", mCallingPid);
1310 if (error < NO_ERROR) reply.setError(error);
Steven Morelandf183fdd2020-10-27 00:12:12 +00001311
1312 constexpr uint32_t kForwardReplyFlags = TF_CLEAR_BUF;
1313 sendReply(reply, (tr.flags & kForwardReplyFlags));
Martijn Coenenea0090a2017-11-02 18:54:40 +00001314 } else {
Steven Moreland80844f72020-12-12 02:06:08 +00001315 if (error != OK) {
1316 alog << "oneway function results for code " << tr.code
1317 << " on binder at "
1318 << reinterpret_cast<void*>(tr.target.ptr)
1319 << " will be dropped but finished with status "
1320 << statusToString(error);
1321
1322 // ideally we could log this even when error == OK, but it
1323 // causes too much logspam because some manually-written
1324 // interfaces have clients that call methods which always
1325 // write results, sometimes as oneway methods.
1326 if (reply.dataSize() != 0) {
1327 alog << " and reply parcel size " << reply.dataSize();
1328 }
1329
1330 alog << endl;
Steven Morelandce66b8a2020-02-10 14:43:14 -08001331 }
Martijn Coenenea0090a2017-11-02 18:54:40 +00001332 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1333 }
1334
Steven Moreland39d887d2020-01-31 14:56:45 -08001335 mServingStackPointer = origServingStackPointer;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001336 mCallingPid = origPid;
Steven Morelandf0212002018-12-26 13:59:23 -08001337 mCallingSid = origSid;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001338 mCallingUid = origUid;
1339 mStrictModePolicy = origStrictModePolicy;
1340 mLastTransactionBinderFlags = origTransactionBinderFlags;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001341 mWorkSource = origWorkSource;
1342 mPropagateWorkSource = origPropagateWorkSet;
Christopher Tate440fd872010-03-18 17:55:03 -07001343
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001344 IF_LOG_TRANSACTIONS() {
1345 TextOutput::Bundle _b(alog);
1346 alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
1347 << tr.target.ptr << ": " << indent << reply << dedent << endl;
1348 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001349
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001350 }
1351 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001352
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001353 case BR_DEAD_BINDER:
1354 {
Serban Constantinescuf683e012013-11-05 16:53:55 +00001355 BpBinder *proxy = (BpBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001356 proxy->sendObituary();
1357 mOut.writeInt32(BC_DEAD_BINDER_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001358 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001359 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001360
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001361 case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1362 {
Serban Constantinescuf683e012013-11-05 16:53:55 +00001363 BpBinder *proxy = (BpBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001364 proxy->getWeakRefs()->decWeak(proxy);
1365 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001366
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001367 case BR_FINISHED:
1368 result = TIMED_OUT;
1369 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001370
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001371 case BR_NOOP:
1372 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001373
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001374 case BR_SPAWN_LOOPER:
1375 mProcess->spawnPooledThread(false);
1376 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001377
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001378 default:
liangweikanga43ee152016-10-25 16:37:54 +08001379 ALOGE("*** BAD COMMAND %d received from Binder driver\n", cmd);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001380 result = UNKNOWN_ERROR;
1381 break;
1382 }
1383
1384 if (result != NO_ERROR) {
1385 mLastError = result;
1386 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001387
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001388 return result;
1389}
1390
Steven Moreland39d887d2020-01-31 14:56:45 -08001391const void* IPCThreadState::getServingStackPointer() const {
1392 return mServingStackPointer;
Jayant Chowdharydac6dc82018-10-01 22:52:44 +00001393}
1394
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001395void IPCThreadState::threadDestructor(void *st)
1396{
Todd Poynor8d96cab2013-06-25 19:12:18 -07001397 IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1398 if (self) {
1399 self->flushCommands();
Elliott Hughes6071da72015-08-12 15:27:47 -07001400#if defined(__ANDROID__)
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -02001401 if (self->mProcess->mDriverFD >= 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +01001402 ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1403 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001404#endif
Todd Poynor8d96cab2013-06-25 19:12:18 -07001405 delete self;
1406 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001407}
1408
Li Li6f059292021-09-10 09:59:30 -07001409status_t IPCThreadState::getProcessFreezeInfo(pid_t pid, uint32_t *sync_received,
1410 uint32_t *async_received)
1411{
1412 int ret = 0;
Jiyong Park5970d0a2022-03-08 16:56:13 +09001413 binder_frozen_status_info info = {};
Li Li6f059292021-09-10 09:59:30 -07001414 info.pid = pid;
1415
1416#if defined(__ANDROID__)
1417 if (ioctl(self()->mProcess->mDriverFD, BINDER_GET_FROZEN_INFO, &info) < 0)
1418 ret = -errno;
1419#endif
1420 *sync_received = info.sync_recv;
1421 *async_received = info.async_recv;
1422
1423 return ret;
1424}
Li Li6f059292021-09-10 09:59:30 -07001425
Marco Ballesio7ee17572020-09-08 10:30:03 -07001426status_t IPCThreadState::freeze(pid_t pid, bool enable, uint32_t timeout_ms) {
1427 struct binder_freeze_info info;
1428 int ret = 0;
1429
1430 info.pid = pid;
1431 info.enable = enable;
1432 info.timeout_ms = timeout_ms;
1433
1434
1435#if defined(__ANDROID__)
1436 if (ioctl(self()->mProcess->mDriverFD, BINDER_FREEZE, &info) < 0)
1437 ret = -errno;
1438#endif
1439
1440 //
1441 // ret==-EAGAIN indicates that transactions have not drained.
1442 // Call again to poll for completion.
1443 //
1444 return ret;
1445}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001446
Carlos Llamasb235b122021-12-20 06:38:44 -08001447void IPCThreadState::logExtendedError() {
1448 struct binder_extended_error ee = {.command = BR_OK};
1449
1450 if (!ProcessState::isDriverFeatureEnabled(ProcessState::DriverFeature::EXTENDED_ERROR))
1451 return;
1452
1453#if defined(__ANDROID__)
1454 if (ioctl(self()->mProcess->mDriverFD, BINDER_GET_EXTENDED_ERROR, &ee) < 0) {
1455 ALOGE("Failed to get extended error: %s", strerror(errno));
1456 return;
1457 }
1458#endif
1459
1460 ALOGE_IF(ee.command != BR_OK, "Binder transaction failure: %d/%d/%d",
1461 ee.id, ee.command, ee.param);
1462}
1463
Colin Cross6f4f3ab2014-02-05 17:42:44 -08001464void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data,
1465 size_t /*dataSize*/,
1466 const binder_size_t* /*objects*/,
Steven Moreland161fe122020-11-12 23:16:47 +00001467 size_t /*objectsSize*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001468{
Steve Blocka19954a2012-01-04 20:05:49 +00001469 //ALOGI("Freeing parcel %p", &parcel);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001470 IF_LOG_COMMANDS() {
1471 alog << "Writing BC_FREE_BUFFER for " << data << endl;
1472 }
Steve Block67263472012-01-09 18:35:44 +00001473 ALOG_ASSERT(data != NULL, "Called with NULL data");
Yi Kongfdd8da92018-06-07 17:52:27 -07001474 if (parcel != nullptr) parcel->closeFileDescriptors();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001475 IPCThreadState* state = self();
1476 state->mOut.writeInt32(BC_FREE_BUFFER);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001477 state->mOut.writePointer((uintptr_t)data);
Martijn Coenen0442a862017-11-17 10:46:32 +01001478 state->flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001479}
1480
Steven Moreland61ff8492019-09-26 16:05:45 -07001481} // namespace android