blob: 18b77e66920fa0c8643de50d2639950b4e7c423e [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#include <utils/threads.h>
31
Hans Boehma997b232019-04-12 16:59:00 -070032#include <atomic>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <errno.h>
Colin Cross96e83222016-04-15 14:29:55 -070034#include <inttypes.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035#include <pthread.h>
36#include <sched.h>
Yabin Cui8fb2d252015-01-26 19:45:47 -080037#include <signal.h>
38#include <stdio.h>
39#include <sys/ioctl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080040#include <sys/resource.h>
Yabin Cui8fb2d252015-01-26 19:45:47 -080041#include <unistd.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080042
Steven Morelanda4853cd2019-07-12 15:44:37 -070043#include "Static.h"
Steven Moreland6ba5a252021-05-04 22:49:00 +000044#include "binder_module.h"
Steven Morelanda4853cd2019-07-12 15:44:37 -070045
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080046#if LOG_NDEBUG
47
48#define IF_LOG_TRANSACTIONS() if (false)
49#define IF_LOG_COMMANDS() if (false)
50#define LOG_REMOTEREFS(...)
51#define IF_LOG_REMOTEREFS() if (false)
Tim Murrayd429f4a2017-03-07 09:31:09 -080052
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053#define LOG_THREADPOOL(...)
54#define LOG_ONEWAY(...)
55
56#else
57
Steve Block9f760152011-10-12 17:27:03 +010058#define IF_LOG_TRANSACTIONS() IF_ALOG(LOG_VERBOSE, "transact")
59#define IF_LOG_COMMANDS() IF_ALOG(LOG_VERBOSE, "ipc")
60#define LOG_REMOTEREFS(...) ALOG(LOG_DEBUG, "remoterefs", __VA_ARGS__)
61#define IF_LOG_REMOTEREFS() IF_ALOG(LOG_DEBUG, "remoterefs")
62#define LOG_THREADPOOL(...) ALOG(LOG_DEBUG, "threadpool", __VA_ARGS__)
63#define LOG_ONEWAY(...) ALOG(LOG_DEBUG, "ipc", __VA_ARGS__)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
65#endif
66
67// ---------------------------------------------------------------------------
68
69namespace android {
70
Chih-Hung Hsieh8e5337d2014-10-24 14:10:09 -070071// Static const and functions will be optimized out if not used,
72// when LOG_NDEBUG and references in IF_LOG_COMMANDS() are optimized out.
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073static const char *kReturnStrings[] = {
Andy McFaddenaefc9cd2011-08-31 07:43:40 -070074 "BR_ERROR",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075 "BR_OK",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076 "BR_TRANSACTION",
77 "BR_REPLY",
78 "BR_ACQUIRE_RESULT",
79 "BR_DEAD_REPLY",
80 "BR_TRANSACTION_COMPLETE",
81 "BR_INCREFS",
82 "BR_ACQUIRE",
83 "BR_RELEASE",
84 "BR_DECREFS",
85 "BR_ATTEMPT_ACQUIRE",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086 "BR_NOOP",
87 "BR_SPAWN_LOOPER",
88 "BR_FINISHED",
89 "BR_DEAD_BINDER",
Andy McFaddenaefc9cd2011-08-31 07:43:40 -070090 "BR_CLEAR_DEATH_NOTIFICATION_DONE",
Steven Morelandf0212002018-12-26 13:59:23 -080091 "BR_FAILED_REPLY",
Hang Lub185ac02021-03-24 13:17:22 +080092 "BR_FROZEN_REPLY",
93 "BR_ONEWAY_SPAM_SUSPECT",
Steven Morelandf0212002018-12-26 13:59:23 -080094 "BR_TRANSACTION_SEC_CTX",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095};
96
97static const char *kCommandStrings[] = {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080098 "BC_TRANSACTION",
99 "BC_REPLY",
100 "BC_ACQUIRE_RESULT",
101 "BC_FREE_BUFFER",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102 "BC_INCREFS",
103 "BC_ACQUIRE",
104 "BC_RELEASE",
105 "BC_DECREFS",
106 "BC_INCREFS_DONE",
107 "BC_ACQUIRE_DONE",
108 "BC_ATTEMPT_ACQUIRE",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800109 "BC_REGISTER_LOOPER",
110 "BC_ENTER_LOOPER",
111 "BC_EXIT_LOOPER",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800112 "BC_REQUEST_DEATH_NOTIFICATION",
113 "BC_CLEAR_DEATH_NOTIFICATION",
114 "BC_DEAD_BINDER_DONE"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800115};
116
Olivier Gaillard91a04802018-11-14 17:32:41 +0000117static const int64_t kWorkSourcePropagatedBitIndex = 32;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100118
songjinshi73a7dde2016-10-18 21:05:56 +0800119static const char* getReturnString(uint32_t cmd)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120{
songjinshi8e486c62019-04-04 11:22:52 +0800121 size_t idx = cmd & _IOC_NRMASK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122 if (idx < sizeof(kReturnStrings) / sizeof(kReturnStrings[0]))
123 return kReturnStrings[idx];
124 else
125 return "unknown";
126}
127
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128static const void* printBinderTransactionData(TextOutput& out, const void* data)
129{
130 const binder_transaction_data* btd =
131 (const binder_transaction_data*)data;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700132 if (btd->target.handle < 1024) {
133 /* want to print descriptors in decimal; guess based on value */
134 out << "target.desc=" << btd->target.handle;
135 } else {
136 out << "target.ptr=" << btd->target.ptr;
137 }
138 out << " (cookie " << btd->cookie << ")" << endl
Jiyong Park16c6e702020-11-13 20:53:12 +0900139 << "code=" << TypeCode(btd->code) << ", flags=" << (void*)(uint64_t)btd->flags << endl
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 << "data=" << btd->data.ptr.buffer << " (" << (void*)btd->data_size
141 << " bytes)" << endl
142 << "offsets=" << btd->data.ptr.offsets << " (" << (void*)btd->offsets_size
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700143 << " bytes)";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800144 return btd+1;
145}
146
147static const void* printReturnCommand(TextOutput& out, const void* _cmd)
148{
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700149 static const size_t N = sizeof(kReturnStrings)/sizeof(kReturnStrings[0]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800150 const int32_t* cmd = (const int32_t*)_cmd;
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100151 uint32_t code = (uint32_t)*cmd++;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700152 size_t cmdIndex = code & 0xff;
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100153 if (code == BR_ERROR) {
Jiyong Park16c6e702020-11-13 20:53:12 +0900154 out << "BR_ERROR: " << (void*)(uint64_t)(*cmd++) << endl;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155 return cmd;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700156 } else if (cmdIndex >= N) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800157 out << "Unknown reply: " << code << endl;
158 return cmd;
159 }
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700160 out << kReturnStrings[cmdIndex];
Tim Murrayd429f4a2017-03-07 09:31:09 -0800161
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162 switch (code) {
163 case BR_TRANSACTION:
164 case BR_REPLY: {
165 out << ": " << indent;
166 cmd = (const int32_t *)printBinderTransactionData(out, cmd);
167 out << dedent;
168 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800169
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800170 case BR_ACQUIRE_RESULT: {
171 const int32_t res = *cmd++;
172 out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
173 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800174
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175 case BR_INCREFS:
176 case BR_ACQUIRE:
177 case BR_RELEASE:
178 case BR_DECREFS: {
179 const int32_t b = *cmd++;
180 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900181 out << ": target=" << (void*)(uint64_t)b << " (cookie " << (void*)(uint64_t)c << ")";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800182 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800184 case BR_ATTEMPT_ACQUIRE: {
185 const int32_t p = *cmd++;
186 const int32_t b = *cmd++;
187 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900188 out << ": target=" << (void*)(uint64_t)b << " (cookie " << (void*)(uint64_t)c
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800189 << "), pri=" << p;
190 } break;
191
192 case BR_DEAD_BINDER:
193 case BR_CLEAR_DEATH_NOTIFICATION_DONE: {
194 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900195 out << ": death cookie " << (void*)(uint64_t)c;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196 } break;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700197
198 default:
199 // no details to show for: BR_OK, BR_DEAD_REPLY,
200 // BR_TRANSACTION_COMPLETE, BR_FINISHED
201 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800203
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800204 out << endl;
205 return cmd;
206}
207
208static const void* printCommand(TextOutput& out, const void* _cmd)
209{
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700210 static const size_t N = sizeof(kCommandStrings)/sizeof(kCommandStrings[0]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800211 const int32_t* cmd = (const int32_t*)_cmd;
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100212 uint32_t code = (uint32_t)*cmd++;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700213 size_t cmdIndex = code & 0xff;
214
215 if (cmdIndex >= N) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800216 out << "Unknown command: " << code << endl;
217 return cmd;
218 }
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700219 out << kCommandStrings[cmdIndex];
220
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800221 switch (code) {
222 case BC_TRANSACTION:
223 case BC_REPLY: {
224 out << ": " << indent;
225 cmd = (const int32_t *)printBinderTransactionData(out, cmd);
226 out << dedent;
227 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800228
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229 case BC_ACQUIRE_RESULT: {
230 const int32_t res = *cmd++;
231 out << ": " << res << (res ? " (SUCCESS)" : " (FAILURE)");
232 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800233
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234 case BC_FREE_BUFFER: {
235 const int32_t buf = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900236 out << ": buffer=" << (void*)(uint64_t)buf;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239 case BC_INCREFS:
240 case BC_ACQUIRE:
241 case BC_RELEASE:
242 case BC_DECREFS: {
243 const int32_t d = *cmd++;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700244 out << ": desc=" << d;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800245 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800246
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 case BC_INCREFS_DONE:
248 case BC_ACQUIRE_DONE: {
249 const int32_t b = *cmd++;
250 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900251 out << ": target=" << (void*)(uint64_t)b << " (cookie " << (void*)(uint64_t)c << ")";
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_ATTEMPT_ACQUIRE: {
255 const int32_t p = *cmd++;
256 const int32_t d = *cmd++;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700257 out << ": desc=" << d << ", pri=" << p;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800259
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800260 case BC_REQUEST_DEATH_NOTIFICATION:
261 case BC_CLEAR_DEATH_NOTIFICATION: {
262 const int32_t h = *cmd++;
263 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900264 out << ": handle=" << h << " (death cookie " << (void*)(uint64_t)c << ")";
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800265 } break;
266
267 case BC_DEAD_BINDER_DONE: {
268 const int32_t c = *cmd++;
Jiyong Park16c6e702020-11-13 20:53:12 +0900269 out << ": death cookie " << (void*)(uint64_t)c;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800270 } break;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700271
272 default:
273 // no details to show for: BC_REGISTER_LOOPER, BC_ENTER_LOOPER,
274 // BC_EXIT_LOOPER
275 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800277
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800278 out << endl;
279 return cmd;
280}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800281
282static pthread_mutex_t gTLSMutex = PTHREAD_MUTEX_INITIALIZER;
Hans Boehma997b232019-04-12 16:59:00 -0700283static std::atomic<bool> gHaveTLS(false);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284static pthread_key_t gTLS = 0;
Hans Boehma997b232019-04-12 16:59:00 -0700285static std::atomic<bool> gShutdown = false;
286static std::atomic<bool> gDisableBackgroundScheduling = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287
288IPCThreadState* IPCThreadState::self()
289{
Hans Boehma997b232019-04-12 16:59:00 -0700290 if (gHaveTLS.load(std::memory_order_acquire)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291restart:
292 const pthread_key_t k = gTLS;
293 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
294 if (st) return st;
295 return new IPCThreadState;
296 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800297
Hans Boehma997b232019-04-12 16:59:00 -0700298 // Racey, heuristic test for simultaneous shutdown.
299 if (gShutdown.load(std::memory_order_relaxed)) {
Andreas Gampef31a3eb2016-02-01 13:21:56 -0800300 ALOGW("Calling IPCThreadState::self() during shutdown is dangerous, expect a crash.\n");
Yi Kongfdd8da92018-06-07 17:52:27 -0700301 return nullptr;
Andreas Gampef31a3eb2016-02-01 13:21:56 -0800302 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800303
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800304 pthread_mutex_lock(&gTLSMutex);
Hans Boehma997b232019-04-12 16:59:00 -0700305 if (!gHaveTLS.load(std::memory_order_relaxed)) {
Andreas Gampef31a3eb2016-02-01 13:21:56 -0800306 int key_create_value = pthread_key_create(&gTLS, threadDestructor);
307 if (key_create_value != 0) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800308 pthread_mutex_unlock(&gTLSMutex);
Andreas Gampef31a3eb2016-02-01 13:21:56 -0800309 ALOGW("IPCThreadState::self() unable to create TLS key, expect a crash: %s\n",
310 strerror(key_create_value));
Yi Kongfdd8da92018-06-07 17:52:27 -0700311 return nullptr;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800312 }
Hans Boehma997b232019-04-12 16:59:00 -0700313 gHaveTLS.store(true, std::memory_order_release);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800314 }
315 pthread_mutex_unlock(&gTLSMutex);
316 goto restart;
317}
318
Brad Fitzpatrick1b608432010-12-13 16:52:35 -0800319IPCThreadState* IPCThreadState::selfOrNull()
320{
Hans Boehma997b232019-04-12 16:59:00 -0700321 if (gHaveTLS.load(std::memory_order_acquire)) {
Brad Fitzpatrick1b608432010-12-13 16:52:35 -0800322 const pthread_key_t k = gTLS;
323 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
324 return st;
325 }
Yi Kongfdd8da92018-06-07 17:52:27 -0700326 return nullptr;
Brad Fitzpatrick1b608432010-12-13 16:52:35 -0800327}
328
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800329void IPCThreadState::shutdown()
330{
Hans Boehma997b232019-04-12 16:59:00 -0700331 gShutdown.store(true, std::memory_order_relaxed);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800332
Hans Boehma997b232019-04-12 16:59:00 -0700333 if (gHaveTLS.load(std::memory_order_acquire)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334 // XXX Need to wait for all thread pool threads to exit!
335 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(gTLS);
336 if (st) {
337 delete st;
Yi Kongfdd8da92018-06-07 17:52:27 -0700338 pthread_setspecific(gTLS, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800339 }
zhongjieff405782016-03-09 15:05:04 +0800340 pthread_key_delete(gTLS);
Hans Boehma997b232019-04-12 16:59:00 -0700341 gHaveTLS.store(false, std::memory_order_release);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342 }
343}
344
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800345void IPCThreadState::disableBackgroundScheduling(bool disable)
346{
Hans Boehma997b232019-04-12 16:59:00 -0700347 gDisableBackgroundScheduling.store(disable, std::memory_order_relaxed);
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800348}
349
Martijn Coenen2b631742017-05-05 11:16:59 -0700350bool IPCThreadState::backgroundSchedulingDisabled()
351{
Hans Boehma997b232019-04-12 16:59:00 -0700352 return gDisableBackgroundScheduling.load(std::memory_order_relaxed);
Martijn Coenen2b631742017-05-05 11:16:59 -0700353}
354
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800355sp<ProcessState> IPCThreadState::process()
356{
357 return mProcess;
358}
359
360status_t IPCThreadState::clearLastError()
361{
362 const status_t err = mLastError;
363 mLastError = NO_ERROR;
364 return err;
365}
366
Dan Stoza9c634fd2014-11-26 12:23:23 -0800367pid_t IPCThreadState::getCallingPid() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800368{
Steven Moreland8e5f3b42021-05-14 02:39:59 +0000369 checkContextIsBinderForUse(__func__);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 return mCallingPid;
371}
372
Steven Morelandf0212002018-12-26 13:59:23 -0800373const char* IPCThreadState::getCallingSid() const
374{
Steven Moreland8e5f3b42021-05-14 02:39:59 +0000375 checkContextIsBinderForUse(__func__);
Steven Morelandf0212002018-12-26 13:59:23 -0800376 return mCallingSid;
377}
378
Dan Stoza9c634fd2014-11-26 12:23:23 -0800379uid_t IPCThreadState::getCallingUid() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380{
Steven Moreland8e5f3b42021-05-14 02:39:59 +0000381 checkContextIsBinderForUse(__func__);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800382 return mCallingUid;
383}
384
Steven Moreland8e5f3b42021-05-14 02:39:59 +0000385IPCThreadState::SpGuard* IPCThreadState::pushGetCallingSpGuard(SpGuard* guard) {
386 SpGuard* orig = mServingStackPointerGuard;
387 mServingStackPointerGuard = guard;
388 return orig;
389}
390
391void IPCThreadState::restoreGetCallingSpGuard(SpGuard* guard) {
392 mServingStackPointerGuard = guard;
393}
394
395void IPCThreadState::checkContextIsBinderForUse(const char* use) const {
396 if (mServingStackPointerGuard == nullptr) return;
397
398 if (!mServingStackPointer || mServingStackPointerGuard < mServingStackPointer) {
399 LOG_ALWAYS_FATAL("In context %s, %s does not make sense.",
400 mServingStackPointerGuard->context, use);
401 }
402
403 // in the case mServingStackPointer is deeper in the stack than the guard,
404 // we must be serving a binder transaction (maybe nested). This is a binder
405 // context, so we don't abort
406}
407
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408int64_t IPCThreadState::clearCallingIdentity()
409{
Steven Morelandf0212002018-12-26 13:59:23 -0800410 // ignore mCallingSid for legacy reasons
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411 int64_t token = ((int64_t)mCallingUid<<32) | mCallingPid;
412 clearCaller();
413 return token;
414}
415
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700416void IPCThreadState::setStrictModePolicy(int32_t policy)
417{
418 mStrictModePolicy = policy;
419}
420
Brad Fitzpatricka877cd82010-07-07 16:06:39 -0700421int32_t IPCThreadState::getStrictModePolicy() const
422{
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700423 return mStrictModePolicy;
424}
425
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000426int64_t IPCThreadState::setCallingWorkSourceUid(uid_t uid)
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100427{
Olivier Gaillard91a04802018-11-14 17:32:41 +0000428 int64_t token = setCallingWorkSourceUidWithoutPropagation(uid);
429 mPropagateWorkSource = true;
430 return token;
431}
432
433int64_t IPCThreadState::setCallingWorkSourceUidWithoutPropagation(uid_t uid)
434{
435 const int64_t propagatedBit = ((int64_t)mPropagateWorkSource) << kWorkSourcePropagatedBitIndex;
436 int64_t token = propagatedBit | mWorkSource;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100437 mWorkSource = uid;
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000438 return token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100439}
440
Olivier Gaillard91a04802018-11-14 17:32:41 +0000441void IPCThreadState::clearPropagateWorkSource()
442{
443 mPropagateWorkSource = false;
444}
445
446bool IPCThreadState::shouldPropagateWorkSource() const
447{
448 return mPropagateWorkSource;
449}
450
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000451uid_t IPCThreadState::getCallingWorkSourceUid() const
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100452{
453 return mWorkSource;
454}
455
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000456int64_t IPCThreadState::clearCallingWorkSource()
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100457{
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000458 return setCallingWorkSourceUid(kUnsetWorkSource);
459}
460
461void IPCThreadState::restoreCallingWorkSource(int64_t token)
462{
463 uid_t uid = (int)token;
Olivier Gaillard91a04802018-11-14 17:32:41 +0000464 setCallingWorkSourceUidWithoutPropagation(uid);
465 mPropagateWorkSource = ((token >> kWorkSourcePropagatedBitIndex) & 1) == 1;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100466}
467
Brad Fitzpatrick52736032010-08-30 16:01:16 -0700468void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
469{
470 mLastTransactionBinderFlags = flags;
471}
472
473int32_t IPCThreadState::getLastTransactionBinderFlags() const
474{
475 return mLastTransactionBinderFlags;
476}
477
Steven Moreland9514b202020-09-21 18:03:27 +0000478void IPCThreadState::setCallRestriction(ProcessState::CallRestriction restriction) {
479 mCallRestriction = restriction;
480}
481
482ProcessState::CallRestriction IPCThreadState::getCallRestriction() const {
483 return mCallRestriction;
484}
485
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800486void IPCThreadState::restoreCallingIdentity(int64_t token)
487{
488 mCallingUid = (int)(token>>32);
Steven Morelandf0212002018-12-26 13:59:23 -0800489 mCallingSid = nullptr; // not enough data to restore
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800490 mCallingPid = (int)token;
491}
492
493void IPCThreadState::clearCaller()
494{
Marco Nelissend43b1942009-07-17 07:59:17 -0700495 mCallingPid = getpid();
Steven Morelandf0212002018-12-26 13:59:23 -0800496 mCallingSid = nullptr; // expensive to lookup
Marco Nelissend43b1942009-07-17 07:59:17 -0700497 mCallingUid = getuid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800498}
499
500void IPCThreadState::flushCommands()
501{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -0200502 if (mProcess->mDriverFD < 0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800503 return;
504 talkWithDriver(false);
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700505 // The flush could have caused post-write refcount decrements to have
506 // been executed, which in turn could result in BC_RELEASE/BC_DECREFS
507 // being queued in mOut. So flush again, if we need to.
508 if (mOut.dataSize() > 0) {
509 talkWithDriver(false);
510 }
511 if (mOut.dataSize() > 0) {
512 ALOGW("mOut.dataSize() > 0 after flushCommands()");
513 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800514}
515
Martijn Coenen0442a862017-11-17 10:46:32 +0100516bool IPCThreadState::flushIfNeeded()
517{
518 if (mIsLooper || mServingStackPointer != nullptr) {
519 return false;
520 }
521 // In case this thread is not a looper and is not currently serving a binder transaction,
522 // there's no guarantee that this thread will call back into the kernel driver any time
523 // soon. Therefore, flush pending commands such as BC_FREE_BUFFER, to prevent them from getting
524 // stuck in this thread's out buffer.
525 flushCommands();
526 return true;
527}
528
Wale Ogunwale376b8222015-04-13 16:16:10 -0700529void IPCThreadState::blockUntilThreadAvailable()
530{
531 pthread_mutex_lock(&mProcess->mThreadCountLock);
Steven Morelandc648a762021-01-16 02:39:45 +0000532 mProcess->mWaitingForThreads++;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700533 while (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads) {
Wale Ogunwalea3206e62015-04-21 12:29:50 -0700534 ALOGW("Waiting for thread to be free. mExecutingThreadsCount=%lu mMaxThreads=%lu\n",
535 static_cast<unsigned long>(mProcess->mExecutingThreadsCount),
536 static_cast<unsigned long>(mProcess->mMaxThreads));
Wale Ogunwale376b8222015-04-13 16:16:10 -0700537 pthread_cond_wait(&mProcess->mThreadCountDecrement, &mProcess->mThreadCountLock);
538 }
Steven Morelandc648a762021-01-16 02:39:45 +0000539 mProcess->mWaitingForThreads--;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700540 pthread_mutex_unlock(&mProcess->mThreadCountLock);
541}
542
Todd Poynor8d96cab2013-06-25 19:12:18 -0700543status_t IPCThreadState::getAndExecuteCommand()
544{
545 status_t result;
546 int32_t cmd;
547
548 result = talkWithDriver();
549 if (result >= NO_ERROR) {
550 size_t IN = mIn.dataAvail();
551 if (IN < sizeof(int32_t)) return result;
552 cmd = mIn.readInt32();
553 IF_LOG_COMMANDS() {
554 alog << "Processing top-level Command: "
555 << getReturnString(cmd) << endl;
556 }
557
Wale Ogunwale376b8222015-04-13 16:16:10 -0700558 pthread_mutex_lock(&mProcess->mThreadCountLock);
559 mProcess->mExecutingThreadsCount++;
Colin Cross96e83222016-04-15 14:29:55 -0700560 if (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads &&
561 mProcess->mStarvationStartTimeMs == 0) {
562 mProcess->mStarvationStartTimeMs = uptimeMillis();
563 }
Wale Ogunwale376b8222015-04-13 16:16:10 -0700564 pthread_mutex_unlock(&mProcess->mThreadCountLock);
565
Todd Poynor8d96cab2013-06-25 19:12:18 -0700566 result = executeCommand(cmd);
567
Wale Ogunwale376b8222015-04-13 16:16:10 -0700568 pthread_mutex_lock(&mProcess->mThreadCountLock);
569 mProcess->mExecutingThreadsCount--;
Colin Cross96e83222016-04-15 14:29:55 -0700570 if (mProcess->mExecutingThreadsCount < mProcess->mMaxThreads &&
571 mProcess->mStarvationStartTimeMs != 0) {
572 int64_t starvationTimeMs = uptimeMillis() - mProcess->mStarvationStartTimeMs;
573 if (starvationTimeMs > 100) {
574 ALOGE("binder thread pool (%zu threads) starved for %" PRId64 " ms",
575 mProcess->mMaxThreads, starvationTimeMs);
576 }
577 mProcess->mStarvationStartTimeMs = 0;
578 }
Steven Morelandc648a762021-01-16 02:39:45 +0000579
580 // Cond broadcast can be expensive, so don't send it every time a binder
581 // call is processed. b/168806193
582 if (mProcess->mWaitingForThreads > 0) {
583 pthread_cond_broadcast(&mProcess->mThreadCountDecrement);
584 }
Wale Ogunwale376b8222015-04-13 16:16:10 -0700585 pthread_mutex_unlock(&mProcess->mThreadCountLock);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700586 }
587
588 return result;
589}
590
591// When we've cleared the incoming command queue, process any pending derefs
592void IPCThreadState::processPendingDerefs()
593{
594 if (mIn.dataPosition() >= mIn.dataSize()) {
Martijn Coenen0791fbf2017-08-08 15:36:16 +0200595 /*
596 * The decWeak()/decStrong() calls may cause a destructor to run,
597 * which in turn could have initiated an outgoing transaction,
598 * which in turn could cause us to add to the pending refs
599 * vectors; so instead of simply iterating, loop until they're empty.
600 *
601 * We do this in an outer loop, because calling decStrong()
602 * may result in something being added to mPendingWeakDerefs,
603 * which could be delayed until the next incoming command
604 * from the driver if we don't process it now.
605 */
606 while (mPendingWeakDerefs.size() > 0 || mPendingStrongDerefs.size() > 0) {
607 while (mPendingWeakDerefs.size() > 0) {
608 RefBase::weakref_type* refs = mPendingWeakDerefs[0];
609 mPendingWeakDerefs.removeAt(0);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700610 refs->decWeak(mProcess.get());
611 }
Todd Poynor8d96cab2013-06-25 19:12:18 -0700612
Martijn Coenen0791fbf2017-08-08 15:36:16 +0200613 if (mPendingStrongDerefs.size() > 0) {
614 // We don't use while() here because we don't want to re-order
615 // strong and weak decs at all; if this decStrong() causes both a
616 // decWeak() and a decStrong() to be queued, we want to process
617 // the decWeak() first.
618 BBinder* obj = mPendingStrongDerefs[0];
619 mPendingStrongDerefs.removeAt(0);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700620 obj->decStrong(mProcess.get());
621 }
Todd Poynor8d96cab2013-06-25 19:12:18 -0700622 }
623 }
624}
625
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700626void IPCThreadState::processPostWriteDerefs()
627{
628 for (size_t i = 0; i < mPostWriteWeakDerefs.size(); i++) {
629 RefBase::weakref_type* refs = mPostWriteWeakDerefs[i];
630 refs->decWeak(mProcess.get());
631 }
632 mPostWriteWeakDerefs.clear();
633
634 for (size_t i = 0; i < mPostWriteStrongDerefs.size(); i++) {
635 RefBase* obj = mPostWriteStrongDerefs[i];
636 obj->decStrong(mProcess.get());
637 }
638 mPostWriteStrongDerefs.clear();
639}
640
Jintao Zhu413a00e2021-01-16 17:42:00 +0800641void IPCThreadState::createTransactionReference(RefBase* ref)
642{
643 ref->incStrong(mProcess.get());
644 mPostWriteStrongDerefs.push(ref);
645}
646
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800647void IPCThreadState::joinThreadPool(bool isMain)
648{
649 LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
650
651 mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800652
Martijn Coenen0442a862017-11-17 10:46:32 +0100653 mIsLooper = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800654 status_t result;
655 do {
Todd Poynor8d96cab2013-06-25 19:12:18 -0700656 processPendingDerefs();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800657 // now get the next command to be processed, waiting if necessary
Todd Poynor8d96cab2013-06-25 19:12:18 -0700658 result = getAndExecuteCommand();
Jason Parksdcd39582009-11-03 12:14:38 -0800659
Todd Poynor8d96cab2013-06-25 19:12:18 -0700660 if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
Steven Moreland6adf33c2019-09-25 13:18:09 -0700661 LOG_ALWAYS_FATAL("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
Jeff Tinkeref073862013-06-11 11:30:21 -0700662 mProcess->mDriverFD, result);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800663 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800664
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800665 // Let this thread exit the thread pool if it is no longer
666 // needed and it is not the main process thread.
667 if(result == TIMED_OUT && !isMain) {
668 break;
669 }
670 } while (result != -ECONNREFUSED && result != -EBADF);
671
Wei Wangc7341432016-10-19 10:23:59 -0700672 LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%d\n",
673 (void*)pthread_self(), getpid(), result);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800674
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800675 mOut.writeInt32(BC_EXIT_LOOPER);
Martijn Coenen0442a862017-11-17 10:46:32 +0100676 mIsLooper = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800677 talkWithDriver(false);
678}
679
Steven Morelandd8c85672020-07-24 21:30:41 +0000680status_t IPCThreadState::setupPolling(int* fd)
Todd Poynor8d96cab2013-06-25 19:12:18 -0700681{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -0200682 if (mProcess->mDriverFD < 0) {
Todd Poynor8d96cab2013-06-25 19:12:18 -0700683 return -EBADF;
684 }
685
686 mOut.writeInt32(BC_ENTER_LOOPER);
Steven Morelandf210b502021-01-15 23:40:32 +0000687 flushCommands();
Todd Poynor8d96cab2013-06-25 19:12:18 -0700688 *fd = mProcess->mDriverFD;
689 return 0;
690}
691
692status_t IPCThreadState::handlePolledCommands()
693{
694 status_t result;
695
696 do {
697 result = getAndExecuteCommand();
698 } while (mIn.dataPosition() < mIn.dataSize());
699
700 processPendingDerefs();
701 flushCommands();
702 return result;
703}
704
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800705void IPCThreadState::stopProcess(bool /*immediate*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800706{
Steve Blocka19954a2012-01-04 20:05:49 +0000707 //ALOGI("**** STOPPING PROCESS");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800708 flushCommands();
709 int fd = mProcess->mDriverFD;
710 mProcess->mDriverFD = -1;
711 close(fd);
712 //kill(getpid(), SIGKILL);
713}
714
715status_t IPCThreadState::transact(int32_t handle,
716 uint32_t code, const Parcel& data,
717 Parcel* reply, uint32_t flags)
718{
Steven Moreland5553ac42020-11-11 02:14:45 +0000719 LOG_ALWAYS_FATAL_IF(data.isForRpc(), "Parcel constructed for RPC, but being used with binder.");
720
Ganesh Mahendran58e5daa2017-10-11 18:05:13 +0800721 status_t err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800722
723 flags |= TF_ACCEPT_FDS;
724
725 IF_LOG_TRANSACTIONS() {
726 TextOutput::Bundle _b(alog);
727 alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
728 << handle << " / code " << TypeCode(code) << ": "
729 << indent << data << dedent << endl;
730 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800731
Ganesh Mahendran58e5daa2017-10-11 18:05:13 +0800732 LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
733 (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
Yi Kongfdd8da92018-06-07 17:52:27 -0700734 err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, nullptr);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800735
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800736 if (err != NO_ERROR) {
737 if (reply) reply->setError(err);
738 return (mLastError = err);
739 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800740
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800741 if ((flags & TF_ONE_WAY) == 0) {
Steven Moreland7732a092019-01-02 17:54:16 -0800742 if (UNLIKELY(mCallRestriction != ProcessState::CallRestriction::NONE)) {
743 if (mCallRestriction == ProcessState::CallRestriction::ERROR_IF_NOT_ONEWAY) {
Steven Moreland8cb34fc2019-05-13 11:44:55 -0700744 ALOGE("Process making non-oneway call (code: %u) but is restricted.", code);
Steven Moreland7732a092019-01-02 17:54:16 -0800745 CallStack::logStack("non-oneway call", CallStack::getCurrent(10).get(),
746 ANDROID_LOG_ERROR);
747 } else /* FATAL_IF_NOT_ONEWAY */ {
Steven Morelandfcc77f12020-09-01 01:16:11 +0000748 LOG_ALWAYS_FATAL("Process may not make non-oneway calls (code: %u).", code);
Steven Moreland7732a092019-01-02 17:54:16 -0800749 }
750 }
751
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700752 #if 0
753 if (code == 4) { // relayout
Steve Blocka19954a2012-01-04 20:05:49 +0000754 ALOGI(">>>>>> CALLING transaction 4");
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700755 } else {
Steve Blocka19954a2012-01-04 20:05:49 +0000756 ALOGI(">>>>>> CALLING transaction %d", code);
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700757 }
758 #endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800759 if (reply) {
760 err = waitForResponse(reply);
761 } else {
762 Parcel fakeReply;
763 err = waitForResponse(&fakeReply);
764 }
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700765 #if 0
766 if (code == 4) { // relayout
Steve Blocka19954a2012-01-04 20:05:49 +0000767 ALOGI("<<<<<< RETURNING transaction 4");
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700768 } else {
Steve Blocka19954a2012-01-04 20:05:49 +0000769 ALOGI("<<<<<< RETURNING transaction %d", code);
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700770 }
771 #endif
Tim Murrayd429f4a2017-03-07 09:31:09 -0800772
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800773 IF_LOG_TRANSACTIONS() {
774 TextOutput::Bundle _b(alog);
775 alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
776 << handle << ": ";
777 if (reply) alog << indent << *reply << dedent << endl;
778 else alog << "(none requested)" << endl;
779 }
780 } else {
Yi Kongfdd8da92018-06-07 17:52:27 -0700781 err = waitForResponse(nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800782 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800783
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800784 return err;
785}
786
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700787void IPCThreadState::incStrongHandle(int32_t handle, BpBinder *proxy)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800788{
789 LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
790 mOut.writeInt32(BC_ACQUIRE);
791 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100792 if (!flushIfNeeded()) {
793 // Create a temp reference until the driver has handled this command.
794 proxy->incStrong(mProcess.get());
795 mPostWriteStrongDerefs.push(proxy);
796 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800797}
798
799void IPCThreadState::decStrongHandle(int32_t handle)
800{
801 LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
802 mOut.writeInt32(BC_RELEASE);
803 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100804 flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800805}
806
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700807void IPCThreadState::incWeakHandle(int32_t handle, BpBinder *proxy)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800808{
809 LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
810 mOut.writeInt32(BC_INCREFS);
811 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100812 if (!flushIfNeeded()) {
813 // Create a temp reference until the driver has handled this command.
814 proxy->getWeakRefs()->incWeak(mProcess.get());
815 mPostWriteWeakDerefs.push(proxy->getWeakRefs());
816 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800817}
818
819void IPCThreadState::decWeakHandle(int32_t handle)
820{
821 LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
822 mOut.writeInt32(BC_DECREFS);
823 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100824 flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800825}
826
827status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
828{
Arve HjønnevÄg11cfdcc2014-02-14 20:14:02 -0800829#if HAS_BC_ATTEMPT_ACQUIRE
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700830 LOG_REMOTEREFS("IPCThreadState::attemptIncStrongHandle(%d)\n", handle);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800831 mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
832 mOut.writeInt32(0); // xxx was thread priority
833 mOut.writeInt32(handle);
834 status_t result = UNKNOWN_ERROR;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800835
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800836 waitForResponse(NULL, &result);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800837
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800838#if LOG_REFCOUNTS
liangweikanga43ee152016-10-25 16:37:54 +0800839 ALOGV("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800840 handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
841#endif
Tim Murrayd429f4a2017-03-07 09:31:09 -0800842
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800843 return result;
Arve HjønnevÄg11cfdcc2014-02-14 20:14:02 -0800844#else
845 (void)handle;
846 ALOGE("%s(%d): Not supported\n", __func__, handle);
847 return INVALID_OPERATION;
848#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800849}
850
851void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
852{
853#if LOG_REFCOUNTS
liangweikanga43ee152016-10-25 16:37:54 +0800854 ALOGV("IPCThreadState::expungeHandle(%ld)\n", handle);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800855#endif
Manoj Gupta9cec85b2017-09-19 16:34:29 -0700856 self()->mProcess->expungeHandle(handle, binder); // NOLINT
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800857}
858
859status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
860{
861 mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
862 mOut.writeInt32((int32_t)handle);
Serban Constantinescuf683e012013-11-05 16:53:55 +0000863 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800864 return NO_ERROR;
865}
866
867status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
868{
869 mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
870 mOut.writeInt32((int32_t)handle);
Serban Constantinescuf683e012013-11-05 16:53:55 +0000871 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800872 return NO_ERROR;
873}
874
875IPCThreadState::IPCThreadState()
Steven Moreland8e5f3b42021-05-14 02:39:59 +0000876 : mProcess(ProcessState::self()),
877 mServingStackPointer(nullptr),
878 mServingStackPointerGuard(nullptr),
879 mWorkSource(kUnsetWorkSource),
880 mPropagateWorkSource(false),
881 mIsLooper(false),
882 mStrictModePolicy(0),
883 mLastTransactionBinderFlags(0),
884 mCallRestriction(mProcess->mCallRestriction) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800885 pthread_setspecific(gTLS, this);
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800886 clearCaller();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800887 mIn.setDataCapacity(256);
888 mOut.setDataCapacity(256);
889}
890
891IPCThreadState::~IPCThreadState()
892{
893}
894
Martijn Coenenea0090a2017-11-02 18:54:40 +0000895status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
896{
897 status_t err;
898 status_t statusBuffer;
899 err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
900 if (err < NO_ERROR) return err;
901
Yi Kongfdd8da92018-06-07 17:52:27 -0700902 return waitForResponse(nullptr, nullptr);
Martijn Coenenea0090a2017-11-02 18:54:40 +0000903}
904
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800905status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
906{
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100907 uint32_t cmd;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800908 int32_t err;
909
910 while (1) {
911 if ((err=talkWithDriver()) < NO_ERROR) break;
912 err = mIn.errorCheck();
913 if (err < NO_ERROR) break;
914 if (mIn.dataAvail() == 0) continue;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800915
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100916 cmd = (uint32_t)mIn.readInt32();
Tim Murrayd429f4a2017-03-07 09:31:09 -0800917
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800918 IF_LOG_COMMANDS() {
919 alog << "Processing waitForResponse Command: "
920 << getReturnString(cmd) << endl;
921 }
922
923 switch (cmd) {
Hang Lub185ac02021-03-24 13:17:22 +0800924 case BR_ONEWAY_SPAM_SUSPECT:
925 ALOGE("Process seems to be sending too many oneway calls.");
926 CallStack::logStack("oneway spamming", CallStack::getCurrent().get(),
927 ANDROID_LOG_ERROR);
928 [[fallthrough]];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800929 case BR_TRANSACTION_COMPLETE:
930 if (!reply && !acquireResult) goto finish;
931 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800932
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800933 case BR_DEAD_REPLY:
934 err = DEAD_OBJECT;
935 goto finish;
936
937 case BR_FAILED_REPLY:
938 err = FAILED_TRANSACTION;
939 goto finish;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800940
Marco Ballesio7ee17572020-09-08 10:30:03 -0700941 case BR_FROZEN_REPLY:
942 err = FAILED_TRANSACTION;
943 goto finish;
944
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800945 case BR_ACQUIRE_RESULT:
946 {
Steve Block67263472012-01-09 18:35:44 +0000947 ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800948 const int32_t result = mIn.readInt32();
949 if (!acquireResult) continue;
950 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
951 }
952 goto finish;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800953
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800954 case BR_REPLY:
955 {
956 binder_transaction_data tr;
957 err = mIn.read(&tr, sizeof(tr));
Steve Block67263472012-01-09 18:35:44 +0000958 ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800959 if (err != NO_ERROR) goto finish;
960
961 if (reply) {
962 if ((tr.flags & TF_STATUS_CODE) == 0) {
963 reply->ipcSetDataReference(
964 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),
967 tr.offsets_size/sizeof(binder_size_t),
Steven Moreland161fe122020-11-12 23:16:47 +0000968 freeBuffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800969 } else {
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800970 err = *reinterpret_cast<const status_t*>(tr.data.ptr.buffer);
Yi Kongfdd8da92018-06-07 17:52:27 -0700971 freeBuffer(nullptr,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800972 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
973 tr.data_size,
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800974 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
Steven Moreland161fe122020-11-12 23:16:47 +0000975 tr.offsets_size/sizeof(binder_size_t));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800976 }
977 } else {
Yi Kongfdd8da92018-06-07 17:52:27 -0700978 freeBuffer(nullptr,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800979 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
980 tr.data_size,
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800981 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
Steven Moreland161fe122020-11-12 23:16:47 +0000982 tr.offsets_size/sizeof(binder_size_t));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800983 continue;
984 }
985 }
986 goto finish;
987
988 default:
989 err = executeCommand(cmd);
990 if (err != NO_ERROR) goto finish;
991 break;
992 }
993 }
994
995finish:
996 if (err != NO_ERROR) {
997 if (acquireResult) *acquireResult = err;
998 if (reply) reply->setError(err);
999 mLastError = err;
1000 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001001
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001002 return err;
1003}
1004
1005status_t IPCThreadState::talkWithDriver(bool doReceive)
1006{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -02001007 if (mProcess->mDriverFD < 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +01001008 return -EBADF;
1009 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001010
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001011 binder_write_read bwr;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001012
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001013 // Is the read buffer empty?
1014 const bool needRead = mIn.dataPosition() >= mIn.dataSize();
Tim Murrayd429f4a2017-03-07 09:31:09 -08001015
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001016 // We don't want to write anything if we are still reading
1017 // from data left in the input buffer and the caller
1018 // has requested to read the next data.
1019 const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001020
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001021 bwr.write_size = outAvail;
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001022 bwr.write_buffer = (uintptr_t)mOut.data();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001023
1024 // This is what we'll read.
1025 if (doReceive && needRead) {
1026 bwr.read_size = mIn.dataCapacity();
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001027 bwr.read_buffer = (uintptr_t)mIn.data();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001028 } else {
1029 bwr.read_size = 0;
Ben Chengd640f892011-12-01 17:11:32 -08001030 bwr.read_buffer = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001031 }
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001033 IF_LOG_COMMANDS() {
1034 TextOutput::Bundle _b(alog);
1035 if (outAvail != 0) {
1036 alog << "Sending commands to driver: " << indent;
1037 const void* cmds = (const void*)bwr.write_buffer;
1038 const void* end = ((const uint8_t*)cmds)+bwr.write_size;
1039 alog << HexDump(cmds, bwr.write_size) << endl;
1040 while (cmds < end) cmds = printCommand(alog, cmds);
1041 alog << dedent;
1042 }
1043 alog << "Size of receive buffer: " << bwr.read_size
1044 << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
1045 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001046
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001047 // Return immediately if there is nothing to do.
1048 if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001049
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001050 bwr.write_consumed = 0;
1051 bwr.read_consumed = 0;
1052 status_t err;
1053 do {
1054 IF_LOG_COMMANDS() {
1055 alog << "About to read/write, write size = " << mOut.dataSize() << endl;
1056 }
Elliott Hughes6071da72015-08-12 15:27:47 -07001057#if defined(__ANDROID__)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001058 if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
1059 err = NO_ERROR;
1060 else
1061 err = -errno;
1062#else
1063 err = INVALID_OPERATION;
1064#endif
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -02001065 if (mProcess->mDriverFD < 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +01001066 err = -EBADF;
1067 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001068 IF_LOG_COMMANDS() {
1069 alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
1070 }
1071 } while (err == -EINTR);
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001072
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001073 IF_LOG_COMMANDS() {
Colin Cross6f4f3ab2014-02-05 17:42:44 -08001074 alog << "Our err: " << (void*)(intptr_t)err << ", write consumed: "
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001075 << bwr.write_consumed << " (of " << mOut.dataSize()
Todd Poynor8d96cab2013-06-25 19:12:18 -07001076 << "), read consumed: " << bwr.read_consumed << endl;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001077 }
1078
1079 if (err >= NO_ERROR) {
1080 if (bwr.write_consumed > 0) {
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001081 if (bwr.write_consumed < mOut.dataSize())
Steven Morelandb077deb2020-04-16 16:22:52 -07001082 LOG_ALWAYS_FATAL("Driver did not consume write buffer. "
1083 "err: %s consumed: %zu of %zu",
1084 statusToString(err).c_str(),
1085 (size_t)bwr.write_consumed,
1086 mOut.dataSize());
Martijn Coenen7c170bb2018-05-04 17:28:55 -07001087 else {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001088 mOut.setDataSize(0);
Martijn Coenen7c170bb2018-05-04 17:28:55 -07001089 processPostWriteDerefs();
1090 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001091 }
1092 if (bwr.read_consumed > 0) {
1093 mIn.setDataSize(bwr.read_consumed);
1094 mIn.setDataPosition(0);
1095 }
1096 IF_LOG_COMMANDS() {
1097 TextOutput::Bundle _b(alog);
1098 alog << "Remaining data size: " << mOut.dataSize() << endl;
1099 alog << "Received commands from driver: " << indent;
1100 const void* cmds = mIn.data();
1101 const void* end = mIn.data() + mIn.dataSize();
1102 alog << HexDump(cmds, mIn.dataSize()) << endl;
1103 while (cmds < end) cmds = printReturnCommand(alog, cmds);
1104 alog << dedent;
1105 }
1106 return NO_ERROR;
1107 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001108
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001109 return err;
1110}
1111
1112status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
1113 int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
1114{
1115 binder_transaction_data tr;
1116
Arve HjønnevÄg07fd0f12014-02-18 21:10:29 -08001117 tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001118 tr.target.handle = handle;
1119 tr.code = code;
1120 tr.flags = binderFlags;
Evgeniy Stepanovd5474322011-04-21 14:15:00 +04001121 tr.cookie = 0;
1122 tr.sender_pid = 0;
1123 tr.sender_euid = 0;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001125 const status_t err = data.errorCheck();
1126 if (err == NO_ERROR) {
1127 tr.data_size = data.ipcDataSize();
1128 tr.data.ptr.buffer = data.ipcData();
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001129 tr.offsets_size = data.ipcObjectsCount()*sizeof(binder_size_t);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001130 tr.data.ptr.offsets = data.ipcObjects();
1131 } else if (statusBuffer) {
1132 tr.flags |= TF_STATUS_CODE;
1133 *statusBuffer = err;
1134 tr.data_size = sizeof(status_t);
Arve HjønnevÄg87b30d02014-02-18 21:04:31 -08001135 tr.data.ptr.buffer = reinterpret_cast<uintptr_t>(statusBuffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001136 tr.offsets_size = 0;
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001137 tr.data.ptr.offsets = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001138 } else {
1139 return (mLastError = err);
1140 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001141
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001142 mOut.writeInt32(cmd);
1143 mOut.write(&tr, sizeof(tr));
Tim Murrayd429f4a2017-03-07 09:31:09 -08001144
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001145 return NO_ERROR;
1146}
1147
1148sp<BBinder> the_context_object;
1149
Jiyong Park384328e2020-11-13 17:16:48 +09001150void IPCThreadState::setTheContextObject(const sp<BBinder>& obj)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001151{
1152 the_context_object = obj;
1153}
1154
1155status_t IPCThreadState::executeCommand(int32_t cmd)
1156{
1157 BBinder* obj;
1158 RefBase::weakref_type* refs;
1159 status_t result = NO_ERROR;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001160
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +01001161 switch ((uint32_t)cmd) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001162 case BR_ERROR:
1163 result = mIn.readInt32();
1164 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001165
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001166 case BR_OK:
1167 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001168
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001169 case BR_ACQUIRE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001170 refs = (RefBase::weakref_type*)mIn.readPointer();
1171 obj = (BBinder*)mIn.readPointer();
Steve Block67263472012-01-09 18:35:44 +00001172 ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001173 "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
1174 refs, obj, refs->refBase());
1175 obj->incStrong(mProcess.get());
1176 IF_LOG_REMOTEREFS() {
1177 LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
1178 obj->printRefs();
1179 }
1180 mOut.writeInt32(BC_ACQUIRE_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001181 mOut.writePointer((uintptr_t)refs);
1182 mOut.writePointer((uintptr_t)obj);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001183 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001184
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001185 case BR_RELEASE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001186 refs = (RefBase::weakref_type*)mIn.readPointer();
1187 obj = (BBinder*)mIn.readPointer();
Steve Block67263472012-01-09 18:35:44 +00001188 ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001189 "BR_RELEASE: object %p does not match cookie %p (expected %p)",
1190 refs, obj, refs->refBase());
1191 IF_LOG_REMOTEREFS() {
1192 LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
1193 obj->printRefs();
1194 }
1195 mPendingStrongDerefs.push(obj);
1196 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001197
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001198 case BR_INCREFS:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001199 refs = (RefBase::weakref_type*)mIn.readPointer();
1200 obj = (BBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001201 refs->incWeak(mProcess.get());
1202 mOut.writeInt32(BC_INCREFS_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001203 mOut.writePointer((uintptr_t)refs);
1204 mOut.writePointer((uintptr_t)obj);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001205 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001206
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001207 case BR_DECREFS:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001208 refs = (RefBase::weakref_type*)mIn.readPointer();
1209 obj = (BBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001210 // NOTE: This assertion is not valid, because the object may no
1211 // longer exist (thus the (BBinder*)cast above resulting in a different
1212 // memory address).
Steve Block67263472012-01-09 18:35:44 +00001213 //ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001214 // "BR_DECREFS: object %p does not match cookie %p (expected %p)",
1215 // refs, obj, refs->refBase());
1216 mPendingWeakDerefs.push(refs);
1217 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001218
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001219 case BR_ATTEMPT_ACQUIRE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001220 refs = (RefBase::weakref_type*)mIn.readPointer();
1221 obj = (BBinder*)mIn.readPointer();
Tim Murrayd429f4a2017-03-07 09:31:09 -08001222
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001223 {
1224 const bool success = refs->attemptIncStrong(mProcess.get());
Steve Block67263472012-01-09 18:35:44 +00001225 ALOG_ASSERT(success && refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001226 "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
1227 refs, obj, refs->refBase());
Tim Murrayd429f4a2017-03-07 09:31:09 -08001228
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001229 mOut.writeInt32(BC_ACQUIRE_RESULT);
1230 mOut.writeInt32((int32_t)success);
1231 }
1232 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001233
Steven Morelandf0212002018-12-26 13:59:23 -08001234 case BR_TRANSACTION_SEC_CTX:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001235 case BR_TRANSACTION:
1236 {
Steven Morelandf0212002018-12-26 13:59:23 -08001237 binder_transaction_data_secctx tr_secctx;
1238 binder_transaction_data& tr = tr_secctx.transaction_data;
1239
1240 if (cmd == (int) BR_TRANSACTION_SEC_CTX) {
1241 result = mIn.read(&tr_secctx, sizeof(tr_secctx));
1242 } else {
1243 result = mIn.read(&tr, sizeof(tr));
1244 tr_secctx.secctx = 0;
1245 }
1246
Steve Block67263472012-01-09 18:35:44 +00001247 ALOG_ASSERT(result == NO_ERROR,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001248 "Not enough command data for brTRANSACTION");
1249 if (result != NO_ERROR) break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001250
Martijn Coenenea0090a2017-11-02 18:54:40 +00001251 Parcel buffer;
1252 buffer.ipcSetDataReference(
1253 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1254 tr.data_size,
1255 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
Steven Moreland161fe122020-11-12 23:16:47 +00001256 tr.offsets_size/sizeof(binder_size_t), freeBuffer);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001257
Steven Moreland39d887d2020-01-31 14:56:45 -08001258 const void* origServingStackPointer = mServingStackPointer;
1259 mServingStackPointer = &origServingStackPointer; // anything on the stack
1260
Martijn Coenenea0090a2017-11-02 18:54:40 +00001261 const pid_t origPid = mCallingPid;
Steven Morelandf0212002018-12-26 13:59:23 -08001262 const char* origSid = mCallingSid;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001263 const uid_t origUid = mCallingUid;
1264 const int32_t origStrictModePolicy = mStrictModePolicy;
1265 const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001266 const int32_t origWorkSource = mWorkSource;
1267 const bool origPropagateWorkSet = mPropagateWorkSource;
1268 // Calling work source will be set by Parcel#enforceInterface. Parcel#enforceInterface
1269 // is only guaranteed to be called for AIDL-generated stubs so we reset the work source
1270 // here to never propagate it.
1271 clearCallingWorkSource();
1272 clearPropagateWorkSource();
Martijn Coenenea0090a2017-11-02 18:54:40 +00001273
1274 mCallingPid = tr.sender_pid;
Steven Morelandf0212002018-12-26 13:59:23 -08001275 mCallingSid = reinterpret_cast<const char*>(tr_secctx.secctx);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001276 mCallingUid = tr.sender_euid;
1277 mLastTransactionBinderFlags = tr.flags;
1278
Steven Morelandf0212002018-12-26 13:59:23 -08001279 // ALOGI(">>>> TRANSACT from pid %d sid %s uid %d\n", mCallingPid,
1280 // (mCallingSid ? mCallingSid : "<N/A>"), mCallingUid);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001281
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001282 Parcel reply;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001283 status_t error;
1284 IF_LOG_TRANSACTIONS() {
1285 TextOutput::Bundle _b(alog);
1286 alog << "BR_TRANSACTION thr " << (void*)pthread_self()
1287 << " / obj " << tr.target.ptr << " / code "
1288 << TypeCode(tr.code) << ": " << indent << buffer
1289 << dedent << endl
1290 << "Data addr = "
1291 << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1292 << ", offsets addr="
1293 << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
1294 }
1295 if (tr.target.ptr) {
1296 // We only have a weak reference on the target object, so we must first try to
1297 // safely acquire a strong reference before doing anything else with it.
1298 if (reinterpret_cast<RefBase::weakref_type*>(
1299 tr.target.ptr)->attemptIncStrong(this)) {
1300 error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,
1301 &reply, tr.flags);
1302 reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);
Dianne Hackbornc1114612016-03-21 10:36:54 -07001303 } else {
Martijn Coenenea0090a2017-11-02 18:54:40 +00001304 error = UNKNOWN_TRANSACTION;
Dianne Hackbornc1114612016-03-21 10:36:54 -07001305 }
Brad Fitzpatrick52736032010-08-30 16:01:16 -07001306
Martijn Coenenea0090a2017-11-02 18:54:40 +00001307 } else {
1308 error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001309 }
Dianne Hackborn5ee2c9d2014-09-30 11:30:03 -07001310
Steven Morelandf0212002018-12-26 13:59:23 -08001311 //ALOGI("<<<< TRANSACT from pid %d restore pid %d sid %s uid %d\n",
1312 // mCallingPid, origPid, (origSid ? origSid : "<N/A>"), origUid);
Tim Murrayd429f4a2017-03-07 09:31:09 -08001313
Martijn Coenenea0090a2017-11-02 18:54:40 +00001314 if ((tr.flags & TF_ONE_WAY) == 0) {
1315 LOG_ONEWAY("Sending reply to %d!", mCallingPid);
1316 if (error < NO_ERROR) reply.setError(error);
Steven Morelandf183fdd2020-10-27 00:12:12 +00001317
1318 constexpr uint32_t kForwardReplyFlags = TF_CLEAR_BUF;
1319 sendReply(reply, (tr.flags & kForwardReplyFlags));
Martijn Coenenea0090a2017-11-02 18:54:40 +00001320 } else {
Steven Moreland80844f72020-12-12 02:06:08 +00001321 if (error != OK) {
1322 alog << "oneway function results for code " << tr.code
1323 << " on binder at "
1324 << reinterpret_cast<void*>(tr.target.ptr)
1325 << " will be dropped but finished with status "
1326 << statusToString(error);
1327
1328 // ideally we could log this even when error == OK, but it
1329 // causes too much logspam because some manually-written
1330 // interfaces have clients that call methods which always
1331 // write results, sometimes as oneway methods.
1332 if (reply.dataSize() != 0) {
1333 alog << " and reply parcel size " << reply.dataSize();
1334 }
1335
1336 alog << endl;
Steven Morelandce66b8a2020-02-10 14:43:14 -08001337 }
Martijn Coenenea0090a2017-11-02 18:54:40 +00001338 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1339 }
1340
Steven Moreland39d887d2020-01-31 14:56:45 -08001341 mServingStackPointer = origServingStackPointer;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001342 mCallingPid = origPid;
Steven Morelandf0212002018-12-26 13:59:23 -08001343 mCallingSid = origSid;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001344 mCallingUid = origUid;
1345 mStrictModePolicy = origStrictModePolicy;
1346 mLastTransactionBinderFlags = origTransactionBinderFlags;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001347 mWorkSource = origWorkSource;
1348 mPropagateWorkSource = origPropagateWorkSet;
Christopher Tate440fd872010-03-18 17:55:03 -07001349
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001350 IF_LOG_TRANSACTIONS() {
1351 TextOutput::Bundle _b(alog);
1352 alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
1353 << tr.target.ptr << ": " << indent << reply << dedent << endl;
1354 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001355
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001356 }
1357 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001358
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001359 case BR_DEAD_BINDER:
1360 {
Serban Constantinescuf683e012013-11-05 16:53:55 +00001361 BpBinder *proxy = (BpBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001362 proxy->sendObituary();
1363 mOut.writeInt32(BC_DEAD_BINDER_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001364 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001365 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001366
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001367 case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1368 {
Serban Constantinescuf683e012013-11-05 16:53:55 +00001369 BpBinder *proxy = (BpBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001370 proxy->getWeakRefs()->decWeak(proxy);
1371 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001372
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001373 case BR_FINISHED:
1374 result = TIMED_OUT;
1375 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001376
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001377 case BR_NOOP:
1378 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001379
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001380 case BR_SPAWN_LOOPER:
1381 mProcess->spawnPooledThread(false);
1382 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001383
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001384 default:
liangweikanga43ee152016-10-25 16:37:54 +08001385 ALOGE("*** BAD COMMAND %d received from Binder driver\n", cmd);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001386 result = UNKNOWN_ERROR;
1387 break;
1388 }
1389
1390 if (result != NO_ERROR) {
1391 mLastError = result;
1392 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001393
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001394 return result;
1395}
1396
Steven Moreland39d887d2020-01-31 14:56:45 -08001397const void* IPCThreadState::getServingStackPointer() const {
1398 return mServingStackPointer;
Jayant Chowdharydac6dc82018-10-01 22:52:44 +00001399}
1400
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001401void IPCThreadState::threadDestructor(void *st)
1402{
Todd Poynor8d96cab2013-06-25 19:12:18 -07001403 IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1404 if (self) {
1405 self->flushCommands();
Elliott Hughes6071da72015-08-12 15:27:47 -07001406#if defined(__ANDROID__)
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -02001407 if (self->mProcess->mDriverFD >= 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +01001408 ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1409 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001410#endif
Todd Poynor8d96cab2013-06-25 19:12:18 -07001411 delete self;
1412 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001413}
1414
Marco Ballesiob09fc4a2020-09-11 16:17:21 -07001415status_t IPCThreadState::getProcessFreezeInfo(pid_t pid, bool *sync_received, bool *async_received)
1416{
1417 int ret = 0;
1418 binder_frozen_status_info info;
1419 info.pid = pid;
1420
1421#if defined(__ANDROID__)
1422 if (ioctl(self()->mProcess->mDriverFD, BINDER_GET_FROZEN_INFO, &info) < 0)
1423 ret = -errno;
1424#endif
1425 *sync_received = info.sync_recv;
1426 *async_received = info.async_recv;
1427
1428 return ret;
1429}
1430
Marco Ballesio7ee17572020-09-08 10:30:03 -07001431status_t IPCThreadState::freeze(pid_t pid, bool enable, uint32_t timeout_ms) {
1432 struct binder_freeze_info info;
1433 int ret = 0;
1434
1435 info.pid = pid;
1436 info.enable = enable;
1437 info.timeout_ms = timeout_ms;
1438
1439
1440#if defined(__ANDROID__)
1441 if (ioctl(self()->mProcess->mDriverFD, BINDER_FREEZE, &info) < 0)
1442 ret = -errno;
1443#endif
1444
1445 //
1446 // ret==-EAGAIN indicates that transactions have not drained.
1447 // Call again to poll for completion.
1448 //
1449 return ret;
1450}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001451
Colin Cross6f4f3ab2014-02-05 17:42:44 -08001452void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data,
1453 size_t /*dataSize*/,
1454 const binder_size_t* /*objects*/,
Steven Moreland161fe122020-11-12 23:16:47 +00001455 size_t /*objectsSize*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001456{
Steve Blocka19954a2012-01-04 20:05:49 +00001457 //ALOGI("Freeing parcel %p", &parcel);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001458 IF_LOG_COMMANDS() {
1459 alog << "Writing BC_FREE_BUFFER for " << data << endl;
1460 }
Steve Block67263472012-01-09 18:35:44 +00001461 ALOG_ASSERT(data != NULL, "Called with NULL data");
Yi Kongfdd8da92018-06-07 17:52:27 -07001462 if (parcel != nullptr) parcel->closeFileDescriptors();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001463 IPCThreadState* state = self();
1464 state->mOut.writeInt32(BC_FREE_BUFFER);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001465 state->mOut.writePointer((uintptr_t)data);
Martijn Coenen0442a862017-11-17 10:46:32 +01001466 state->flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001467}
1468
Steven Moreland61ff8492019-09-26 16:05:45 -07001469} // namespace android