blob: 9e04ffeb11e7034aedc8dd54452ac617b946c30b [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 Moreland35626652021-05-15 01:32:04 +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 Moreland35626652021-05-15 01:32:04 +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 Moreland35626652021-05-15 01:32:04 +0000381 checkContextIsBinderForUse(__func__);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800382 return mCallingUid;
383}
384
Steven Moreland35626652021-05-15 01:32:04 +0000385const IPCThreadState::SpGuard* IPCThreadState::pushGetCallingSpGuard(const SpGuard* guard) {
386 const SpGuard* orig = mServingStackPointerGuard;
387 mServingStackPointerGuard = guard;
388 return orig;
389}
390
391void IPCThreadState::restoreGetCallingSpGuard(const SpGuard* guard) {
392 mServingStackPointerGuard = guard;
393}
394
395void IPCThreadState::checkContextIsBinderForUse(const char* use) const {
396 if (LIKELY(mServingStackPointerGuard == nullptr)) return;
397
398 if (!mServingStackPointer || mServingStackPointerGuard->address < mServingStackPointer) {
399 LOG_ALWAYS_FATAL("In context %s, %s does not make sense (binder sp: %p, guard: %p).",
400 mServingStackPointerGuard->context, use, mServingStackPointer,
401 mServingStackPointerGuard->address);
402 }
403
404 // in the case mServingStackPointer is deeper in the stack than the guard,
405 // we must be serving a binder transaction (maybe nested). This is a binder
406 // context, so we don't abort
407}
408
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409int64_t IPCThreadState::clearCallingIdentity()
410{
Steven Morelandf0212002018-12-26 13:59:23 -0800411 // ignore mCallingSid for legacy reasons
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800412 int64_t token = ((int64_t)mCallingUid<<32) | mCallingPid;
413 clearCaller();
414 return token;
415}
416
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700417void IPCThreadState::setStrictModePolicy(int32_t policy)
418{
419 mStrictModePolicy = policy;
420}
421
Brad Fitzpatricka877cd82010-07-07 16:06:39 -0700422int32_t IPCThreadState::getStrictModePolicy() const
423{
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700424 return mStrictModePolicy;
425}
426
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000427int64_t IPCThreadState::setCallingWorkSourceUid(uid_t uid)
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100428{
Olivier Gaillard91a04802018-11-14 17:32:41 +0000429 int64_t token = setCallingWorkSourceUidWithoutPropagation(uid);
430 mPropagateWorkSource = true;
431 return token;
432}
433
434int64_t IPCThreadState::setCallingWorkSourceUidWithoutPropagation(uid_t uid)
435{
436 const int64_t propagatedBit = ((int64_t)mPropagateWorkSource) << kWorkSourcePropagatedBitIndex;
437 int64_t token = propagatedBit | mWorkSource;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100438 mWorkSource = uid;
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000439 return token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100440}
441
Olivier Gaillard91a04802018-11-14 17:32:41 +0000442void IPCThreadState::clearPropagateWorkSource()
443{
444 mPropagateWorkSource = false;
445}
446
447bool IPCThreadState::shouldPropagateWorkSource() const
448{
449 return mPropagateWorkSource;
450}
451
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000452uid_t IPCThreadState::getCallingWorkSourceUid() const
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100453{
454 return mWorkSource;
455}
456
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000457int64_t IPCThreadState::clearCallingWorkSource()
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100458{
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000459 return setCallingWorkSourceUid(kUnsetWorkSource);
460}
461
462void IPCThreadState::restoreCallingWorkSource(int64_t token)
463{
464 uid_t uid = (int)token;
Olivier Gaillard91a04802018-11-14 17:32:41 +0000465 setCallingWorkSourceUidWithoutPropagation(uid);
466 mPropagateWorkSource = ((token >> kWorkSourcePropagatedBitIndex) & 1) == 1;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100467}
468
Brad Fitzpatrick52736032010-08-30 16:01:16 -0700469void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
470{
471 mLastTransactionBinderFlags = flags;
472}
473
474int32_t IPCThreadState::getLastTransactionBinderFlags() const
475{
476 return mLastTransactionBinderFlags;
477}
478
Steven Moreland9514b202020-09-21 18:03:27 +0000479void IPCThreadState::setCallRestriction(ProcessState::CallRestriction restriction) {
480 mCallRestriction = restriction;
481}
482
483ProcessState::CallRestriction IPCThreadState::getCallRestriction() const {
484 return mCallRestriction;
485}
486
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800487void IPCThreadState::restoreCallingIdentity(int64_t token)
488{
489 mCallingUid = (int)(token>>32);
Steven Morelandf0212002018-12-26 13:59:23 -0800490 mCallingSid = nullptr; // not enough data to restore
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800491 mCallingPid = (int)token;
492}
493
494void IPCThreadState::clearCaller()
495{
Marco Nelissend43b1942009-07-17 07:59:17 -0700496 mCallingPid = getpid();
Steven Morelandf0212002018-12-26 13:59:23 -0800497 mCallingSid = nullptr; // expensive to lookup
Marco Nelissend43b1942009-07-17 07:59:17 -0700498 mCallingUid = getuid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800499}
500
501void IPCThreadState::flushCommands()
502{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -0200503 if (mProcess->mDriverFD < 0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800504 return;
505 talkWithDriver(false);
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700506 // The flush could have caused post-write refcount decrements to have
507 // been executed, which in turn could result in BC_RELEASE/BC_DECREFS
508 // being queued in mOut. So flush again, if we need to.
509 if (mOut.dataSize() > 0) {
510 talkWithDriver(false);
511 }
512 if (mOut.dataSize() > 0) {
513 ALOGW("mOut.dataSize() > 0 after flushCommands()");
514 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800515}
516
Martijn Coenen0442a862017-11-17 10:46:32 +0100517bool IPCThreadState::flushIfNeeded()
518{
Frankie Changf4c81372021-05-18 13:08:05 +0800519 if (mIsLooper || mServingStackPointer != nullptr || mIsFlushing) {
Martijn Coenen0442a862017-11-17 10:46:32 +0100520 return false;
521 }
Frankie Changf4c81372021-05-18 13:08:05 +0800522 mIsFlushing = true;
Martijn Coenen0442a862017-11-17 10:46:32 +0100523 // In case this thread is not a looper and is not currently serving a binder transaction,
524 // there's no guarantee that this thread will call back into the kernel driver any time
525 // soon. Therefore, flush pending commands such as BC_FREE_BUFFER, to prevent them from getting
526 // stuck in this thread's out buffer.
527 flushCommands();
Frankie Changf4c81372021-05-18 13:08:05 +0800528 mIsFlushing = false;
Martijn Coenen0442a862017-11-17 10:46:32 +0100529 return true;
530}
531
Wale Ogunwale376b8222015-04-13 16:16:10 -0700532void IPCThreadState::blockUntilThreadAvailable()
533{
534 pthread_mutex_lock(&mProcess->mThreadCountLock);
Steven Morelandc648a762021-01-16 02:39:45 +0000535 mProcess->mWaitingForThreads++;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700536 while (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads) {
Wale Ogunwalea3206e62015-04-21 12:29:50 -0700537 ALOGW("Waiting for thread to be free. mExecutingThreadsCount=%lu mMaxThreads=%lu\n",
538 static_cast<unsigned long>(mProcess->mExecutingThreadsCount),
539 static_cast<unsigned long>(mProcess->mMaxThreads));
Wale Ogunwale376b8222015-04-13 16:16:10 -0700540 pthread_cond_wait(&mProcess->mThreadCountDecrement, &mProcess->mThreadCountLock);
541 }
Steven Morelandc648a762021-01-16 02:39:45 +0000542 mProcess->mWaitingForThreads--;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700543 pthread_mutex_unlock(&mProcess->mThreadCountLock);
544}
545
Todd Poynor8d96cab2013-06-25 19:12:18 -0700546status_t IPCThreadState::getAndExecuteCommand()
547{
548 status_t result;
549 int32_t cmd;
550
551 result = talkWithDriver();
552 if (result >= NO_ERROR) {
553 size_t IN = mIn.dataAvail();
554 if (IN < sizeof(int32_t)) return result;
555 cmd = mIn.readInt32();
556 IF_LOG_COMMANDS() {
557 alog << "Processing top-level Command: "
558 << getReturnString(cmd) << endl;
559 }
560
Wale Ogunwale376b8222015-04-13 16:16:10 -0700561 pthread_mutex_lock(&mProcess->mThreadCountLock);
562 mProcess->mExecutingThreadsCount++;
Colin Cross96e83222016-04-15 14:29:55 -0700563 if (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads &&
564 mProcess->mStarvationStartTimeMs == 0) {
565 mProcess->mStarvationStartTimeMs = uptimeMillis();
566 }
Wale Ogunwale376b8222015-04-13 16:16:10 -0700567 pthread_mutex_unlock(&mProcess->mThreadCountLock);
568
Todd Poynor8d96cab2013-06-25 19:12:18 -0700569 result = executeCommand(cmd);
570
Wale Ogunwale376b8222015-04-13 16:16:10 -0700571 pthread_mutex_lock(&mProcess->mThreadCountLock);
572 mProcess->mExecutingThreadsCount--;
Colin Cross96e83222016-04-15 14:29:55 -0700573 if (mProcess->mExecutingThreadsCount < mProcess->mMaxThreads &&
574 mProcess->mStarvationStartTimeMs != 0) {
575 int64_t starvationTimeMs = uptimeMillis() - mProcess->mStarvationStartTimeMs;
576 if (starvationTimeMs > 100) {
577 ALOGE("binder thread pool (%zu threads) starved for %" PRId64 " ms",
578 mProcess->mMaxThreads, starvationTimeMs);
579 }
580 mProcess->mStarvationStartTimeMs = 0;
581 }
Steven Morelandc648a762021-01-16 02:39:45 +0000582
583 // Cond broadcast can be expensive, so don't send it every time a binder
584 // call is processed. b/168806193
585 if (mProcess->mWaitingForThreads > 0) {
586 pthread_cond_broadcast(&mProcess->mThreadCountDecrement);
587 }
Wale Ogunwale376b8222015-04-13 16:16:10 -0700588 pthread_mutex_unlock(&mProcess->mThreadCountLock);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700589 }
590
591 return result;
592}
593
594// When we've cleared the incoming command queue, process any pending derefs
595void IPCThreadState::processPendingDerefs()
596{
597 if (mIn.dataPosition() >= mIn.dataSize()) {
Martijn Coenen0791fbf2017-08-08 15:36:16 +0200598 /*
599 * The decWeak()/decStrong() calls may cause a destructor to run,
600 * which in turn could have initiated an outgoing transaction,
601 * which in turn could cause us to add to the pending refs
602 * vectors; so instead of simply iterating, loop until they're empty.
603 *
604 * We do this in an outer loop, because calling decStrong()
605 * may result in something being added to mPendingWeakDerefs,
606 * which could be delayed until the next incoming command
607 * from the driver if we don't process it now.
608 */
609 while (mPendingWeakDerefs.size() > 0 || mPendingStrongDerefs.size() > 0) {
610 while (mPendingWeakDerefs.size() > 0) {
611 RefBase::weakref_type* refs = mPendingWeakDerefs[0];
612 mPendingWeakDerefs.removeAt(0);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700613 refs->decWeak(mProcess.get());
614 }
Todd Poynor8d96cab2013-06-25 19:12:18 -0700615
Martijn Coenen0791fbf2017-08-08 15:36:16 +0200616 if (mPendingStrongDerefs.size() > 0) {
617 // We don't use while() here because we don't want to re-order
618 // strong and weak decs at all; if this decStrong() causes both a
619 // decWeak() and a decStrong() to be queued, we want to process
620 // the decWeak() first.
621 BBinder* obj = mPendingStrongDerefs[0];
622 mPendingStrongDerefs.removeAt(0);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700623 obj->decStrong(mProcess.get());
624 }
Todd Poynor8d96cab2013-06-25 19:12:18 -0700625 }
626 }
627}
628
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700629void IPCThreadState::processPostWriteDerefs()
630{
631 for (size_t i = 0; i < mPostWriteWeakDerefs.size(); i++) {
632 RefBase::weakref_type* refs = mPostWriteWeakDerefs[i];
633 refs->decWeak(mProcess.get());
634 }
635 mPostWriteWeakDerefs.clear();
636
637 for (size_t i = 0; i < mPostWriteStrongDerefs.size(); i++) {
638 RefBase* obj = mPostWriteStrongDerefs[i];
639 obj->decStrong(mProcess.get());
640 }
641 mPostWriteStrongDerefs.clear();
642}
643
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800644void IPCThreadState::joinThreadPool(bool isMain)
645{
646 LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
647
648 mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800649
Martijn Coenen0442a862017-11-17 10:46:32 +0100650 mIsLooper = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800651 status_t result;
652 do {
Todd Poynor8d96cab2013-06-25 19:12:18 -0700653 processPendingDerefs();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800654 // now get the next command to be processed, waiting if necessary
Todd Poynor8d96cab2013-06-25 19:12:18 -0700655 result = getAndExecuteCommand();
Jason Parksdcd39582009-11-03 12:14:38 -0800656
Todd Poynor8d96cab2013-06-25 19:12:18 -0700657 if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
Steven Moreland6adf33c2019-09-25 13:18:09 -0700658 LOG_ALWAYS_FATAL("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
Jeff Tinkeref073862013-06-11 11:30:21 -0700659 mProcess->mDriverFD, result);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800660 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800661
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800662 // Let this thread exit the thread pool if it is no longer
663 // needed and it is not the main process thread.
664 if(result == TIMED_OUT && !isMain) {
665 break;
666 }
667 } while (result != -ECONNREFUSED && result != -EBADF);
668
Wei Wangc7341432016-10-19 10:23:59 -0700669 LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%d\n",
670 (void*)pthread_self(), getpid(), result);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800671
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800672 mOut.writeInt32(BC_EXIT_LOOPER);
Martijn Coenen0442a862017-11-17 10:46:32 +0100673 mIsLooper = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800674 talkWithDriver(false);
675}
676
Steven Morelandd8c85672020-07-24 21:30:41 +0000677status_t IPCThreadState::setupPolling(int* fd)
Todd Poynor8d96cab2013-06-25 19:12:18 -0700678{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -0200679 if (mProcess->mDriverFD < 0) {
Todd Poynor8d96cab2013-06-25 19:12:18 -0700680 return -EBADF;
681 }
682
683 mOut.writeInt32(BC_ENTER_LOOPER);
Steven Morelandf210b502021-01-15 23:40:32 +0000684 flushCommands();
Todd Poynor8d96cab2013-06-25 19:12:18 -0700685 *fd = mProcess->mDriverFD;
686 return 0;
687}
688
689status_t IPCThreadState::handlePolledCommands()
690{
691 status_t result;
692
693 do {
694 result = getAndExecuteCommand();
695 } while (mIn.dataPosition() < mIn.dataSize());
696
697 processPendingDerefs();
698 flushCommands();
699 return result;
700}
701
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800702void IPCThreadState::stopProcess(bool /*immediate*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800703{
Steve Blocka19954a2012-01-04 20:05:49 +0000704 //ALOGI("**** STOPPING PROCESS");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800705 flushCommands();
706 int fd = mProcess->mDriverFD;
707 mProcess->mDriverFD = -1;
708 close(fd);
709 //kill(getpid(), SIGKILL);
710}
711
712status_t IPCThreadState::transact(int32_t handle,
713 uint32_t code, const Parcel& data,
714 Parcel* reply, uint32_t flags)
715{
Steven Moreland5553ac42020-11-11 02:14:45 +0000716 LOG_ALWAYS_FATAL_IF(data.isForRpc(), "Parcel constructed for RPC, but being used with binder.");
717
Ganesh Mahendran58e5daa2017-10-11 18:05:13 +0800718 status_t err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800719
720 flags |= TF_ACCEPT_FDS;
721
722 IF_LOG_TRANSACTIONS() {
723 TextOutput::Bundle _b(alog);
724 alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
725 << handle << " / code " << TypeCode(code) << ": "
726 << indent << data << dedent << endl;
727 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800728
Ganesh Mahendran58e5daa2017-10-11 18:05:13 +0800729 LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
730 (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
Yi Kongfdd8da92018-06-07 17:52:27 -0700731 err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, nullptr);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800732
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800733 if (err != NO_ERROR) {
734 if (reply) reply->setError(err);
735 return (mLastError = err);
736 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800737
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800738 if ((flags & TF_ONE_WAY) == 0) {
Steven Moreland7732a092019-01-02 17:54:16 -0800739 if (UNLIKELY(mCallRestriction != ProcessState::CallRestriction::NONE)) {
740 if (mCallRestriction == ProcessState::CallRestriction::ERROR_IF_NOT_ONEWAY) {
Steven Moreland8cb34fc2019-05-13 11:44:55 -0700741 ALOGE("Process making non-oneway call (code: %u) but is restricted.", code);
Steven Moreland7732a092019-01-02 17:54:16 -0800742 CallStack::logStack("non-oneway call", CallStack::getCurrent(10).get(),
743 ANDROID_LOG_ERROR);
744 } else /* FATAL_IF_NOT_ONEWAY */ {
Steven Morelandfcc77f12020-09-01 01:16:11 +0000745 LOG_ALWAYS_FATAL("Process may not make non-oneway calls (code: %u).", code);
Steven Moreland7732a092019-01-02 17:54:16 -0800746 }
747 }
748
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700749 #if 0
750 if (code == 4) { // relayout
Steve Blocka19954a2012-01-04 20:05:49 +0000751 ALOGI(">>>>>> CALLING transaction 4");
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700752 } else {
Steve Blocka19954a2012-01-04 20:05:49 +0000753 ALOGI(">>>>>> CALLING transaction %d", code);
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700754 }
755 #endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800756 if (reply) {
757 err = waitForResponse(reply);
758 } else {
759 Parcel fakeReply;
760 err = waitForResponse(&fakeReply);
761 }
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700762 #if 0
763 if (code == 4) { // relayout
Steve Blocka19954a2012-01-04 20:05:49 +0000764 ALOGI("<<<<<< RETURNING transaction 4");
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700765 } else {
Steve Blocka19954a2012-01-04 20:05:49 +0000766 ALOGI("<<<<<< RETURNING transaction %d", code);
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700767 }
768 #endif
Tim Murrayd429f4a2017-03-07 09:31:09 -0800769
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800770 IF_LOG_TRANSACTIONS() {
771 TextOutput::Bundle _b(alog);
772 alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
773 << handle << ": ";
774 if (reply) alog << indent << *reply << dedent << endl;
775 else alog << "(none requested)" << endl;
776 }
777 } else {
Yi Kongfdd8da92018-06-07 17:52:27 -0700778 err = waitForResponse(nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800779 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800780
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800781 return err;
782}
783
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700784void IPCThreadState::incStrongHandle(int32_t handle, BpBinder *proxy)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800785{
786 LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
787 mOut.writeInt32(BC_ACQUIRE);
788 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100789 if (!flushIfNeeded()) {
790 // Create a temp reference until the driver has handled this command.
791 proxy->incStrong(mProcess.get());
792 mPostWriteStrongDerefs.push(proxy);
793 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800794}
795
796void IPCThreadState::decStrongHandle(int32_t handle)
797{
798 LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
799 mOut.writeInt32(BC_RELEASE);
800 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100801 flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800802}
803
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700804void IPCThreadState::incWeakHandle(int32_t handle, BpBinder *proxy)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800805{
806 LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
807 mOut.writeInt32(BC_INCREFS);
808 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100809 if (!flushIfNeeded()) {
810 // Create a temp reference until the driver has handled this command.
811 proxy->getWeakRefs()->incWeak(mProcess.get());
812 mPostWriteWeakDerefs.push(proxy->getWeakRefs());
813 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800814}
815
816void IPCThreadState::decWeakHandle(int32_t handle)
817{
818 LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
819 mOut.writeInt32(BC_DECREFS);
820 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100821 flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800822}
823
824status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
825{
Arve HjønnevÄg11cfdcc2014-02-14 20:14:02 -0800826#if HAS_BC_ATTEMPT_ACQUIRE
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700827 LOG_REMOTEREFS("IPCThreadState::attemptIncStrongHandle(%d)\n", handle);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800828 mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
829 mOut.writeInt32(0); // xxx was thread priority
830 mOut.writeInt32(handle);
831 status_t result = UNKNOWN_ERROR;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800832
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800833 waitForResponse(NULL, &result);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800834
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800835#if LOG_REFCOUNTS
liangweikanga43ee152016-10-25 16:37:54 +0800836 ALOGV("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800837 handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
838#endif
Tim Murrayd429f4a2017-03-07 09:31:09 -0800839
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800840 return result;
Arve HjønnevÄg11cfdcc2014-02-14 20:14:02 -0800841#else
842 (void)handle;
843 ALOGE("%s(%d): Not supported\n", __func__, handle);
844 return INVALID_OPERATION;
845#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800846}
847
848void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
849{
850#if LOG_REFCOUNTS
liangweikanga43ee152016-10-25 16:37:54 +0800851 ALOGV("IPCThreadState::expungeHandle(%ld)\n", handle);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800852#endif
Manoj Gupta9cec85b2017-09-19 16:34:29 -0700853 self()->mProcess->expungeHandle(handle, binder); // NOLINT
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800854}
855
856status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
857{
858 mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
859 mOut.writeInt32((int32_t)handle);
Serban Constantinescuf683e012013-11-05 16:53:55 +0000860 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800861 return NO_ERROR;
862}
863
864status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
865{
866 mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
867 mOut.writeInt32((int32_t)handle);
Serban Constantinescuf683e012013-11-05 16:53:55 +0000868 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800869 return NO_ERROR;
870}
871
872IPCThreadState::IPCThreadState()
Steven Moreland35626652021-05-15 01:32:04 +0000873 : mProcess(ProcessState::self()),
874 mServingStackPointer(nullptr),
875 mServingStackPointerGuard(nullptr),
876 mWorkSource(kUnsetWorkSource),
877 mPropagateWorkSource(false),
878 mIsLooper(false),
Frankie Changf4c81372021-05-18 13:08:05 +0800879 mIsFlushing(false),
Steven Moreland35626652021-05-15 01:32:04 +0000880 mStrictModePolicy(0),
881 mLastTransactionBinderFlags(0),
882 mCallRestriction(mProcess->mCallRestriction) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800883 pthread_setspecific(gTLS, this);
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800884 clearCaller();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800885 mIn.setDataCapacity(256);
886 mOut.setDataCapacity(256);
887}
888
889IPCThreadState::~IPCThreadState()
890{
891}
892
Martijn Coenenea0090a2017-11-02 18:54:40 +0000893status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
894{
895 status_t err;
896 status_t statusBuffer;
897 err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
898 if (err < NO_ERROR) return err;
899
Yi Kongfdd8da92018-06-07 17:52:27 -0700900 return waitForResponse(nullptr, nullptr);
Martijn Coenenea0090a2017-11-02 18:54:40 +0000901}
902
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800903status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
904{
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100905 uint32_t cmd;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800906 int32_t err;
907
908 while (1) {
909 if ((err=talkWithDriver()) < NO_ERROR) break;
910 err = mIn.errorCheck();
911 if (err < NO_ERROR) break;
912 if (mIn.dataAvail() == 0) continue;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800913
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100914 cmd = (uint32_t)mIn.readInt32();
Tim Murrayd429f4a2017-03-07 09:31:09 -0800915
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800916 IF_LOG_COMMANDS() {
917 alog << "Processing waitForResponse Command: "
918 << getReturnString(cmd) << endl;
919 }
920
921 switch (cmd) {
Hang Lub185ac02021-03-24 13:17:22 +0800922 case BR_ONEWAY_SPAM_SUSPECT:
923 ALOGE("Process seems to be sending too many oneway calls.");
924 CallStack::logStack("oneway spamming", CallStack::getCurrent().get(),
925 ANDROID_LOG_ERROR);
926 [[fallthrough]];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800927 case BR_TRANSACTION_COMPLETE:
928 if (!reply && !acquireResult) goto finish;
929 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800930
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800931 case BR_DEAD_REPLY:
932 err = DEAD_OBJECT;
933 goto finish;
934
935 case BR_FAILED_REPLY:
936 err = FAILED_TRANSACTION;
937 goto finish;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800938
Marco Ballesio7ee17572020-09-08 10:30:03 -0700939 case BR_FROZEN_REPLY:
940 err = FAILED_TRANSACTION;
941 goto finish;
942
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800943 case BR_ACQUIRE_RESULT:
944 {
Steve Block67263472012-01-09 18:35:44 +0000945 ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800946 const int32_t result = mIn.readInt32();
947 if (!acquireResult) continue;
948 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
949 }
950 goto finish;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800951
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800952 case BR_REPLY:
953 {
954 binder_transaction_data tr;
955 err = mIn.read(&tr, sizeof(tr));
Steve Block67263472012-01-09 18:35:44 +0000956 ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800957 if (err != NO_ERROR) goto finish;
958
959 if (reply) {
960 if ((tr.flags & TF_STATUS_CODE) == 0) {
961 reply->ipcSetDataReference(
962 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
963 tr.data_size,
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800964 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
965 tr.offsets_size/sizeof(binder_size_t),
Steven Moreland161fe122020-11-12 23:16:47 +0000966 freeBuffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800967 } else {
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800968 err = *reinterpret_cast<const status_t*>(tr.data.ptr.buffer);
Yi Kongfdd8da92018-06-07 17:52:27 -0700969 freeBuffer(nullptr,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800970 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
971 tr.data_size,
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800972 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
Steven Moreland161fe122020-11-12 23:16:47 +0000973 tr.offsets_size/sizeof(binder_size_t));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800974 }
975 } else {
Yi Kongfdd8da92018-06-07 17:52:27 -0700976 freeBuffer(nullptr,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800977 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
978 tr.data_size,
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800979 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
Steven Moreland161fe122020-11-12 23:16:47 +0000980 tr.offsets_size/sizeof(binder_size_t));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800981 continue;
982 }
983 }
984 goto finish;
985
986 default:
987 err = executeCommand(cmd);
988 if (err != NO_ERROR) goto finish;
989 break;
990 }
991 }
992
993finish:
994 if (err != NO_ERROR) {
995 if (acquireResult) *acquireResult = err;
996 if (reply) reply->setError(err);
997 mLastError = err;
998 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800999
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001000 return err;
1001}
1002
1003status_t IPCThreadState::talkWithDriver(bool doReceive)
1004{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -02001005 if (mProcess->mDriverFD < 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +01001006 return -EBADF;
1007 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001008
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001009 binder_write_read bwr;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001010
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001011 // Is the read buffer empty?
1012 const bool needRead = mIn.dataPosition() >= mIn.dataSize();
Tim Murrayd429f4a2017-03-07 09:31:09 -08001013
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001014 // We don't want to write anything if we are still reading
1015 // from data left in the input buffer and the caller
1016 // has requested to read the next data.
1017 const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001018
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001019 bwr.write_size = outAvail;
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001020 bwr.write_buffer = (uintptr_t)mOut.data();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001021
1022 // This is what we'll read.
1023 if (doReceive && needRead) {
1024 bwr.read_size = mIn.dataCapacity();
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001025 bwr.read_buffer = (uintptr_t)mIn.data();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001026 } else {
1027 bwr.read_size = 0;
Ben Chengd640f892011-12-01 17:11:32 -08001028 bwr.read_buffer = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001029 }
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001031 IF_LOG_COMMANDS() {
1032 TextOutput::Bundle _b(alog);
1033 if (outAvail != 0) {
1034 alog << "Sending commands to driver: " << indent;
1035 const void* cmds = (const void*)bwr.write_buffer;
1036 const void* end = ((const uint8_t*)cmds)+bwr.write_size;
1037 alog << HexDump(cmds, bwr.write_size) << endl;
1038 while (cmds < end) cmds = printCommand(alog, cmds);
1039 alog << dedent;
1040 }
1041 alog << "Size of receive buffer: " << bwr.read_size
1042 << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
1043 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001044
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001045 // Return immediately if there is nothing to do.
1046 if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001047
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001048 bwr.write_consumed = 0;
1049 bwr.read_consumed = 0;
1050 status_t err;
1051 do {
1052 IF_LOG_COMMANDS() {
1053 alog << "About to read/write, write size = " << mOut.dataSize() << endl;
1054 }
Elliott Hughes6071da72015-08-12 15:27:47 -07001055#if defined(__ANDROID__)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001056 if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
1057 err = NO_ERROR;
1058 else
1059 err = -errno;
1060#else
1061 err = INVALID_OPERATION;
1062#endif
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -02001063 if (mProcess->mDriverFD < 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +01001064 err = -EBADF;
1065 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001066 IF_LOG_COMMANDS() {
1067 alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
1068 }
1069 } while (err == -EINTR);
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001070
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001071 IF_LOG_COMMANDS() {
Colin Cross6f4f3ab2014-02-05 17:42:44 -08001072 alog << "Our err: " << (void*)(intptr_t)err << ", write consumed: "
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001073 << bwr.write_consumed << " (of " << mOut.dataSize()
Todd Poynor8d96cab2013-06-25 19:12:18 -07001074 << "), read consumed: " << bwr.read_consumed << endl;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001075 }
1076
1077 if (err >= NO_ERROR) {
1078 if (bwr.write_consumed > 0) {
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001079 if (bwr.write_consumed < mOut.dataSize())
Steven Morelandb077deb2020-04-16 16:22:52 -07001080 LOG_ALWAYS_FATAL("Driver did not consume write buffer. "
1081 "err: %s consumed: %zu of %zu",
1082 statusToString(err).c_str(),
1083 (size_t)bwr.write_consumed,
1084 mOut.dataSize());
Martijn Coenen7c170bb2018-05-04 17:28:55 -07001085 else {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001086 mOut.setDataSize(0);
Martijn Coenen7c170bb2018-05-04 17:28:55 -07001087 processPostWriteDerefs();
1088 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001089 }
1090 if (bwr.read_consumed > 0) {
1091 mIn.setDataSize(bwr.read_consumed);
1092 mIn.setDataPosition(0);
1093 }
1094 IF_LOG_COMMANDS() {
1095 TextOutput::Bundle _b(alog);
1096 alog << "Remaining data size: " << mOut.dataSize() << endl;
1097 alog << "Received commands from driver: " << indent;
1098 const void* cmds = mIn.data();
1099 const void* end = mIn.data() + mIn.dataSize();
1100 alog << HexDump(cmds, mIn.dataSize()) << endl;
1101 while (cmds < end) cmds = printReturnCommand(alog, cmds);
1102 alog << dedent;
1103 }
1104 return NO_ERROR;
1105 }
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::writeTransactionData(int32_t cmd, uint32_t binderFlags,
1111 int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
1112{
1113 binder_transaction_data tr;
1114
Arve HjønnevÄg07fd0f12014-02-18 21:10:29 -08001115 tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001116 tr.target.handle = handle;
1117 tr.code = code;
1118 tr.flags = binderFlags;
Evgeniy Stepanovd5474322011-04-21 14:15:00 +04001119 tr.cookie = 0;
1120 tr.sender_pid = 0;
1121 tr.sender_euid = 0;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001123 const status_t err = data.errorCheck();
1124 if (err == NO_ERROR) {
1125 tr.data_size = data.ipcDataSize();
1126 tr.data.ptr.buffer = data.ipcData();
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001127 tr.offsets_size = data.ipcObjectsCount()*sizeof(binder_size_t);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001128 tr.data.ptr.offsets = data.ipcObjects();
1129 } else if (statusBuffer) {
1130 tr.flags |= TF_STATUS_CODE;
1131 *statusBuffer = err;
1132 tr.data_size = sizeof(status_t);
Arve HjønnevÄg87b30d02014-02-18 21:04:31 -08001133 tr.data.ptr.buffer = reinterpret_cast<uintptr_t>(statusBuffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001134 tr.offsets_size = 0;
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001135 tr.data.ptr.offsets = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001136 } else {
1137 return (mLastError = err);
1138 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001139
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001140 mOut.writeInt32(cmd);
1141 mOut.write(&tr, sizeof(tr));
Tim Murrayd429f4a2017-03-07 09:31:09 -08001142
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001143 return NO_ERROR;
1144}
1145
1146sp<BBinder> the_context_object;
1147
Jiyong Park384328e2020-11-13 17:16:48 +09001148void IPCThreadState::setTheContextObject(const sp<BBinder>& obj)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001149{
1150 the_context_object = obj;
1151}
1152
1153status_t IPCThreadState::executeCommand(int32_t cmd)
1154{
1155 BBinder* obj;
1156 RefBase::weakref_type* refs;
1157 status_t result = NO_ERROR;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001158
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +01001159 switch ((uint32_t)cmd) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001160 case BR_ERROR:
1161 result = mIn.readInt32();
1162 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001163
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001164 case BR_OK:
1165 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001166
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001167 case BR_ACQUIRE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001168 refs = (RefBase::weakref_type*)mIn.readPointer();
1169 obj = (BBinder*)mIn.readPointer();
Steve Block67263472012-01-09 18:35:44 +00001170 ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001171 "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
1172 refs, obj, refs->refBase());
1173 obj->incStrong(mProcess.get());
1174 IF_LOG_REMOTEREFS() {
1175 LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
1176 obj->printRefs();
1177 }
1178 mOut.writeInt32(BC_ACQUIRE_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001179 mOut.writePointer((uintptr_t)refs);
1180 mOut.writePointer((uintptr_t)obj);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001181 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001182
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001183 case BR_RELEASE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001184 refs = (RefBase::weakref_type*)mIn.readPointer();
1185 obj = (BBinder*)mIn.readPointer();
Steve Block67263472012-01-09 18:35:44 +00001186 ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001187 "BR_RELEASE: object %p does not match cookie %p (expected %p)",
1188 refs, obj, refs->refBase());
1189 IF_LOG_REMOTEREFS() {
1190 LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
1191 obj->printRefs();
1192 }
1193 mPendingStrongDerefs.push(obj);
1194 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001195
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001196 case BR_INCREFS:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001197 refs = (RefBase::weakref_type*)mIn.readPointer();
1198 obj = (BBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001199 refs->incWeak(mProcess.get());
1200 mOut.writeInt32(BC_INCREFS_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001201 mOut.writePointer((uintptr_t)refs);
1202 mOut.writePointer((uintptr_t)obj);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001203 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001205 case BR_DECREFS:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001206 refs = (RefBase::weakref_type*)mIn.readPointer();
1207 obj = (BBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001208 // NOTE: This assertion is not valid, because the object may no
1209 // longer exist (thus the (BBinder*)cast above resulting in a different
1210 // memory address).
Steve Block67263472012-01-09 18:35:44 +00001211 //ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001212 // "BR_DECREFS: object %p does not match cookie %p (expected %p)",
1213 // refs, obj, refs->refBase());
1214 mPendingWeakDerefs.push(refs);
1215 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001216
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001217 case BR_ATTEMPT_ACQUIRE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001218 refs = (RefBase::weakref_type*)mIn.readPointer();
1219 obj = (BBinder*)mIn.readPointer();
Tim Murrayd429f4a2017-03-07 09:31:09 -08001220
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001221 {
1222 const bool success = refs->attemptIncStrong(mProcess.get());
Steve Block67263472012-01-09 18:35:44 +00001223 ALOG_ASSERT(success && refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001224 "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
1225 refs, obj, refs->refBase());
Tim Murrayd429f4a2017-03-07 09:31:09 -08001226
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001227 mOut.writeInt32(BC_ACQUIRE_RESULT);
1228 mOut.writeInt32((int32_t)success);
1229 }
1230 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001231
Steven Morelandf0212002018-12-26 13:59:23 -08001232 case BR_TRANSACTION_SEC_CTX:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001233 case BR_TRANSACTION:
1234 {
Steven Morelandf0212002018-12-26 13:59:23 -08001235 binder_transaction_data_secctx tr_secctx;
1236 binder_transaction_data& tr = tr_secctx.transaction_data;
1237
1238 if (cmd == (int) BR_TRANSACTION_SEC_CTX) {
1239 result = mIn.read(&tr_secctx, sizeof(tr_secctx));
1240 } else {
1241 result = mIn.read(&tr, sizeof(tr));
1242 tr_secctx.secctx = 0;
1243 }
1244
Steve Block67263472012-01-09 18:35:44 +00001245 ALOG_ASSERT(result == NO_ERROR,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001246 "Not enough command data for brTRANSACTION");
1247 if (result != NO_ERROR) break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001248
Martijn Coenenea0090a2017-11-02 18:54:40 +00001249 Parcel buffer;
1250 buffer.ipcSetDataReference(
1251 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1252 tr.data_size,
1253 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
Steven Moreland161fe122020-11-12 23:16:47 +00001254 tr.offsets_size/sizeof(binder_size_t), freeBuffer);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001255
Steven Moreland39d887d2020-01-31 14:56:45 -08001256 const void* origServingStackPointer = mServingStackPointer;
Steven Moreland35626652021-05-15 01:32:04 +00001257 mServingStackPointer = __builtin_frame_address(0);
Steven Moreland39d887d2020-01-31 14:56:45 -08001258
Martijn Coenenea0090a2017-11-02 18:54:40 +00001259 const pid_t origPid = mCallingPid;
Steven Morelandf0212002018-12-26 13:59:23 -08001260 const char* origSid = mCallingSid;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001261 const uid_t origUid = mCallingUid;
1262 const int32_t origStrictModePolicy = mStrictModePolicy;
1263 const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001264 const int32_t origWorkSource = mWorkSource;
1265 const bool origPropagateWorkSet = mPropagateWorkSource;
1266 // Calling work source will be set by Parcel#enforceInterface. Parcel#enforceInterface
1267 // is only guaranteed to be called for AIDL-generated stubs so we reset the work source
1268 // here to never propagate it.
1269 clearCallingWorkSource();
1270 clearPropagateWorkSource();
Martijn Coenenea0090a2017-11-02 18:54:40 +00001271
1272 mCallingPid = tr.sender_pid;
Steven Morelandf0212002018-12-26 13:59:23 -08001273 mCallingSid = reinterpret_cast<const char*>(tr_secctx.secctx);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001274 mCallingUid = tr.sender_euid;
1275 mLastTransactionBinderFlags = tr.flags;
1276
Steven Morelandf0212002018-12-26 13:59:23 -08001277 // ALOGI(">>>> TRANSACT from pid %d sid %s uid %d\n", mCallingPid,
1278 // (mCallingSid ? mCallingSid : "<N/A>"), mCallingUid);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001279
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001280 Parcel reply;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001281 status_t error;
1282 IF_LOG_TRANSACTIONS() {
1283 TextOutput::Bundle _b(alog);
1284 alog << "BR_TRANSACTION thr " << (void*)pthread_self()
1285 << " / obj " << tr.target.ptr << " / code "
1286 << TypeCode(tr.code) << ": " << indent << buffer
1287 << dedent << endl
1288 << "Data addr = "
1289 << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1290 << ", offsets addr="
1291 << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
1292 }
1293 if (tr.target.ptr) {
1294 // We only have a weak reference on the target object, so we must first try to
1295 // safely acquire a strong reference before doing anything else with it.
1296 if (reinterpret_cast<RefBase::weakref_type*>(
1297 tr.target.ptr)->attemptIncStrong(this)) {
1298 error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,
1299 &reply, tr.flags);
1300 reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);
Dianne Hackbornc1114612016-03-21 10:36:54 -07001301 } else {
Martijn Coenenea0090a2017-11-02 18:54:40 +00001302 error = UNKNOWN_TRANSACTION;
Dianne Hackbornc1114612016-03-21 10:36:54 -07001303 }
Brad Fitzpatrick52736032010-08-30 16:01:16 -07001304
Martijn Coenenea0090a2017-11-02 18:54:40 +00001305 } else {
1306 error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001307 }
Dianne Hackborn5ee2c9d2014-09-30 11:30:03 -07001308
Steven Morelandf0212002018-12-26 13:59:23 -08001309 //ALOGI("<<<< TRANSACT from pid %d restore pid %d sid %s uid %d\n",
1310 // mCallingPid, origPid, (origSid ? origSid : "<N/A>"), origUid);
Tim Murrayd429f4a2017-03-07 09:31:09 -08001311
Martijn Coenenea0090a2017-11-02 18:54:40 +00001312 if ((tr.flags & TF_ONE_WAY) == 0) {
1313 LOG_ONEWAY("Sending reply to %d!", mCallingPid);
1314 if (error < NO_ERROR) reply.setError(error);
Steven Morelandf183fdd2020-10-27 00:12:12 +00001315
1316 constexpr uint32_t kForwardReplyFlags = TF_CLEAR_BUF;
1317 sendReply(reply, (tr.flags & kForwardReplyFlags));
Martijn Coenenea0090a2017-11-02 18:54:40 +00001318 } else {
Steven Moreland80844f72020-12-12 02:06:08 +00001319 if (error != OK) {
1320 alog << "oneway function results for code " << tr.code
1321 << " on binder at "
1322 << reinterpret_cast<void*>(tr.target.ptr)
1323 << " will be dropped but finished with status "
1324 << statusToString(error);
1325
1326 // ideally we could log this even when error == OK, but it
1327 // causes too much logspam because some manually-written
1328 // interfaces have clients that call methods which always
1329 // write results, sometimes as oneway methods.
1330 if (reply.dataSize() != 0) {
1331 alog << " and reply parcel size " << reply.dataSize();
1332 }
1333
1334 alog << endl;
Steven Morelandce66b8a2020-02-10 14:43:14 -08001335 }
Martijn Coenenea0090a2017-11-02 18:54:40 +00001336 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1337 }
1338
Steven Moreland39d887d2020-01-31 14:56:45 -08001339 mServingStackPointer = origServingStackPointer;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001340 mCallingPid = origPid;
Steven Morelandf0212002018-12-26 13:59:23 -08001341 mCallingSid = origSid;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001342 mCallingUid = origUid;
1343 mStrictModePolicy = origStrictModePolicy;
1344 mLastTransactionBinderFlags = origTransactionBinderFlags;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001345 mWorkSource = origWorkSource;
1346 mPropagateWorkSource = origPropagateWorkSet;
Christopher Tate440fd872010-03-18 17:55:03 -07001347
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001348 IF_LOG_TRANSACTIONS() {
1349 TextOutput::Bundle _b(alog);
1350 alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
1351 << tr.target.ptr << ": " << indent << reply << dedent << endl;
1352 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001354 }
1355 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001356
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001357 case BR_DEAD_BINDER:
1358 {
Serban Constantinescuf683e012013-11-05 16:53:55 +00001359 BpBinder *proxy = (BpBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001360 proxy->sendObituary();
1361 mOut.writeInt32(BC_DEAD_BINDER_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001362 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001363 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001364
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001365 case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1366 {
Serban Constantinescuf683e012013-11-05 16:53:55 +00001367 BpBinder *proxy = (BpBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001368 proxy->getWeakRefs()->decWeak(proxy);
1369 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001370
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001371 case BR_FINISHED:
1372 result = TIMED_OUT;
1373 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001374
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001375 case BR_NOOP:
1376 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001377
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001378 case BR_SPAWN_LOOPER:
1379 mProcess->spawnPooledThread(false);
1380 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001381
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001382 default:
liangweikanga43ee152016-10-25 16:37:54 +08001383 ALOGE("*** BAD COMMAND %d received from Binder driver\n", cmd);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001384 result = UNKNOWN_ERROR;
1385 break;
1386 }
1387
1388 if (result != NO_ERROR) {
1389 mLastError = result;
1390 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001391
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001392 return result;
1393}
1394
Steven Moreland39d887d2020-01-31 14:56:45 -08001395const void* IPCThreadState::getServingStackPointer() const {
1396 return mServingStackPointer;
Jayant Chowdharydac6dc82018-10-01 22:52:44 +00001397}
1398
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001399void IPCThreadState::threadDestructor(void *st)
1400{
Todd Poynor8d96cab2013-06-25 19:12:18 -07001401 IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1402 if (self) {
1403 self->flushCommands();
Elliott Hughes6071da72015-08-12 15:27:47 -07001404#if defined(__ANDROID__)
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -02001405 if (self->mProcess->mDriverFD >= 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +01001406 ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1407 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001408#endif
Todd Poynor8d96cab2013-06-25 19:12:18 -07001409 delete self;
1410 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001411}
1412
Marco Ballesiob09fc4a2020-09-11 16:17:21 -07001413status_t IPCThreadState::getProcessFreezeInfo(pid_t pid, bool *sync_received, bool *async_received)
1414{
1415 int ret = 0;
1416 binder_frozen_status_info info;
1417 info.pid = pid;
1418
1419#if defined(__ANDROID__)
1420 if (ioctl(self()->mProcess->mDriverFD, BINDER_GET_FROZEN_INFO, &info) < 0)
1421 ret = -errno;
1422#endif
1423 *sync_received = info.sync_recv;
1424 *async_received = info.async_recv;
1425
1426 return ret;
1427}
1428
Li Li6f059292021-09-10 09:59:30 -07001429#ifndef __ANDROID_VNDK__
1430status_t IPCThreadState::getProcessFreezeInfo(pid_t pid, uint32_t *sync_received,
1431 uint32_t *async_received)
1432{
1433 int ret = 0;
1434 binder_frozen_status_info info;
1435 info.pid = pid;
1436
1437#if defined(__ANDROID__)
1438 if (ioctl(self()->mProcess->mDriverFD, BINDER_GET_FROZEN_INFO, &info) < 0)
1439 ret = -errno;
1440#endif
1441 *sync_received = info.sync_recv;
1442 *async_received = info.async_recv;
1443
1444 return ret;
1445}
1446#endif
1447
Marco Ballesio7ee17572020-09-08 10:30:03 -07001448status_t IPCThreadState::freeze(pid_t pid, bool enable, uint32_t timeout_ms) {
1449 struct binder_freeze_info info;
1450 int ret = 0;
1451
1452 info.pid = pid;
1453 info.enable = enable;
1454 info.timeout_ms = timeout_ms;
1455
1456
1457#if defined(__ANDROID__)
1458 if (ioctl(self()->mProcess->mDriverFD, BINDER_FREEZE, &info) < 0)
1459 ret = -errno;
1460#endif
1461
1462 //
1463 // ret==-EAGAIN indicates that transactions have not drained.
1464 // Call again to poll for completion.
1465 //
1466 return ret;
1467}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001468
Colin Cross6f4f3ab2014-02-05 17:42:44 -08001469void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data,
1470 size_t /*dataSize*/,
1471 const binder_size_t* /*objects*/,
Steven Moreland161fe122020-11-12 23:16:47 +00001472 size_t /*objectsSize*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001473{
Steve Blocka19954a2012-01-04 20:05:49 +00001474 //ALOGI("Freeing parcel %p", &parcel);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001475 IF_LOG_COMMANDS() {
1476 alog << "Writing BC_FREE_BUFFER for " << data << endl;
1477 }
Steve Block67263472012-01-09 18:35:44 +00001478 ALOG_ASSERT(data != NULL, "Called with NULL data");
Yi Kongfdd8da92018-06-07 17:52:27 -07001479 if (parcel != nullptr) parcel->closeFileDescriptors();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001480 IPCThreadState* state = self();
1481 state->mOut.writeInt32(BC_FREE_BUFFER);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001482 state->mOut.writePointer((uintptr_t)data);
Martijn Coenen0442a862017-11-17 10:46:32 +01001483 state->flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001484}
1485
Steven Moreland61ff8492019-09-26 16:05:45 -07001486} // namespace android