blob: f6ca26ec8d2d656dfca34a21f503e581da3def2a [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
Glenn Kastena26e1cf2012-03-16 07:15:23 -070025#include <cutils/sched_policy.h>
Steven Moreland7732a092019-01-02 17:54:16 -080026#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080027#include <utils/Log.h>
Colin Cross96e83222016-04-15 14:29:55 -070028#include <utils/SystemClock.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080029
Hans Boehma997b232019-04-12 16:59:00 -070030#include <atomic>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <errno.h>
Colin Cross96e83222016-04-15 14:29:55 -070032#include <inttypes.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <pthread.h>
34#include <sched.h>
Yabin Cui8fb2d252015-01-26 19:45:47 -080035#include <signal.h>
36#include <stdio.h>
37#include <sys/ioctl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080038#include <sys/resource.h>
Yabin Cui8fb2d252015-01-26 19:45:47 -080039#include <unistd.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080040
Steven Moreland6ba5a252021-05-04 22:49:00 +000041#include "binder_module.h"
Steven Morelanda4853cd2019-07-12 15:44:37 -070042
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080043#if LOG_NDEBUG
44
45#define IF_LOG_TRANSACTIONS() if (false)
46#define IF_LOG_COMMANDS() if (false)
mattgilbride85897672022-10-22 17:42:44 +000047#define LOG_REMOTEREFS(...)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080048#define IF_LOG_REMOTEREFS() if (false)
Tim Murrayd429f4a2017-03-07 09:31:09 -080049
mattgilbride85897672022-10-22 17:42:44 +000050#define LOG_THREADPOOL(...)
51#define LOG_ONEWAY(...)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080052
53#else
54
Steve Block9f760152011-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__)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
62#endif
63
64// ---------------------------------------------------------------------------
65
66namespace android {
67
Chih-Hung Hsieh8e5337d2014-10-24 14:10:09 -070068// Static const and functions will be optimized out if not used,
69// when LOG_NDEBUG and references in IF_LOG_COMMANDS() are optimized out.
Devin Moorea7499132023-12-15 18:48:39 +000070static const char* kReturnStrings[] = {
71 "BR_ERROR",
72 "BR_OK",
73 "BR_TRANSACTION",
74 "BR_REPLY",
75 "BR_ACQUIRE_RESULT",
76 "BR_DEAD_REPLY",
77 "BR_TRANSACTION_COMPLETE",
78 "BR_INCREFS",
79 "BR_ACQUIRE",
80 "BR_RELEASE",
81 "BR_DECREFS",
82 "BR_ATTEMPT_ACQUIRE",
83 "BR_NOOP",
84 "BR_SPAWN_LOOPER",
85 "BR_FINISHED",
86 "BR_DEAD_BINDER",
87 "BR_CLEAR_DEATH_NOTIFICATION_DONE",
88 "BR_FAILED_REPLY",
89 "BR_FROZEN_REPLY",
90 "BR_ONEWAY_SPAM_SUSPECT",
91 "BR_TRANSACTION_PENDING_FROZEN",
92 "BR_TRANSACTION_SEC_CTX",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093};
94
95static const char *kCommandStrings[] = {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080096 "BC_TRANSACTION",
97 "BC_REPLY",
98 "BC_ACQUIRE_RESULT",
99 "BC_FREE_BUFFER",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100 "BC_INCREFS",
101 "BC_ACQUIRE",
102 "BC_RELEASE",
103 "BC_DECREFS",
104 "BC_INCREFS_DONE",
105 "BC_ACQUIRE_DONE",
106 "BC_ATTEMPT_ACQUIRE",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107 "BC_REGISTER_LOOPER",
108 "BC_ENTER_LOOPER",
109 "BC_EXIT_LOOPER",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800110 "BC_REQUEST_DEATH_NOTIFICATION",
111 "BC_CLEAR_DEATH_NOTIFICATION",
112 "BC_DEAD_BINDER_DONE"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800113};
114
Olivier Gaillard91a04802018-11-14 17:32:41 +0000115static const int64_t kWorkSourcePropagatedBitIndex = 32;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100116
songjinshi73a7dde2016-10-18 21:05:56 +0800117static const char* getReturnString(uint32_t cmd)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800118{
songjinshi8e486c62019-04-04 11:22:52 +0800119 size_t idx = cmd & _IOC_NRMASK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120 if (idx < sizeof(kReturnStrings) / sizeof(kReturnStrings[0]))
121 return kReturnStrings[idx];
122 else
123 return "unknown";
124}
125
Pawan Wagh7063b522022-09-28 18:52:26 +0000126static const void* printBinderTransactionData(std::ostream& out, const void* data) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127 const binder_transaction_data* btd =
128 (const binder_transaction_data*)data;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700129 if (btd->target.handle < 1024) {
130 /* want to print descriptors in decimal; guess based on value */
Pawan Wagh7063b522022-09-28 18:52:26 +0000131 out << "\ttarget.desc=" << btd->target.handle;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700132 } else {
Pawan Wagh7063b522022-09-28 18:52:26 +0000133 out << "\ttarget.ptr=" << btd->target.ptr;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700134 }
Alice Ryhlc268ccb2022-11-17 10:18:38 +0000135 out << "\t (cookie " << btd->cookie << ")\n"
Pawan Wagh7063b522022-09-28 18:52:26 +0000136 << "\tcode=" << TypeCode(btd->code) << ", flags=" << (void*)(uint64_t)btd->flags << "\n"
Alice Ryhlc268ccb2022-11-17 10:18:38 +0000137 << "\tdata=" << btd->data.ptr.buffer << " (" << (void*)btd->data_size << " bytes)\n"
138 << "\toffsets=" << btd->data.ptr.offsets << " (" << (void*)btd->offsets_size << " bytes)\n";
139 return btd + 1;
140}
141
142static const void* printBinderTransactionDataSecCtx(std::ostream& out, const void* data) {
143 const binder_transaction_data_secctx* btd = (const binder_transaction_data_secctx*)data;
144
145 printBinderTransactionData(out, &btd->transaction_data);
146
147 char* secctx = (char*)btd->secctx;
148 out << "\tsecctx=" << secctx << "\n";
149
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800150 return btd+1;
151}
152
Pawan Wagh7063b522022-09-28 18:52:26 +0000153static const void* printReturnCommand(std::ostream& out, const void* _cmd) {
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700154 static const size_t N = sizeof(kReturnStrings)/sizeof(kReturnStrings[0]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155 const int32_t* cmd = (const int32_t*)_cmd;
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100156 uint32_t code = (uint32_t)*cmd++;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700157 size_t cmdIndex = code & 0xff;
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100158 if (code == BR_ERROR) {
Pawan Wagh7063b522022-09-28 18:52:26 +0000159 out << "\tBR_ERROR: " << (void*)(uint64_t)(*cmd++) << "\n";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160 return cmd;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700161 } else if (cmdIndex >= N) {
Pawan Wagh7063b522022-09-28 18:52:26 +0000162 out << "\tUnknown reply: " << code << "\n";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163 return cmd;
164 }
Pawan Wagh7063b522022-09-28 18:52:26 +0000165 out << "\t" << kReturnStrings[cmdIndex];
Tim Murrayd429f4a2017-03-07 09:31:09 -0800166
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800167 switch (code) {
Alice Ryhlc268ccb2022-11-17 10:18:38 +0000168 case BR_TRANSACTION_SEC_CTX: {
169 out << ": ";
170 cmd = (const int32_t*)printBinderTransactionDataSecCtx(out, cmd);
171 } break;
172
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173 case BR_TRANSACTION:
174 case BR_REPLY: {
Pawan Wagh7063b522022-09-28 18:52:26 +0000175 out << ": ";
176 cmd = (const int32_t*)printBinderTransactionData(out, cmd);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800177 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800178
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179 case BR_ACQUIRE_RESULT: {
180 const int32_t res = *cmd++;
181 out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
182 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800184 case BR_INCREFS:
185 case BR_ACQUIRE:
186 case BR_RELEASE:
187 case BR_DECREFS: {
188 const int32_t b = *cmd++;
189 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900190 out << ": target=" << (void*)(uint64_t)b << " (cookie " << (void*)(uint64_t)c << ")";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800191 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800192
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800193 case BR_ATTEMPT_ACQUIRE: {
194 const int32_t p = *cmd++;
195 const int32_t b = *cmd++;
196 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900197 out << ": target=" << (void*)(uint64_t)b << " (cookie " << (void*)(uint64_t)c
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800198 << "), pri=" << p;
199 } break;
200
201 case BR_DEAD_BINDER:
202 case BR_CLEAR_DEATH_NOTIFICATION_DONE: {
203 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900204 out << ": death cookie " << (void*)(uint64_t)c;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205 } break;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700206
207 default:
208 // no details to show for: BR_OK, BR_DEAD_REPLY,
209 // BR_TRANSACTION_COMPLETE, BR_FINISHED
210 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800211 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800212
Pawan Wagh7063b522022-09-28 18:52:26 +0000213 out << "\n";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214 return cmd;
215}
216
Pawan Wagh7063b522022-09-28 18:52:26 +0000217static const void* printCommand(std::ostream& out, const void* _cmd) {
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700218 static const size_t N = sizeof(kCommandStrings)/sizeof(kCommandStrings[0]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219 const int32_t* cmd = (const int32_t*)_cmd;
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100220 uint32_t code = (uint32_t)*cmd++;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700221 size_t cmdIndex = code & 0xff;
222
223 if (cmdIndex >= N) {
Pawan Wagh7063b522022-09-28 18:52:26 +0000224 out << "Unknown command: " << code << "\n";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225 return cmd;
226 }
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700227 out << kCommandStrings[cmdIndex];
228
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229 switch (code) {
230 case BC_TRANSACTION:
231 case BC_REPLY: {
Pawan Wagh7063b522022-09-28 18:52:26 +0000232 out << ": ";
233 cmd = (const int32_t*)printBinderTransactionData(out, cmd);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800235
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236 case BC_ACQUIRE_RESULT: {
237 const int32_t res = *cmd++;
238 out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
239 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800240
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800241 case BC_FREE_BUFFER: {
242 const int32_t buf = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900243 out << ": buffer=" << (void*)(uint64_t)buf;
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:
247 case BC_ACQUIRE:
248 case BC_RELEASE:
249 case BC_DECREFS: {
250 const int32_t d = *cmd++;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700251 out << ": desc=" << d;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800253
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 case BC_INCREFS_DONE:
255 case BC_ACQUIRE_DONE: {
256 const int32_t b = *cmd++;
257 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900258 out << ": target=" << (void*)(uint64_t)b << " (cookie " << (void*)(uint64_t)c << ")";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800260
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261 case BC_ATTEMPT_ACQUIRE: {
262 const int32_t p = *cmd++;
263 const int32_t d = *cmd++;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700264 out << ": desc=" << d << ", pri=" << p;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800266
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800267 case BC_REQUEST_DEATH_NOTIFICATION:
268 case BC_CLEAR_DEATH_NOTIFICATION: {
269 const int32_t h = *cmd++;
270 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900271 out << ": handle=" << h << " (death cookie " << (void*)(uint64_t)c << ")";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272 } break;
273
274 case BC_DEAD_BINDER_DONE: {
275 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900276 out << ": death cookie " << (void*)(uint64_t)c;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800277 } break;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700278
279 default:
280 // no details to show for: BC_REGISTER_LOOPER, BC_ENTER_LOOPER,
281 // BC_EXIT_LOOPER
282 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800284
Pawan Wagh7063b522022-09-28 18:52:26 +0000285 out << "\n";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286 return cmd;
287}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288
289static pthread_mutex_t gTLSMutex = PTHREAD_MUTEX_INITIALIZER;
Hans Boehma997b232019-04-12 16:59:00 -0700290static std::atomic<bool> gHaveTLS(false);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291static pthread_key_t gTLS = 0;
Hans Boehma997b232019-04-12 16:59:00 -0700292static std::atomic<bool> gShutdown = false;
293static std::atomic<bool> gDisableBackgroundScheduling = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800294
295IPCThreadState* IPCThreadState::self()
296{
Hans Boehma997b232019-04-12 16:59:00 -0700297 if (gHaveTLS.load(std::memory_order_acquire)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800298restart:
299 const pthread_key_t k = gTLS;
300 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
301 if (st) return st;
302 return new IPCThreadState;
303 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800304
Hans Boehma997b232019-04-12 16:59:00 -0700305 // Racey, heuristic test for simultaneous shutdown.
306 if (gShutdown.load(std::memory_order_relaxed)) {
Andreas Gampef31a3eb2016-02-01 13:21:56 -0800307 ALOGW("Calling IPCThreadState::self() during shutdown is dangerous, expect a crash.\n");
Yi Kongfdd8da92018-06-07 17:52:27 -0700308 return nullptr;
Andreas Gampef31a3eb2016-02-01 13:21:56 -0800309 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800310
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800311 pthread_mutex_lock(&gTLSMutex);
Hans Boehma997b232019-04-12 16:59:00 -0700312 if (!gHaveTLS.load(std::memory_order_relaxed)) {
Andreas Gampef31a3eb2016-02-01 13:21:56 -0800313 int key_create_value = pthread_key_create(&gTLS, threadDestructor);
314 if (key_create_value != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800315 pthread_mutex_unlock(&gTLSMutex);
Andreas Gampef31a3eb2016-02-01 13:21:56 -0800316 ALOGW("IPCThreadState::self() unable to create TLS key, expect a crash: %s\n",
317 strerror(key_create_value));
Yi Kongfdd8da92018-06-07 17:52:27 -0700318 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800319 }
Hans Boehma997b232019-04-12 16:59:00 -0700320 gHaveTLS.store(true, std::memory_order_release);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800321 }
322 pthread_mutex_unlock(&gTLSMutex);
323 goto restart;
324}
325
Brad Fitzpatrick1b608432010-12-13 16:52:35 -0800326IPCThreadState* IPCThreadState::selfOrNull()
327{
Hans Boehma997b232019-04-12 16:59:00 -0700328 if (gHaveTLS.load(std::memory_order_acquire)) {
Brad Fitzpatrick1b608432010-12-13 16:52:35 -0800329 const pthread_key_t k = gTLS;
330 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
331 return st;
332 }
Yi Kongfdd8da92018-06-07 17:52:27 -0700333 return nullptr;
Brad Fitzpatrick1b608432010-12-13 16:52:35 -0800334}
335
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800336void IPCThreadState::shutdown()
337{
Hans Boehma997b232019-04-12 16:59:00 -0700338 gShutdown.store(true, std::memory_order_relaxed);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800339
Hans Boehma997b232019-04-12 16:59:00 -0700340 if (gHaveTLS.load(std::memory_order_acquire)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800341 // XXX Need to wait for all thread pool threads to exit!
342 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(gTLS);
343 if (st) {
344 delete st;
Yi Kongfdd8da92018-06-07 17:52:27 -0700345 pthread_setspecific(gTLS, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800346 }
zhongjieff405782016-03-09 15:05:04 +0800347 pthread_key_delete(gTLS);
Hans Boehma997b232019-04-12 16:59:00 -0700348 gHaveTLS.store(false, std::memory_order_release);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349 }
350}
351
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800352void IPCThreadState::disableBackgroundScheduling(bool disable)
353{
Hans Boehma997b232019-04-12 16:59:00 -0700354 gDisableBackgroundScheduling.store(disable, std::memory_order_relaxed);
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800355}
356
Martijn Coenen2b631742017-05-05 11:16:59 -0700357bool IPCThreadState::backgroundSchedulingDisabled()
358{
Hans Boehma997b232019-04-12 16:59:00 -0700359 return gDisableBackgroundScheduling.load(std::memory_order_relaxed);
Martijn Coenen2b631742017-05-05 11:16:59 -0700360}
361
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800362status_t IPCThreadState::clearLastError()
363{
364 const status_t err = mLastError;
365 mLastError = NO_ERROR;
366 return err;
367}
368
Dan Stoza9c634fd2014-11-26 12:23:23 -0800369pid_t IPCThreadState::getCallingPid() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370{
Steven Moreland35626652021-05-15 01:32:04 +0000371 checkContextIsBinderForUse(__func__);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800372 return mCallingPid;
373}
374
Steven Morelandf0212002018-12-26 13:59:23 -0800375const char* IPCThreadState::getCallingSid() const
376{
Steven Moreland35626652021-05-15 01:32:04 +0000377 checkContextIsBinderForUse(__func__);
Steven Morelandf0212002018-12-26 13:59:23 -0800378 return mCallingSid;
379}
380
Dan Stoza9c634fd2014-11-26 12:23:23 -0800381uid_t IPCThreadState::getCallingUid() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800382{
Steven Moreland35626652021-05-15 01:32:04 +0000383 checkContextIsBinderForUse(__func__);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800384 return mCallingUid;
385}
386
Steven Moreland35626652021-05-15 01:32:04 +0000387const IPCThreadState::SpGuard* IPCThreadState::pushGetCallingSpGuard(const SpGuard* guard) {
388 const SpGuard* orig = mServingStackPointerGuard;
389 mServingStackPointerGuard = guard;
390 return orig;
391}
392
393void IPCThreadState::restoreGetCallingSpGuard(const SpGuard* guard) {
394 mServingStackPointerGuard = guard;
395}
396
397void IPCThreadState::checkContextIsBinderForUse(const char* use) const {
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -0700398 if (mServingStackPointerGuard == nullptr) [[likely]] {
399 return;
400 }
Steven Moreland35626652021-05-15 01:32:04 +0000401
402 if (!mServingStackPointer || mServingStackPointerGuard->address < mServingStackPointer) {
403 LOG_ALWAYS_FATAL("In context %s, %s does not make sense (binder sp: %p, guard: %p).",
404 mServingStackPointerGuard->context, use, mServingStackPointer,
405 mServingStackPointerGuard->address);
406 }
407
408 // in the case mServingStackPointer is deeper in the stack than the guard,
409 // we must be serving a binder transaction (maybe nested). This is a binder
410 // context, so we don't abort
411}
412
mattgilbride85897672022-10-22 17:42:44 +0000413constexpr uint32_t encodeExplicitIdentity(bool hasExplicitIdentity, pid_t callingPid) {
414 uint32_t as_unsigned = static_cast<uint32_t>(callingPid);
415 if (hasExplicitIdentity) {
416 return as_unsigned | (1 << 30);
417 } else {
418 return as_unsigned & ~(1 << 30);
419 }
420}
421
422constexpr int64_t packCallingIdentity(bool hasExplicitIdentity, uid_t callingUid,
423 pid_t callingPid) {
424 // Calling PID is a 32-bit signed integer, but doesn't consume the entire 32 bit space.
425 // To future-proof this and because we have extra capacity, we decided to also support -1,
426 // since this constant is used to represent invalid UID in other places of the system.
427 // Thus, we pack hasExplicitIdentity into the 2nd bit from the left. This allows us to
428 // preserve the (left-most) bit for the sign while also encoding the value of
429 // hasExplicitIdentity.
430 // 32b | 1b | 1b | 30b
431 // token = [ calling uid | calling pid(sign) | has explicit identity | calling pid(rest) ]
432 uint64_t token = (static_cast<uint64_t>(callingUid) << 32) |
433 encodeExplicitIdentity(hasExplicitIdentity, callingPid);
434 return static_cast<int64_t>(token);
435}
436
437constexpr bool unpackHasExplicitIdentity(int64_t token) {
438 return static_cast<int32_t>(token) & (1 << 30);
439}
440
441constexpr uid_t unpackCallingUid(int64_t token) {
442 return static_cast<uid_t>(token >> 32);
443}
444
445constexpr pid_t unpackCallingPid(int64_t token) {
446 int32_t encodedPid = static_cast<int32_t>(token);
447 if (encodedPid & (1 << 31)) {
448 return encodedPid | (1 << 30);
449 } else {
450 return encodedPid & ~(1 << 30);
451 }
452}
453
454static_assert(unpackHasExplicitIdentity(packCallingIdentity(true, 1000, 9999)) == true,
455 "pack true hasExplicit");
456
457static_assert(unpackCallingUid(packCallingIdentity(true, 1000, 9999)) == 1000, "pack true uid");
458
459static_assert(unpackCallingPid(packCallingIdentity(true, 1000, 9999)) == 9999, "pack true pid");
460
461static_assert(unpackHasExplicitIdentity(packCallingIdentity(false, 1000, 9999)) == false,
462 "pack false hasExplicit");
463
464static_assert(unpackCallingUid(packCallingIdentity(false, 1000, 9999)) == 1000, "pack false uid");
465
466static_assert(unpackCallingPid(packCallingIdentity(false, 1000, 9999)) == 9999, "pack false pid");
467
468static_assert(unpackHasExplicitIdentity(packCallingIdentity(true, 1000, -1)) == true,
469 "pack true (negative) hasExplicit");
470
471static_assert(unpackCallingUid(packCallingIdentity(true, 1000, -1)) == 1000,
472 "pack true (negative) uid");
473
474static_assert(unpackCallingPid(packCallingIdentity(true, 1000, -1)) == -1,
475 "pack true (negative) pid");
476
477static_assert(unpackHasExplicitIdentity(packCallingIdentity(false, 1000, -1)) == false,
478 "pack false (negative) hasExplicit");
479
480static_assert(unpackCallingUid(packCallingIdentity(false, 1000, -1)) == 1000,
481 "pack false (negative) uid");
482
483static_assert(unpackCallingPid(packCallingIdentity(false, 1000, -1)) == -1,
484 "pack false (negative) pid");
485
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800486int64_t IPCThreadState::clearCallingIdentity()
487{
Steven Morelandf0212002018-12-26 13:59:23 -0800488 // ignore mCallingSid for legacy reasons
mattgilbride85897672022-10-22 17:42:44 +0000489 int64_t token = packCallingIdentity(mHasExplicitIdentity, mCallingUid, mCallingPid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800490 clearCaller();
mattgilbride85897672022-10-22 17:42:44 +0000491 mHasExplicitIdentity = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800492 return token;
493}
494
mattgilbride85897672022-10-22 17:42:44 +0000495bool IPCThreadState::hasExplicitIdentity() {
496 return mHasExplicitIdentity;
497}
498
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700499void IPCThreadState::setStrictModePolicy(int32_t policy)
500{
501 mStrictModePolicy = policy;
502}
503
Brad Fitzpatricka877cd82010-07-07 16:06:39 -0700504int32_t IPCThreadState::getStrictModePolicy() const
505{
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700506 return mStrictModePolicy;
507}
508
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000509int64_t IPCThreadState::setCallingWorkSourceUid(uid_t uid)
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100510{
Olivier Gaillard91a04802018-11-14 17:32:41 +0000511 int64_t token = setCallingWorkSourceUidWithoutPropagation(uid);
512 mPropagateWorkSource = true;
513 return token;
514}
515
516int64_t IPCThreadState::setCallingWorkSourceUidWithoutPropagation(uid_t uid)
517{
518 const int64_t propagatedBit = ((int64_t)mPropagateWorkSource) << kWorkSourcePropagatedBitIndex;
519 int64_t token = propagatedBit | mWorkSource;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100520 mWorkSource = uid;
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000521 return token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100522}
523
Olivier Gaillard91a04802018-11-14 17:32:41 +0000524void IPCThreadState::clearPropagateWorkSource()
525{
526 mPropagateWorkSource = false;
527}
528
529bool IPCThreadState::shouldPropagateWorkSource() const
530{
531 return mPropagateWorkSource;
532}
533
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000534uid_t IPCThreadState::getCallingWorkSourceUid() const
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100535{
536 return mWorkSource;
537}
538
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000539int64_t IPCThreadState::clearCallingWorkSource()
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100540{
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000541 return setCallingWorkSourceUid(kUnsetWorkSource);
542}
543
544void IPCThreadState::restoreCallingWorkSource(int64_t token)
545{
546 uid_t uid = (int)token;
Olivier Gaillard91a04802018-11-14 17:32:41 +0000547 setCallingWorkSourceUidWithoutPropagation(uid);
548 mPropagateWorkSource = ((token >> kWorkSourcePropagatedBitIndex) & 1) == 1;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100549}
550
Brad Fitzpatrick52736032010-08-30 16:01:16 -0700551void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
552{
553 mLastTransactionBinderFlags = flags;
554}
555
556int32_t IPCThreadState::getLastTransactionBinderFlags() const
557{
558 return mLastTransactionBinderFlags;
559}
560
Steven Moreland9514b202020-09-21 18:03:27 +0000561void IPCThreadState::setCallRestriction(ProcessState::CallRestriction restriction) {
562 mCallRestriction = restriction;
563}
564
565ProcessState::CallRestriction IPCThreadState::getCallRestriction() const {
566 return mCallRestriction;
567}
568
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800569void IPCThreadState::restoreCallingIdentity(int64_t token)
570{
mattgilbride85897672022-10-22 17:42:44 +0000571 mCallingUid = unpackCallingUid(token);
Steven Morelandf0212002018-12-26 13:59:23 -0800572 mCallingSid = nullptr; // not enough data to restore
mattgilbride85897672022-10-22 17:42:44 +0000573 mCallingPid = unpackCallingPid(token);
574 mHasExplicitIdentity = unpackHasExplicitIdentity(token);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800575}
576
577void IPCThreadState::clearCaller()
578{
Marco Nelissend43b1942009-07-17 07:59:17 -0700579 mCallingPid = getpid();
Steven Morelandf0212002018-12-26 13:59:23 -0800580 mCallingSid = nullptr; // expensive to lookup
Marco Nelissend43b1942009-07-17 07:59:17 -0700581 mCallingUid = getuid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800582}
583
584void IPCThreadState::flushCommands()
585{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -0200586 if (mProcess->mDriverFD < 0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800587 return;
588 talkWithDriver(false);
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700589 // The flush could have caused post-write refcount decrements to have
590 // been executed, which in turn could result in BC_RELEASE/BC_DECREFS
591 // being queued in mOut. So flush again, if we need to.
592 if (mOut.dataSize() > 0) {
593 talkWithDriver(false);
594 }
595 if (mOut.dataSize() > 0) {
596 ALOGW("mOut.dataSize() > 0 after flushCommands()");
597 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800598}
599
Martijn Coenen0442a862017-11-17 10:46:32 +0100600bool IPCThreadState::flushIfNeeded()
601{
Frankie Changf4c81372021-05-18 13:08:05 +0800602 if (mIsLooper || mServingStackPointer != nullptr || mIsFlushing) {
Martijn Coenen0442a862017-11-17 10:46:32 +0100603 return false;
604 }
Frankie Changf4c81372021-05-18 13:08:05 +0800605 mIsFlushing = true;
Martijn Coenen0442a862017-11-17 10:46:32 +0100606 // In case this thread is not a looper and is not currently serving a binder transaction,
607 // there's no guarantee that this thread will call back into the kernel driver any time
608 // soon. Therefore, flush pending commands such as BC_FREE_BUFFER, to prevent them from getting
609 // stuck in this thread's out buffer.
610 flushCommands();
Frankie Changf4c81372021-05-18 13:08:05 +0800611 mIsFlushing = false;
Martijn Coenen0442a862017-11-17 10:46:32 +0100612 return true;
613}
614
Wale Ogunwale376b8222015-04-13 16:16:10 -0700615void IPCThreadState::blockUntilThreadAvailable()
616{
617 pthread_mutex_lock(&mProcess->mThreadCountLock);
Steven Morelandc648a762021-01-16 02:39:45 +0000618 mProcess->mWaitingForThreads++;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700619 while (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads) {
Wale Ogunwalea3206e62015-04-21 12:29:50 -0700620 ALOGW("Waiting for thread to be free. mExecutingThreadsCount=%lu mMaxThreads=%lu\n",
621 static_cast<unsigned long>(mProcess->mExecutingThreadsCount),
622 static_cast<unsigned long>(mProcess->mMaxThreads));
Wale Ogunwale376b8222015-04-13 16:16:10 -0700623 pthread_cond_wait(&mProcess->mThreadCountDecrement, &mProcess->mThreadCountLock);
624 }
Steven Morelandc648a762021-01-16 02:39:45 +0000625 mProcess->mWaitingForThreads--;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700626 pthread_mutex_unlock(&mProcess->mThreadCountLock);
627}
628
Todd Poynor8d96cab2013-06-25 19:12:18 -0700629status_t IPCThreadState::getAndExecuteCommand()
630{
631 status_t result;
632 int32_t cmd;
633
634 result = talkWithDriver();
635 if (result >= NO_ERROR) {
636 size_t IN = mIn.dataAvail();
637 if (IN < sizeof(int32_t)) return result;
638 cmd = mIn.readInt32();
639 IF_LOG_COMMANDS() {
Pawan Wagh7063b522022-09-28 18:52:26 +0000640 std::ostringstream logStream;
641 logStream << "Processing top-level Command: " << getReturnString(cmd) << "\n";
642 std::string message = logStream.str();
643 ALOGI("%s", message.c_str());
Todd Poynor8d96cab2013-06-25 19:12:18 -0700644 }
645
Wale Ogunwale376b8222015-04-13 16:16:10 -0700646 pthread_mutex_lock(&mProcess->mThreadCountLock);
647 mProcess->mExecutingThreadsCount++;
Colin Cross96e83222016-04-15 14:29:55 -0700648 if (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads &&
649 mProcess->mStarvationStartTimeMs == 0) {
650 mProcess->mStarvationStartTimeMs = uptimeMillis();
651 }
Wale Ogunwale376b8222015-04-13 16:16:10 -0700652 pthread_mutex_unlock(&mProcess->mThreadCountLock);
653
Todd Poynor8d96cab2013-06-25 19:12:18 -0700654 result = executeCommand(cmd);
655
Wale Ogunwale376b8222015-04-13 16:16:10 -0700656 pthread_mutex_lock(&mProcess->mThreadCountLock);
657 mProcess->mExecutingThreadsCount--;
Colin Cross96e83222016-04-15 14:29:55 -0700658 if (mProcess->mExecutingThreadsCount < mProcess->mMaxThreads &&
659 mProcess->mStarvationStartTimeMs != 0) {
660 int64_t starvationTimeMs = uptimeMillis() - mProcess->mStarvationStartTimeMs;
661 if (starvationTimeMs > 100) {
662 ALOGE("binder thread pool (%zu threads) starved for %" PRId64 " ms",
663 mProcess->mMaxThreads, starvationTimeMs);
664 }
665 mProcess->mStarvationStartTimeMs = 0;
666 }
Steven Morelandc648a762021-01-16 02:39:45 +0000667
668 // Cond broadcast can be expensive, so don't send it every time a binder
669 // call is processed. b/168806193
670 if (mProcess->mWaitingForThreads > 0) {
671 pthread_cond_broadcast(&mProcess->mThreadCountDecrement);
672 }
Wale Ogunwale376b8222015-04-13 16:16:10 -0700673 pthread_mutex_unlock(&mProcess->mThreadCountLock);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700674 }
675
676 return result;
677}
678
679// When we've cleared the incoming command queue, process any pending derefs
680void IPCThreadState::processPendingDerefs()
681{
682 if (mIn.dataPosition() >= mIn.dataSize()) {
Martijn Coenen0791fbf2017-08-08 15:36:16 +0200683 /*
684 * The decWeak()/decStrong() calls may cause a destructor to run,
685 * which in turn could have initiated an outgoing transaction,
686 * which in turn could cause us to add to the pending refs
687 * vectors; so instead of simply iterating, loop until they're empty.
688 *
689 * We do this in an outer loop, because calling decStrong()
690 * may result in something being added to mPendingWeakDerefs,
691 * which could be delayed until the next incoming command
692 * from the driver if we don't process it now.
693 */
694 while (mPendingWeakDerefs.size() > 0 || mPendingStrongDerefs.size() > 0) {
695 while (mPendingWeakDerefs.size() > 0) {
696 RefBase::weakref_type* refs = mPendingWeakDerefs[0];
697 mPendingWeakDerefs.removeAt(0);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700698 refs->decWeak(mProcess.get());
699 }
Todd Poynor8d96cab2013-06-25 19:12:18 -0700700
Martijn Coenen0791fbf2017-08-08 15:36:16 +0200701 if (mPendingStrongDerefs.size() > 0) {
702 // We don't use while() here because we don't want to re-order
703 // strong and weak decs at all; if this decStrong() causes both a
704 // decWeak() and a decStrong() to be queued, we want to process
705 // the decWeak() first.
706 BBinder* obj = mPendingStrongDerefs[0];
707 mPendingStrongDerefs.removeAt(0);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700708 obj->decStrong(mProcess.get());
709 }
Todd Poynor8d96cab2013-06-25 19:12:18 -0700710 }
711 }
712}
713
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700714void IPCThreadState::processPostWriteDerefs()
715{
716 for (size_t i = 0; i < mPostWriteWeakDerefs.size(); i++) {
717 RefBase::weakref_type* refs = mPostWriteWeakDerefs[i];
718 refs->decWeak(mProcess.get());
719 }
720 mPostWriteWeakDerefs.clear();
721
722 for (size_t i = 0; i < mPostWriteStrongDerefs.size(); i++) {
723 RefBase* obj = mPostWriteStrongDerefs[i];
724 obj->decStrong(mProcess.get());
725 }
726 mPostWriteStrongDerefs.clear();
727}
728
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800729void IPCThreadState::joinThreadPool(bool isMain)
730{
731 LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
Elie Kheirallah47431c12022-04-21 23:46:17 +0000732 pthread_mutex_lock(&mProcess->mThreadCountLock);
733 mProcess->mCurrentThreads++;
734 pthread_mutex_unlock(&mProcess->mThreadCountLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800735 mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800736
Martijn Coenen0442a862017-11-17 10:46:32 +0100737 mIsLooper = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800738 status_t result;
739 do {
Todd Poynor8d96cab2013-06-25 19:12:18 -0700740 processPendingDerefs();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800741 // now get the next command to be processed, waiting if necessary
Todd Poynor8d96cab2013-06-25 19:12:18 -0700742 result = getAndExecuteCommand();
Jason Parksdcd39582009-11-03 12:14:38 -0800743
Todd Poynor8d96cab2013-06-25 19:12:18 -0700744 if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
Steven Moreland6adf33c2019-09-25 13:18:09 -0700745 LOG_ALWAYS_FATAL("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
Jeff Tinkeref073862013-06-11 11:30:21 -0700746 mProcess->mDriverFD, result);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800747 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800748
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800749 // Let this thread exit the thread pool if it is no longer
750 // needed and it is not the main process thread.
751 if(result == TIMED_OUT && !isMain) {
752 break;
753 }
754 } while (result != -ECONNREFUSED && result != -EBADF);
755
Wei Wangc7341432016-10-19 10:23:59 -0700756 LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%d\n",
757 (void*)pthread_self(), getpid(), result);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800758
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800759 mOut.writeInt32(BC_EXIT_LOOPER);
Martijn Coenen0442a862017-11-17 10:46:32 +0100760 mIsLooper = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800761 talkWithDriver(false);
Elie Kheirallah47431c12022-04-21 23:46:17 +0000762 pthread_mutex_lock(&mProcess->mThreadCountLock);
763 LOG_ALWAYS_FATAL_IF(mProcess->mCurrentThreads == 0,
764 "Threadpool thread count = 0. Thread cannot exist and exit in empty "
765 "threadpool\n"
766 "Misconfiguration. Increase threadpool max threads configuration\n");
767 mProcess->mCurrentThreads--;
768 pthread_mutex_unlock(&mProcess->mThreadCountLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800769}
770
Steven Morelandd8c85672020-07-24 21:30:41 +0000771status_t IPCThreadState::setupPolling(int* fd)
Todd Poynor8d96cab2013-06-25 19:12:18 -0700772{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -0200773 if (mProcess->mDriverFD < 0) {
Todd Poynor8d96cab2013-06-25 19:12:18 -0700774 return -EBADF;
775 }
776
777 mOut.writeInt32(BC_ENTER_LOOPER);
Steven Morelandf210b502021-01-15 23:40:32 +0000778 flushCommands();
Todd Poynor8d96cab2013-06-25 19:12:18 -0700779 *fd = mProcess->mDriverFD;
Elie Kheirallah47431c12022-04-21 23:46:17 +0000780 pthread_mutex_lock(&mProcess->mThreadCountLock);
781 mProcess->mCurrentThreads++;
782 pthread_mutex_unlock(&mProcess->mThreadCountLock);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700783 return 0;
784}
785
786status_t IPCThreadState::handlePolledCommands()
787{
788 status_t result;
789
790 do {
791 result = getAndExecuteCommand();
792 } while (mIn.dataPosition() < mIn.dataSize());
793
794 processPendingDerefs();
795 flushCommands();
796 return result;
797}
798
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800799void IPCThreadState::stopProcess(bool /*immediate*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800800{
Steve Blocka19954a2012-01-04 20:05:49 +0000801 //ALOGI("**** STOPPING PROCESS");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800802 flushCommands();
803 int fd = mProcess->mDriverFD;
804 mProcess->mDriverFD = -1;
805 close(fd);
806 //kill(getpid(), SIGKILL);
807}
808
809status_t IPCThreadState::transact(int32_t handle,
810 uint32_t code, const Parcel& data,
811 Parcel* reply, uint32_t flags)
812{
Steven Moreland5553ac42020-11-11 02:14:45 +0000813 LOG_ALWAYS_FATAL_IF(data.isForRpc(), "Parcel constructed for RPC, but being used with binder.");
814
Ganesh Mahendran58e5daa2017-10-11 18:05:13 +0800815 status_t err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800816
817 flags |= TF_ACCEPT_FDS;
818
819 IF_LOG_TRANSACTIONS() {
Pawan Wagh7063b522022-09-28 18:52:26 +0000820 std::ostringstream logStream;
821 logStream << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand " << handle
822 << " / code " << TypeCode(code) << ": \t" << data << "\n";
823 std::string message = logStream.str();
824 ALOGI("%s", message.c_str());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800825 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800826
Ganesh Mahendran58e5daa2017-10-11 18:05:13 +0800827 LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
828 (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
Yi Kongfdd8da92018-06-07 17:52:27 -0700829 err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, nullptr);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800830
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800831 if (err != NO_ERROR) {
832 if (reply) reply->setError(err);
833 return (mLastError = err);
834 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800835
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800836 if ((flags & TF_ONE_WAY) == 0) {
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -0700837 if (mCallRestriction != ProcessState::CallRestriction::NONE) [[unlikely]] {
Steven Moreland7732a092019-01-02 17:54:16 -0800838 if (mCallRestriction == ProcessState::CallRestriction::ERROR_IF_NOT_ONEWAY) {
Steven Moreland8cb34fc2019-05-13 11:44:55 -0700839 ALOGE("Process making non-oneway call (code: %u) but is restricted.", code);
Steven Moreland7732a092019-01-02 17:54:16 -0800840 CallStack::logStack("non-oneway call", CallStack::getCurrent(10).get(),
841 ANDROID_LOG_ERROR);
842 } else /* FATAL_IF_NOT_ONEWAY */ {
Steven Morelandfcc77f12020-09-01 01:16:11 +0000843 LOG_ALWAYS_FATAL("Process may not make non-oneway calls (code: %u).", code);
Steven Moreland7732a092019-01-02 17:54:16 -0800844 }
845 }
846
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -0700847#if 0
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700848 if (code == 4) { // relayout
Steve Blocka19954a2012-01-04 20:05:49 +0000849 ALOGI(">>>>>> CALLING transaction 4");
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700850 } else {
Steve Blocka19954a2012-01-04 20:05:49 +0000851 ALOGI(">>>>>> CALLING transaction %d", code);
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700852 }
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -0700853#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800854 if (reply) {
855 err = waitForResponse(reply);
856 } else {
857 Parcel fakeReply;
858 err = waitForResponse(&fakeReply);
859 }
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700860 #if 0
861 if (code == 4) { // relayout
Steve Blocka19954a2012-01-04 20:05:49 +0000862 ALOGI("<<<<<< RETURNING transaction 4");
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700863 } else {
Steve Blocka19954a2012-01-04 20:05:49 +0000864 ALOGI("<<<<<< RETURNING transaction %d", code);
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700865 }
866 #endif
Tim Murrayd429f4a2017-03-07 09:31:09 -0800867
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800868 IF_LOG_TRANSACTIONS() {
Pawan Wagh7063b522022-09-28 18:52:26 +0000869 std::ostringstream logStream;
870 logStream << "BR_REPLY thr " << (void*)pthread_self() << " / hand " << handle << ": ";
871 if (reply)
872 logStream << "\t" << *reply << "\n";
873 else
874 logStream << "(none requested)"
875 << "\n";
876 std::string message = logStream.str();
877 ALOGI("%s", message.c_str());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800878 }
879 } else {
Yi Kongfdd8da92018-06-07 17:52:27 -0700880 err = waitForResponse(nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800881 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800882
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800883 return err;
884}
885
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700886void IPCThreadState::incStrongHandle(int32_t handle, BpBinder *proxy)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800887{
888 LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
889 mOut.writeInt32(BC_ACQUIRE);
890 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100891 if (!flushIfNeeded()) {
892 // Create a temp reference until the driver has handled this command.
893 proxy->incStrong(mProcess.get());
894 mPostWriteStrongDerefs.push(proxy);
895 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800896}
897
898void IPCThreadState::decStrongHandle(int32_t handle)
899{
900 LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
901 mOut.writeInt32(BC_RELEASE);
902 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100903 flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800904}
905
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700906void IPCThreadState::incWeakHandle(int32_t handle, BpBinder *proxy)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800907{
908 LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
909 mOut.writeInt32(BC_INCREFS);
910 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100911 if (!flushIfNeeded()) {
912 // Create a temp reference until the driver has handled this command.
913 proxy->getWeakRefs()->incWeak(mProcess.get());
914 mPostWriteWeakDerefs.push(proxy->getWeakRefs());
915 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800916}
917
918void IPCThreadState::decWeakHandle(int32_t handle)
919{
920 LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
921 mOut.writeInt32(BC_DECREFS);
922 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100923 flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800924}
925
926status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
927{
Arve HjønnevÄg11cfdcc2014-02-14 20:14:02 -0800928#if HAS_BC_ATTEMPT_ACQUIRE
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700929 LOG_REMOTEREFS("IPCThreadState::attemptIncStrongHandle(%d)\n", handle);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800930 mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
931 mOut.writeInt32(0); // xxx was thread priority
932 mOut.writeInt32(handle);
933 status_t result = UNKNOWN_ERROR;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800934
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800935 waitForResponse(NULL, &result);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800936
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800937#if LOG_REFCOUNTS
liangweikanga43ee152016-10-25 16:37:54 +0800938 ALOGV("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800939 handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
940#endif
Tim Murrayd429f4a2017-03-07 09:31:09 -0800941
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800942 return result;
Arve HjønnevÄg11cfdcc2014-02-14 20:14:02 -0800943#else
944 (void)handle;
945 ALOGE("%s(%d): Not supported\n", __func__, handle);
946 return INVALID_OPERATION;
947#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800948}
949
950void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
951{
952#if LOG_REFCOUNTS
liangweikanga43ee152016-10-25 16:37:54 +0800953 ALOGV("IPCThreadState::expungeHandle(%ld)\n", handle);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800954#endif
Manoj Gupta9cec85b2017-09-19 16:34:29 -0700955 self()->mProcess->expungeHandle(handle, binder); // NOLINT
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800956}
957
958status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
959{
960 mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
961 mOut.writeInt32((int32_t)handle);
Serban Constantinescuf683e012013-11-05 16:53:55 +0000962 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800963 return NO_ERROR;
964}
965
966status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
967{
968 mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
969 mOut.writeInt32((int32_t)handle);
Serban Constantinescuf683e012013-11-05 16:53:55 +0000970 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800971 return NO_ERROR;
972}
973
974IPCThreadState::IPCThreadState()
Steven Moreland35626652021-05-15 01:32:04 +0000975 : mProcess(ProcessState::self()),
976 mServingStackPointer(nullptr),
977 mServingStackPointerGuard(nullptr),
978 mWorkSource(kUnsetWorkSource),
979 mPropagateWorkSource(false),
980 mIsLooper(false),
Frankie Changf4c81372021-05-18 13:08:05 +0800981 mIsFlushing(false),
Steven Moreland35626652021-05-15 01:32:04 +0000982 mStrictModePolicy(0),
983 mLastTransactionBinderFlags(0),
984 mCallRestriction(mProcess->mCallRestriction) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800985 pthread_setspecific(gTLS, this);
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800986 clearCaller();
mattgilbride85897672022-10-22 17:42:44 +0000987 mHasExplicitIdentity = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800988 mIn.setDataCapacity(256);
989 mOut.setDataCapacity(256);
990}
991
992IPCThreadState::~IPCThreadState()
993{
994}
995
Martijn Coenenea0090a2017-11-02 18:54:40 +0000996status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
997{
998 status_t err;
999 status_t statusBuffer;
1000 err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
1001 if (err < NO_ERROR) return err;
1002
Yi Kongfdd8da92018-06-07 17:52:27 -07001003 return waitForResponse(nullptr, nullptr);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001004}
1005
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001006status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
1007{
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +01001008 uint32_t cmd;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001009 int32_t err;
1010
1011 while (1) {
1012 if ((err=talkWithDriver()) < NO_ERROR) break;
1013 err = mIn.errorCheck();
1014 if (err < NO_ERROR) break;
1015 if (mIn.dataAvail() == 0) continue;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001016
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +01001017 cmd = (uint32_t)mIn.readInt32();
Tim Murrayd429f4a2017-03-07 09:31:09 -08001018
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001019 IF_LOG_COMMANDS() {
Pawan Wagh7063b522022-09-28 18:52:26 +00001020 std::ostringstream logStream;
1021 logStream << "Processing waitForResponse Command: " << getReturnString(cmd) << "\n";
1022 std::string message = logStream.str();
1023 ALOGI("%s", message.c_str());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001024 }
1025
1026 switch (cmd) {
Hang Lub185ac02021-03-24 13:17:22 +08001027 case BR_ONEWAY_SPAM_SUSPECT:
1028 ALOGE("Process seems to be sending too many oneway calls.");
1029 CallStack::logStack("oneway spamming", CallStack::getCurrent().get(),
1030 ANDROID_LOG_ERROR);
1031 [[fallthrough]];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001032 case BR_TRANSACTION_COMPLETE:
1033 if (!reply && !acquireResult) goto finish;
1034 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001035
Li Li0e3443d2022-12-07 21:51:19 -08001036 case BR_TRANSACTION_PENDING_FROZEN:
1037 ALOGW("Sending oneway calls to frozen process.");
1038 goto finish;
1039
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001040 case BR_DEAD_REPLY:
1041 err = DEAD_OBJECT;
1042 goto finish;
1043
1044 case BR_FAILED_REPLY:
1045 err = FAILED_TRANSACTION;
1046 goto finish;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001047
Marco Ballesio7ee17572020-09-08 10:30:03 -07001048 case BR_FROZEN_REPLY:
1049 err = FAILED_TRANSACTION;
1050 goto finish;
1051
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001052 case BR_ACQUIRE_RESULT:
1053 {
Steve Block67263472012-01-09 18:35:44 +00001054 ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001055 const int32_t result = mIn.readInt32();
1056 if (!acquireResult) continue;
1057 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
1058 }
1059 goto finish;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001060
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001061 case BR_REPLY:
1062 {
1063 binder_transaction_data tr;
1064 err = mIn.read(&tr, sizeof(tr));
Steve Block67263472012-01-09 18:35:44 +00001065 ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001066 if (err != NO_ERROR) goto finish;
1067
1068 if (reply) {
1069 if ((tr.flags & TF_STATUS_CODE) == 0) {
1070 reply->ipcSetDataReference(
1071 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1072 tr.data_size,
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001073 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1074 tr.offsets_size/sizeof(binder_size_t),
Steven Moreland161fe122020-11-12 23:16:47 +00001075 freeBuffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001076 } else {
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001077 err = *reinterpret_cast<const status_t*>(tr.data.ptr.buffer);
Frederick Mayle53b6ffe2022-07-15 20:14:01 +00001078 freeBuffer(reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1079 tr.data_size,
1080 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1081 tr.offsets_size / sizeof(binder_size_t));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001082 }
1083 } else {
Frederick Mayle53b6ffe2022-07-15 20:14:01 +00001084 freeBuffer(reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer), tr.data_size,
1085 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
1086 tr.offsets_size / sizeof(binder_size_t));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001087 continue;
1088 }
1089 }
1090 goto finish;
1091
1092 default:
1093 err = executeCommand(cmd);
1094 if (err != NO_ERROR) goto finish;
1095 break;
1096 }
1097 }
1098
1099finish:
1100 if (err != NO_ERROR) {
1101 if (acquireResult) *acquireResult = err;
1102 if (reply) reply->setError(err);
1103 mLastError = err;
Carlos Llamasb235b122021-12-20 06:38:44 -08001104 logExtendedError();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001105 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001107 return err;
1108}
1109
1110status_t IPCThreadState::talkWithDriver(bool doReceive)
1111{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -02001112 if (mProcess->mDriverFD < 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +01001113 return -EBADF;
1114 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001115
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001116 binder_write_read bwr;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001117
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001118 // Is the read buffer empty?
1119 const bool needRead = mIn.dataPosition() >= mIn.dataSize();
Tim Murrayd429f4a2017-03-07 09:31:09 -08001120
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001121 // We don't want to write anything if we are still reading
1122 // from data left in the input buffer and the caller
1123 // has requested to read the next data.
1124 const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001126 bwr.write_size = outAvail;
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001127 bwr.write_buffer = (uintptr_t)mOut.data();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001128
1129 // This is what we'll read.
1130 if (doReceive && needRead) {
1131 bwr.read_size = mIn.dataCapacity();
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001132 bwr.read_buffer = (uintptr_t)mIn.data();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001133 } else {
1134 bwr.read_size = 0;
Ben Chengd640f892011-12-01 17:11:32 -08001135 bwr.read_buffer = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001136 }
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001137
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001138 IF_LOG_COMMANDS() {
Pawan Wagh7063b522022-09-28 18:52:26 +00001139 std::ostringstream logStream;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001140 if (outAvail != 0) {
Pawan Wagh7063b522022-09-28 18:52:26 +00001141 logStream << "Sending commands to driver: ";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001142 const void* cmds = (const void*)bwr.write_buffer;
Pawan Wagh7063b522022-09-28 18:52:26 +00001143 const void* end = ((const uint8_t*)cmds) + bwr.write_size;
1144 logStream << "\t" << HexDump(cmds, bwr.write_size) << "\n";
1145 while (cmds < end) cmds = printCommand(logStream, cmds);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001146 }
Pawan Wagh7063b522022-09-28 18:52:26 +00001147 logStream << "Size of receive buffer: " << bwr.read_size << ", needRead: " << needRead
1148 << ", doReceive: " << doReceive << "\n";
1149
1150 std::string message = logStream.str();
1151 ALOGI("%s", message.c_str());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001152 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001153
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001154 // Return immediately if there is nothing to do.
1155 if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001156
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001157 bwr.write_consumed = 0;
1158 bwr.read_consumed = 0;
1159 status_t err;
1160 do {
1161 IF_LOG_COMMANDS() {
Pawan Wagh7063b522022-09-28 18:52:26 +00001162 std::ostringstream logStream;
1163 logStream << "About to read/write, write size = " << mOut.dataSize() << "\n";
1164 std::string message = logStream.str();
1165 ALOGI("%s", message.c_str());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001166 }
Elliott Hughes6071da72015-08-12 15:27:47 -07001167#if defined(__ANDROID__)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001168 if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
1169 err = NO_ERROR;
1170 else
1171 err = -errno;
1172#else
1173 err = INVALID_OPERATION;
1174#endif
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -02001175 if (mProcess->mDriverFD < 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +01001176 err = -EBADF;
1177 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001178 IF_LOG_COMMANDS() {
Pawan Wagh7063b522022-09-28 18:52:26 +00001179 std::ostringstream logStream;
1180 logStream << "Finished read/write, write size = " << mOut.dataSize() << "\n";
1181 std::string message = logStream.str();
1182 ALOGI("%s", message.c_str());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001183 }
1184 } while (err == -EINTR);
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001185
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001186 IF_LOG_COMMANDS() {
Pawan Wagh7063b522022-09-28 18:52:26 +00001187 std::ostringstream logStream;
1188 logStream << "Our err: " << (void*)(intptr_t)err
1189 << ", write consumed: " << bwr.write_consumed << " (of " << mOut.dataSize()
1190 << "), read consumed: " << bwr.read_consumed << "\n";
1191 std::string message = logStream.str();
1192 ALOGI("%s", message.c_str());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001193 }
1194
1195 if (err >= NO_ERROR) {
1196 if (bwr.write_consumed > 0) {
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001197 if (bwr.write_consumed < mOut.dataSize())
Steven Morelandb077deb2020-04-16 16:22:52 -07001198 LOG_ALWAYS_FATAL("Driver did not consume write buffer. "
1199 "err: %s consumed: %zu of %zu",
1200 statusToString(err).c_str(),
1201 (size_t)bwr.write_consumed,
1202 mOut.dataSize());
Martijn Coenen7c170bb2018-05-04 17:28:55 -07001203 else {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001204 mOut.setDataSize(0);
Martijn Coenen7c170bb2018-05-04 17:28:55 -07001205 processPostWriteDerefs();
1206 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001207 }
1208 if (bwr.read_consumed > 0) {
1209 mIn.setDataSize(bwr.read_consumed);
1210 mIn.setDataPosition(0);
1211 }
1212 IF_LOG_COMMANDS() {
Pawan Wagh7063b522022-09-28 18:52:26 +00001213 std::ostringstream logStream;
1214 logStream << "Remaining data size: " << mOut.dataSize() << "\n";
1215 logStream << "Received commands from driver: ";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001216 const void* cmds = mIn.data();
1217 const void* end = mIn.data() + mIn.dataSize();
Pawan Wagh7063b522022-09-28 18:52:26 +00001218 logStream << "\t" << HexDump(cmds, mIn.dataSize()) << "\n";
1219 while (cmds < end) cmds = printReturnCommand(logStream, cmds);
1220 std::string message = logStream.str();
1221 ALOGI("%s", message.c_str());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001222 }
1223 return NO_ERROR;
1224 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001225
Theodore Duboisbf144632023-01-09 15:36:49 -08001226 ALOGE_IF(mProcess->mDriverFD >= 0,
1227 "Driver returned error (%s). This is a bug in either libbinder or the driver. This "
1228 "thread's connection to %s will no longer work.",
1229 statusToString(err).c_str(), mProcess->mDriverName.c_str());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001230 return err;
1231}
1232
1233status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
1234 int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
1235{
1236 binder_transaction_data tr;
1237
Arve HjønnevÄg07fd0f12014-02-18 21:10:29 -08001238 tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001239 tr.target.handle = handle;
1240 tr.code = code;
1241 tr.flags = binderFlags;
Evgeniy Stepanovd5474322011-04-21 14:15:00 +04001242 tr.cookie = 0;
1243 tr.sender_pid = 0;
1244 tr.sender_euid = 0;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001245
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001246 const status_t err = data.errorCheck();
1247 if (err == NO_ERROR) {
1248 tr.data_size = data.ipcDataSize();
1249 tr.data.ptr.buffer = data.ipcData();
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001250 tr.offsets_size = data.ipcObjectsCount()*sizeof(binder_size_t);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001251 tr.data.ptr.offsets = data.ipcObjects();
1252 } else if (statusBuffer) {
1253 tr.flags |= TF_STATUS_CODE;
1254 *statusBuffer = err;
1255 tr.data_size = sizeof(status_t);
Arve HjønnevÄg87b30d02014-02-18 21:04:31 -08001256 tr.data.ptr.buffer = reinterpret_cast<uintptr_t>(statusBuffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001257 tr.offsets_size = 0;
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001258 tr.data.ptr.offsets = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001259 } else {
1260 return (mLastError = err);
1261 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001262
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001263 mOut.writeInt32(cmd);
1264 mOut.write(&tr, sizeof(tr));
Tim Murrayd429f4a2017-03-07 09:31:09 -08001265
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001266 return NO_ERROR;
1267}
1268
1269sp<BBinder> the_context_object;
1270
Jiyong Park384328e2020-11-13 17:16:48 +09001271void IPCThreadState::setTheContextObject(const sp<BBinder>& obj)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001272{
1273 the_context_object = obj;
1274}
1275
1276status_t IPCThreadState::executeCommand(int32_t cmd)
1277{
1278 BBinder* obj;
1279 RefBase::weakref_type* refs;
1280 status_t result = NO_ERROR;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001281
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +01001282 switch ((uint32_t)cmd) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001283 case BR_ERROR:
1284 result = mIn.readInt32();
1285 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001286
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001287 case BR_OK:
1288 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001289
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001290 case BR_ACQUIRE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001291 refs = (RefBase::weakref_type*)mIn.readPointer();
1292 obj = (BBinder*)mIn.readPointer();
Steve Block67263472012-01-09 18:35:44 +00001293 ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001294 "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
1295 refs, obj, refs->refBase());
1296 obj->incStrong(mProcess.get());
1297 IF_LOG_REMOTEREFS() {
1298 LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
1299 obj->printRefs();
1300 }
1301 mOut.writeInt32(BC_ACQUIRE_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001302 mOut.writePointer((uintptr_t)refs);
1303 mOut.writePointer((uintptr_t)obj);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001304 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001305
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001306 case BR_RELEASE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001307 refs = (RefBase::weakref_type*)mIn.readPointer();
1308 obj = (BBinder*)mIn.readPointer();
Steve Block67263472012-01-09 18:35:44 +00001309 ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001310 "BR_RELEASE: object %p does not match cookie %p (expected %p)",
1311 refs, obj, refs->refBase());
1312 IF_LOG_REMOTEREFS() {
1313 LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
1314 obj->printRefs();
1315 }
1316 mPendingStrongDerefs.push(obj);
1317 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001318
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001319 case BR_INCREFS:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001320 refs = (RefBase::weakref_type*)mIn.readPointer();
1321 obj = (BBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001322 refs->incWeak(mProcess.get());
1323 mOut.writeInt32(BC_INCREFS_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001324 mOut.writePointer((uintptr_t)refs);
1325 mOut.writePointer((uintptr_t)obj);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001326 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001328 case BR_DECREFS:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001329 refs = (RefBase::weakref_type*)mIn.readPointer();
Jiyong Park5970d0a2022-03-08 16:56:13 +09001330 // NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores)
1331 obj = (BBinder*)mIn.readPointer(); // consume
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001332 // NOTE: This assertion is not valid, because the object may no
1333 // longer exist (thus the (BBinder*)cast above resulting in a different
1334 // memory address).
Steve Block67263472012-01-09 18:35:44 +00001335 //ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001336 // "BR_DECREFS: object %p does not match cookie %p (expected %p)",
1337 // refs, obj, refs->refBase());
1338 mPendingWeakDerefs.push(refs);
1339 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001340
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001341 case BR_ATTEMPT_ACQUIRE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001342 refs = (RefBase::weakref_type*)mIn.readPointer();
1343 obj = (BBinder*)mIn.readPointer();
Tim Murrayd429f4a2017-03-07 09:31:09 -08001344
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001345 {
1346 const bool success = refs->attemptIncStrong(mProcess.get());
Steve Block67263472012-01-09 18:35:44 +00001347 ALOG_ASSERT(success && refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001348 "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
1349 refs, obj, refs->refBase());
Tim Murrayd429f4a2017-03-07 09:31:09 -08001350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001351 mOut.writeInt32(BC_ACQUIRE_RESULT);
1352 mOut.writeInt32((int32_t)success);
1353 }
1354 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001355
Steven Morelandf0212002018-12-26 13:59:23 -08001356 case BR_TRANSACTION_SEC_CTX:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001357 case BR_TRANSACTION:
1358 {
Steven Morelandf0212002018-12-26 13:59:23 -08001359 binder_transaction_data_secctx tr_secctx;
1360 binder_transaction_data& tr = tr_secctx.transaction_data;
1361
1362 if (cmd == (int) BR_TRANSACTION_SEC_CTX) {
1363 result = mIn.read(&tr_secctx, sizeof(tr_secctx));
1364 } else {
1365 result = mIn.read(&tr, sizeof(tr));
1366 tr_secctx.secctx = 0;
1367 }
1368
Steve Block67263472012-01-09 18:35:44 +00001369 ALOG_ASSERT(result == NO_ERROR,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001370 "Not enough command data for brTRANSACTION");
1371 if (result != NO_ERROR) break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001372
Martijn Coenenea0090a2017-11-02 18:54:40 +00001373 Parcel buffer;
1374 buffer.ipcSetDataReference(
1375 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1376 tr.data_size,
1377 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
Steven Moreland161fe122020-11-12 23:16:47 +00001378 tr.offsets_size/sizeof(binder_size_t), freeBuffer);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001379
Steven Moreland39d887d2020-01-31 14:56:45 -08001380 const void* origServingStackPointer = mServingStackPointer;
Steven Moreland35626652021-05-15 01:32:04 +00001381 mServingStackPointer = __builtin_frame_address(0);
Steven Moreland39d887d2020-01-31 14:56:45 -08001382
Martijn Coenenea0090a2017-11-02 18:54:40 +00001383 const pid_t origPid = mCallingPid;
Steven Morelandf0212002018-12-26 13:59:23 -08001384 const char* origSid = mCallingSid;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001385 const uid_t origUid = mCallingUid;
mattgilbride85897672022-10-22 17:42:44 +00001386 const bool origHasExplicitIdentity = mHasExplicitIdentity;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001387 const int32_t origStrictModePolicy = mStrictModePolicy;
1388 const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001389 const int32_t origWorkSource = mWorkSource;
1390 const bool origPropagateWorkSet = mPropagateWorkSource;
1391 // Calling work source will be set by Parcel#enforceInterface. Parcel#enforceInterface
1392 // is only guaranteed to be called for AIDL-generated stubs so we reset the work source
1393 // here to never propagate it.
1394 clearCallingWorkSource();
1395 clearPropagateWorkSource();
Martijn Coenenea0090a2017-11-02 18:54:40 +00001396
1397 mCallingPid = tr.sender_pid;
Steven Morelandf0212002018-12-26 13:59:23 -08001398 mCallingSid = reinterpret_cast<const char*>(tr_secctx.secctx);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001399 mCallingUid = tr.sender_euid;
mattgilbride85897672022-10-22 17:42:44 +00001400 mHasExplicitIdentity = false;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001401 mLastTransactionBinderFlags = tr.flags;
1402
Steven Morelandf0212002018-12-26 13:59:23 -08001403 // ALOGI(">>>> TRANSACT from pid %d sid %s uid %d\n", mCallingPid,
1404 // (mCallingSid ? mCallingSid : "<N/A>"), mCallingUid);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001405
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001406 Parcel reply;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001407 status_t error;
1408 IF_LOG_TRANSACTIONS() {
Pawan Wagh7063b522022-09-28 18:52:26 +00001409 std::ostringstream logStream;
1410 logStream << "BR_TRANSACTION thr " << (void*)pthread_self() << " / obj "
1411 << tr.target.ptr << " / code " << TypeCode(tr.code) << ": \t" << buffer
1412 << "\n"
1413 << "Data addr = " << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1414 << ", offsets addr="
1415 << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << "\n";
1416 std::string message = logStream.str();
1417 ALOGI("%s", message.c_str());
Martijn Coenenea0090a2017-11-02 18:54:40 +00001418 }
1419 if (tr.target.ptr) {
1420 // We only have a weak reference on the target object, so we must first try to
1421 // safely acquire a strong reference before doing anything else with it.
1422 if (reinterpret_cast<RefBase::weakref_type*>(
1423 tr.target.ptr)->attemptIncStrong(this)) {
1424 error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,
1425 &reply, tr.flags);
1426 reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);
Dianne Hackbornc1114612016-03-21 10:36:54 -07001427 } else {
Martijn Coenenea0090a2017-11-02 18:54:40 +00001428 error = UNKNOWN_TRANSACTION;
Dianne Hackbornc1114612016-03-21 10:36:54 -07001429 }
Brad Fitzpatrick52736032010-08-30 16:01:16 -07001430
Martijn Coenenea0090a2017-11-02 18:54:40 +00001431 } else {
1432 error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001433 }
Dianne Hackborn5ee2c9d2014-09-30 11:30:03 -07001434
Steven Morelandf0212002018-12-26 13:59:23 -08001435 //ALOGI("<<<< TRANSACT from pid %d restore pid %d sid %s uid %d\n",
1436 // mCallingPid, origPid, (origSid ? origSid : "<N/A>"), origUid);
Tim Murrayd429f4a2017-03-07 09:31:09 -08001437
Martijn Coenenea0090a2017-11-02 18:54:40 +00001438 if ((tr.flags & TF_ONE_WAY) == 0) {
1439 LOG_ONEWAY("Sending reply to %d!", mCallingPid);
1440 if (error < NO_ERROR) reply.setError(error);
Steven Morelandf183fdd2020-10-27 00:12:12 +00001441
Steven Morelandce15b9f2022-09-08 17:42:45 +00001442 // b/238777741: clear buffer before we send the reply.
1443 // Otherwise, there is a race where the client may
1444 // receive the reply and send another transaction
1445 // here and the space used by this transaction won't
1446 // be freed for the client.
1447 buffer.setDataSize(0);
1448
Steven Morelandf183fdd2020-10-27 00:12:12 +00001449 constexpr uint32_t kForwardReplyFlags = TF_CLEAR_BUF;
1450 sendReply(reply, (tr.flags & kForwardReplyFlags));
Martijn Coenenea0090a2017-11-02 18:54:40 +00001451 } else {
Steven Moreland80844f72020-12-12 02:06:08 +00001452 if (error != OK) {
Pawan Wagh7063b522022-09-28 18:52:26 +00001453 std::ostringstream logStream;
1454 logStream << "oneway function results for code " << tr.code << " on binder at "
1455 << reinterpret_cast<void*>(tr.target.ptr)
1456 << " will be dropped but finished with status "
1457 << statusToString(error);
Steven Moreland80844f72020-12-12 02:06:08 +00001458
1459 // ideally we could log this even when error == OK, but it
1460 // causes too much logspam because some manually-written
1461 // interfaces have clients that call methods which always
1462 // write results, sometimes as oneway methods.
1463 if (reply.dataSize() != 0) {
Pawan Wagh7063b522022-09-28 18:52:26 +00001464 logStream << " and reply parcel size " << reply.dataSize();
Steven Moreland80844f72020-12-12 02:06:08 +00001465 }
Pawan Wagh7063b522022-09-28 18:52:26 +00001466 std::string message = logStream.str();
1467 ALOGI("%s", message.c_str());
Steven Morelandce66b8a2020-02-10 14:43:14 -08001468 }
Martijn Coenenea0090a2017-11-02 18:54:40 +00001469 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1470 }
1471
Steven Moreland39d887d2020-01-31 14:56:45 -08001472 mServingStackPointer = origServingStackPointer;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001473 mCallingPid = origPid;
Steven Morelandf0212002018-12-26 13:59:23 -08001474 mCallingSid = origSid;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001475 mCallingUid = origUid;
mattgilbride85897672022-10-22 17:42:44 +00001476 mHasExplicitIdentity = origHasExplicitIdentity;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001477 mStrictModePolicy = origStrictModePolicy;
1478 mLastTransactionBinderFlags = origTransactionBinderFlags;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001479 mWorkSource = origWorkSource;
1480 mPropagateWorkSource = origPropagateWorkSet;
Christopher Tate440fd872010-03-18 17:55:03 -07001481
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001482 IF_LOG_TRANSACTIONS() {
Pawan Wagh7063b522022-09-28 18:52:26 +00001483 std::ostringstream logStream;
1484 logStream << "BC_REPLY thr " << (void*)pthread_self() << " / obj " << tr.target.ptr
1485 << ": \t" << reply << "\n";
1486 std::string message = logStream.str();
1487 ALOGI("%s", message.c_str());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001488 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001489
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001490 }
1491 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001492
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001493 case BR_DEAD_BINDER:
1494 {
Serban Constantinescuf683e012013-11-05 16:53:55 +00001495 BpBinder *proxy = (BpBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001496 proxy->sendObituary();
1497 mOut.writeInt32(BC_DEAD_BINDER_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001498 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001499 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001500
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001501 case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1502 {
Serban Constantinescuf683e012013-11-05 16:53:55 +00001503 BpBinder *proxy = (BpBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001504 proxy->getWeakRefs()->decWeak(proxy);
1505 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001506
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001507 case BR_FINISHED:
1508 result = TIMED_OUT;
1509 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001510
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001511 case BR_NOOP:
1512 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001513
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001514 case BR_SPAWN_LOOPER:
1515 mProcess->spawnPooledThread(false);
1516 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001517
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001518 default:
liangweikanga43ee152016-10-25 16:37:54 +08001519 ALOGE("*** BAD COMMAND %d received from Binder driver\n", cmd);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001520 result = UNKNOWN_ERROR;
1521 break;
1522 }
1523
1524 if (result != NO_ERROR) {
1525 mLastError = result;
1526 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001527
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001528 return result;
1529}
1530
Steven Moreland39d887d2020-01-31 14:56:45 -08001531const void* IPCThreadState::getServingStackPointer() const {
1532 return mServingStackPointer;
Jayant Chowdharydac6dc82018-10-01 22:52:44 +00001533}
1534
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001535void IPCThreadState::threadDestructor(void *st)
1536{
Todd Poynor8d96cab2013-06-25 19:12:18 -07001537 IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1538 if (self) {
1539 self->flushCommands();
Elliott Hughes6071da72015-08-12 15:27:47 -07001540#if defined(__ANDROID__)
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -02001541 if (self->mProcess->mDriverFD >= 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +01001542 ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1543 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001544#endif
Todd Poynor8d96cab2013-06-25 19:12:18 -07001545 delete self;
1546 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001547}
1548
Li Li6f059292021-09-10 09:59:30 -07001549status_t IPCThreadState::getProcessFreezeInfo(pid_t pid, uint32_t *sync_received,
1550 uint32_t *async_received)
1551{
1552 int ret = 0;
Jiyong Park5970d0a2022-03-08 16:56:13 +09001553 binder_frozen_status_info info = {};
Li Li6f059292021-09-10 09:59:30 -07001554 info.pid = pid;
1555
1556#if defined(__ANDROID__)
1557 if (ioctl(self()->mProcess->mDriverFD, BINDER_GET_FROZEN_INFO, &info) < 0)
1558 ret = -errno;
1559#endif
1560 *sync_received = info.sync_recv;
1561 *async_received = info.async_recv;
1562
1563 return ret;
1564}
Li Li6f059292021-09-10 09:59:30 -07001565
Marco Ballesio7ee17572020-09-08 10:30:03 -07001566status_t IPCThreadState::freeze(pid_t pid, bool enable, uint32_t timeout_ms) {
1567 struct binder_freeze_info info;
1568 int ret = 0;
1569
1570 info.pid = pid;
1571 info.enable = enable;
1572 info.timeout_ms = timeout_ms;
1573
1574
1575#if defined(__ANDROID__)
1576 if (ioctl(self()->mProcess->mDriverFD, BINDER_FREEZE, &info) < 0)
1577 ret = -errno;
1578#endif
1579
1580 //
1581 // ret==-EAGAIN indicates that transactions have not drained.
1582 // Call again to poll for completion.
1583 //
1584 return ret;
1585}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001586
Carlos Llamasb235b122021-12-20 06:38:44 -08001587void IPCThreadState::logExtendedError() {
1588 struct binder_extended_error ee = {.command = BR_OK};
1589
1590 if (!ProcessState::isDriverFeatureEnabled(ProcessState::DriverFeature::EXTENDED_ERROR))
1591 return;
1592
1593#if defined(__ANDROID__)
1594 if (ioctl(self()->mProcess->mDriverFD, BINDER_GET_EXTENDED_ERROR, &ee) < 0) {
1595 ALOGE("Failed to get extended error: %s", strerror(errno));
1596 return;
1597 }
1598#endif
1599
1600 ALOGE_IF(ee.command != BR_OK, "Binder transaction failure: %d/%d/%d",
1601 ee.id, ee.command, ee.param);
1602}
1603
Frederick Mayle53b6ffe2022-07-15 20:14:01 +00001604void IPCThreadState::freeBuffer(const uint8_t* data, size_t /*dataSize*/,
1605 const binder_size_t* /*objects*/, size_t /*objectsSize*/) {
Steve Blocka19954a2012-01-04 20:05:49 +00001606 //ALOGI("Freeing parcel %p", &parcel);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001607 IF_LOG_COMMANDS() {
Pawan Wagh7063b522022-09-28 18:52:26 +00001608 std::ostringstream logStream;
1609 logStream << "Writing BC_FREE_BUFFER for " << data << "\n";
1610 std::string message = logStream.str();
1611 ALOGI("%s", message.c_str());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001612 }
Steve Block67263472012-01-09 18:35:44 +00001613 ALOG_ASSERT(data != NULL, "Called with NULL data");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001614 IPCThreadState* state = self();
1615 state->mOut.writeInt32(BC_FREE_BUFFER);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001616 state->mOut.writePointer((uintptr_t)data);
Martijn Coenen0442a862017-11-17 10:46:32 +01001617 state->flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001618}
1619
Steven Moreland61ff8492019-09-26 16:05:45 -07001620} // namespace android