blob: ef7fd44419b48451a4c225bc3252e233ee052a01 [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{
369 return mCallingPid;
370}
371
Steven Morelandf0212002018-12-26 13:59:23 -0800372const char* IPCThreadState::getCallingSid() const
373{
374 return mCallingSid;
375}
376
Dan Stoza9c634fd2014-11-26 12:23:23 -0800377uid_t IPCThreadState::getCallingUid() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378{
379 return mCallingUid;
380}
381
382int64_t IPCThreadState::clearCallingIdentity()
383{
Steven Morelandf0212002018-12-26 13:59:23 -0800384 // ignore mCallingSid for legacy reasons
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800385 int64_t token = ((int64_t)mCallingUid<<32) | mCallingPid;
386 clearCaller();
387 return token;
388}
389
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700390void IPCThreadState::setStrictModePolicy(int32_t policy)
391{
392 mStrictModePolicy = policy;
393}
394
Brad Fitzpatricka877cd82010-07-07 16:06:39 -0700395int32_t IPCThreadState::getStrictModePolicy() const
396{
Brad Fitzpatrick702ea9d2010-06-18 13:07:53 -0700397 return mStrictModePolicy;
398}
399
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000400int64_t IPCThreadState::setCallingWorkSourceUid(uid_t uid)
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100401{
Olivier Gaillard91a04802018-11-14 17:32:41 +0000402 int64_t token = setCallingWorkSourceUidWithoutPropagation(uid);
403 mPropagateWorkSource = true;
404 return token;
405}
406
407int64_t IPCThreadState::setCallingWorkSourceUidWithoutPropagation(uid_t uid)
408{
409 const int64_t propagatedBit = ((int64_t)mPropagateWorkSource) << kWorkSourcePropagatedBitIndex;
410 int64_t token = propagatedBit | mWorkSource;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100411 mWorkSource = uid;
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000412 return token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100413}
414
Olivier Gaillard91a04802018-11-14 17:32:41 +0000415void IPCThreadState::clearPropagateWorkSource()
416{
417 mPropagateWorkSource = false;
418}
419
420bool IPCThreadState::shouldPropagateWorkSource() const
421{
422 return mPropagateWorkSource;
423}
424
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000425uid_t IPCThreadState::getCallingWorkSourceUid() const
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100426{
427 return mWorkSource;
428}
429
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000430int64_t IPCThreadState::clearCallingWorkSource()
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100431{
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +0000432 return setCallingWorkSourceUid(kUnsetWorkSource);
433}
434
435void IPCThreadState::restoreCallingWorkSource(int64_t token)
436{
437 uid_t uid = (int)token;
Olivier Gaillard91a04802018-11-14 17:32:41 +0000438 setCallingWorkSourceUidWithoutPropagation(uid);
439 mPropagateWorkSource = ((token >> kWorkSourcePropagatedBitIndex) & 1) == 1;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100440}
441
Brad Fitzpatrick52736032010-08-30 16:01:16 -0700442void IPCThreadState::setLastTransactionBinderFlags(int32_t flags)
443{
444 mLastTransactionBinderFlags = flags;
445}
446
447int32_t IPCThreadState::getLastTransactionBinderFlags() const
448{
449 return mLastTransactionBinderFlags;
450}
451
Steven Moreland9514b202020-09-21 18:03:27 +0000452void IPCThreadState::setCallRestriction(ProcessState::CallRestriction restriction) {
453 mCallRestriction = restriction;
454}
455
456ProcessState::CallRestriction IPCThreadState::getCallRestriction() const {
457 return mCallRestriction;
458}
459
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800460void IPCThreadState::restoreCallingIdentity(int64_t token)
461{
462 mCallingUid = (int)(token>>32);
Steven Morelandf0212002018-12-26 13:59:23 -0800463 mCallingSid = nullptr; // not enough data to restore
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800464 mCallingPid = (int)token;
465}
466
467void IPCThreadState::clearCaller()
468{
Marco Nelissend43b1942009-07-17 07:59:17 -0700469 mCallingPid = getpid();
Steven Morelandf0212002018-12-26 13:59:23 -0800470 mCallingSid = nullptr; // expensive to lookup
Marco Nelissend43b1942009-07-17 07:59:17 -0700471 mCallingUid = getuid();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800472}
473
474void IPCThreadState::flushCommands()
475{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -0200476 if (mProcess->mDriverFD < 0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800477 return;
478 talkWithDriver(false);
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700479 // The flush could have caused post-write refcount decrements to have
480 // been executed, which in turn could result in BC_RELEASE/BC_DECREFS
481 // being queued in mOut. So flush again, if we need to.
482 if (mOut.dataSize() > 0) {
483 talkWithDriver(false);
484 }
485 if (mOut.dataSize() > 0) {
486 ALOGW("mOut.dataSize() > 0 after flushCommands()");
487 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800488}
489
Martijn Coenen0442a862017-11-17 10:46:32 +0100490bool IPCThreadState::flushIfNeeded()
491{
492 if (mIsLooper || mServingStackPointer != nullptr) {
493 return false;
494 }
495 // In case this thread is not a looper and is not currently serving a binder transaction,
496 // there's no guarantee that this thread will call back into the kernel driver any time
497 // soon. Therefore, flush pending commands such as BC_FREE_BUFFER, to prevent them from getting
498 // stuck in this thread's out buffer.
499 flushCommands();
500 return true;
501}
502
Wale Ogunwale376b8222015-04-13 16:16:10 -0700503void IPCThreadState::blockUntilThreadAvailable()
504{
505 pthread_mutex_lock(&mProcess->mThreadCountLock);
Steven Morelandc648a762021-01-16 02:39:45 +0000506 mProcess->mWaitingForThreads++;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700507 while (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads) {
Wale Ogunwalea3206e62015-04-21 12:29:50 -0700508 ALOGW("Waiting for thread to be free. mExecutingThreadsCount=%lu mMaxThreads=%lu\n",
509 static_cast<unsigned long>(mProcess->mExecutingThreadsCount),
510 static_cast<unsigned long>(mProcess->mMaxThreads));
Wale Ogunwale376b8222015-04-13 16:16:10 -0700511 pthread_cond_wait(&mProcess->mThreadCountDecrement, &mProcess->mThreadCountLock);
512 }
Steven Morelandc648a762021-01-16 02:39:45 +0000513 mProcess->mWaitingForThreads--;
Wale Ogunwale376b8222015-04-13 16:16:10 -0700514 pthread_mutex_unlock(&mProcess->mThreadCountLock);
515}
516
Todd Poynor8d96cab2013-06-25 19:12:18 -0700517status_t IPCThreadState::getAndExecuteCommand()
518{
519 status_t result;
520 int32_t cmd;
521
522 result = talkWithDriver();
523 if (result >= NO_ERROR) {
524 size_t IN = mIn.dataAvail();
525 if (IN < sizeof(int32_t)) return result;
526 cmd = mIn.readInt32();
527 IF_LOG_COMMANDS() {
528 alog << "Processing top-level Command: "
529 << getReturnString(cmd) << endl;
530 }
531
Wale Ogunwale376b8222015-04-13 16:16:10 -0700532 pthread_mutex_lock(&mProcess->mThreadCountLock);
533 mProcess->mExecutingThreadsCount++;
Colin Cross96e83222016-04-15 14:29:55 -0700534 if (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads &&
535 mProcess->mStarvationStartTimeMs == 0) {
536 mProcess->mStarvationStartTimeMs = uptimeMillis();
537 }
Wale Ogunwale376b8222015-04-13 16:16:10 -0700538 pthread_mutex_unlock(&mProcess->mThreadCountLock);
539
Todd Poynor8d96cab2013-06-25 19:12:18 -0700540 result = executeCommand(cmd);
541
Wale Ogunwale376b8222015-04-13 16:16:10 -0700542 pthread_mutex_lock(&mProcess->mThreadCountLock);
543 mProcess->mExecutingThreadsCount--;
Colin Cross96e83222016-04-15 14:29:55 -0700544 if (mProcess->mExecutingThreadsCount < mProcess->mMaxThreads &&
545 mProcess->mStarvationStartTimeMs != 0) {
546 int64_t starvationTimeMs = uptimeMillis() - mProcess->mStarvationStartTimeMs;
547 if (starvationTimeMs > 100) {
548 ALOGE("binder thread pool (%zu threads) starved for %" PRId64 " ms",
549 mProcess->mMaxThreads, starvationTimeMs);
550 }
551 mProcess->mStarvationStartTimeMs = 0;
552 }
Steven Morelandc648a762021-01-16 02:39:45 +0000553
554 // Cond broadcast can be expensive, so don't send it every time a binder
555 // call is processed. b/168806193
556 if (mProcess->mWaitingForThreads > 0) {
557 pthread_cond_broadcast(&mProcess->mThreadCountDecrement);
558 }
Wale Ogunwale376b8222015-04-13 16:16:10 -0700559 pthread_mutex_unlock(&mProcess->mThreadCountLock);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700560 }
561
562 return result;
563}
564
565// When we've cleared the incoming command queue, process any pending derefs
566void IPCThreadState::processPendingDerefs()
567{
568 if (mIn.dataPosition() >= mIn.dataSize()) {
Martijn Coenen0791fbf2017-08-08 15:36:16 +0200569 /*
570 * The decWeak()/decStrong() calls may cause a destructor to run,
571 * which in turn could have initiated an outgoing transaction,
572 * which in turn could cause us to add to the pending refs
573 * vectors; so instead of simply iterating, loop until they're empty.
574 *
575 * We do this in an outer loop, because calling decStrong()
576 * may result in something being added to mPendingWeakDerefs,
577 * which could be delayed until the next incoming command
578 * from the driver if we don't process it now.
579 */
580 while (mPendingWeakDerefs.size() > 0 || mPendingStrongDerefs.size() > 0) {
581 while (mPendingWeakDerefs.size() > 0) {
582 RefBase::weakref_type* refs = mPendingWeakDerefs[0];
583 mPendingWeakDerefs.removeAt(0);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700584 refs->decWeak(mProcess.get());
585 }
Todd Poynor8d96cab2013-06-25 19:12:18 -0700586
Martijn Coenen0791fbf2017-08-08 15:36:16 +0200587 if (mPendingStrongDerefs.size() > 0) {
588 // We don't use while() here because we don't want to re-order
589 // strong and weak decs at all; if this decStrong() causes both a
590 // decWeak() and a decStrong() to be queued, we want to process
591 // the decWeak() first.
592 BBinder* obj = mPendingStrongDerefs[0];
593 mPendingStrongDerefs.removeAt(0);
Todd Poynor8d96cab2013-06-25 19:12:18 -0700594 obj->decStrong(mProcess.get());
595 }
Todd Poynor8d96cab2013-06-25 19:12:18 -0700596 }
597 }
598}
599
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700600void IPCThreadState::processPostWriteDerefs()
601{
602 for (size_t i = 0; i < mPostWriteWeakDerefs.size(); i++) {
603 RefBase::weakref_type* refs = mPostWriteWeakDerefs[i];
604 refs->decWeak(mProcess.get());
605 }
606 mPostWriteWeakDerefs.clear();
607
608 for (size_t i = 0; i < mPostWriteStrongDerefs.size(); i++) {
609 RefBase* obj = mPostWriteStrongDerefs[i];
610 obj->decStrong(mProcess.get());
611 }
612 mPostWriteStrongDerefs.clear();
613}
614
Jintao Zhu413a00e2021-01-16 17:42:00 +0800615void IPCThreadState::createTransactionReference(RefBase* ref)
616{
617 ref->incStrong(mProcess.get());
618 mPostWriteStrongDerefs.push(ref);
619}
620
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800621void IPCThreadState::joinThreadPool(bool isMain)
622{
623 LOG_THREADPOOL("**** THREAD %p (PID %d) IS JOINING THE THREAD POOL\n", (void*)pthread_self(), getpid());
624
625 mOut.writeInt32(isMain ? BC_ENTER_LOOPER : BC_REGISTER_LOOPER);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800626
Martijn Coenen0442a862017-11-17 10:46:32 +0100627 mIsLooper = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800628 status_t result;
629 do {
Todd Poynor8d96cab2013-06-25 19:12:18 -0700630 processPendingDerefs();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800631 // now get the next command to be processed, waiting if necessary
Todd Poynor8d96cab2013-06-25 19:12:18 -0700632 result = getAndExecuteCommand();
Jason Parksdcd39582009-11-03 12:14:38 -0800633
Todd Poynor8d96cab2013-06-25 19:12:18 -0700634 if (result < NO_ERROR && result != TIMED_OUT && result != -ECONNREFUSED && result != -EBADF) {
Steven Moreland6adf33c2019-09-25 13:18:09 -0700635 LOG_ALWAYS_FATAL("getAndExecuteCommand(fd=%d) returned unexpected error %d, aborting",
Jeff Tinkeref073862013-06-11 11:30:21 -0700636 mProcess->mDriverFD, result);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800637 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800638
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800639 // Let this thread exit the thread pool if it is no longer
640 // needed and it is not the main process thread.
641 if(result == TIMED_OUT && !isMain) {
642 break;
643 }
644 } while (result != -ECONNREFUSED && result != -EBADF);
645
Wei Wangc7341432016-10-19 10:23:59 -0700646 LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%d\n",
647 (void*)pthread_self(), getpid(), result);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800648
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800649 mOut.writeInt32(BC_EXIT_LOOPER);
Martijn Coenen0442a862017-11-17 10:46:32 +0100650 mIsLooper = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800651 talkWithDriver(false);
652}
653
Steven Morelandd8c85672020-07-24 21:30:41 +0000654status_t IPCThreadState::setupPolling(int* fd)
Todd Poynor8d96cab2013-06-25 19:12:18 -0700655{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -0200656 if (mProcess->mDriverFD < 0) {
Todd Poynor8d96cab2013-06-25 19:12:18 -0700657 return -EBADF;
658 }
659
660 mOut.writeInt32(BC_ENTER_LOOPER);
Steven Morelandf210b502021-01-15 23:40:32 +0000661 flushCommands();
Todd Poynor8d96cab2013-06-25 19:12:18 -0700662 *fd = mProcess->mDriverFD;
663 return 0;
664}
665
666status_t IPCThreadState::handlePolledCommands()
667{
668 status_t result;
669
670 do {
671 result = getAndExecuteCommand();
672 } while (mIn.dataPosition() < mIn.dataSize());
673
674 processPendingDerefs();
675 flushCommands();
676 return result;
677}
678
Colin Cross6f4f3ab2014-02-05 17:42:44 -0800679void IPCThreadState::stopProcess(bool /*immediate*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800680{
Steve Blocka19954a2012-01-04 20:05:49 +0000681 //ALOGI("**** STOPPING PROCESS");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800682 flushCommands();
683 int fd = mProcess->mDriverFD;
684 mProcess->mDriverFD = -1;
685 close(fd);
686 //kill(getpid(), SIGKILL);
687}
688
689status_t IPCThreadState::transact(int32_t handle,
690 uint32_t code, const Parcel& data,
691 Parcel* reply, uint32_t flags)
692{
Steven Moreland5553ac42020-11-11 02:14:45 +0000693 LOG_ALWAYS_FATAL_IF(data.isForRpc(), "Parcel constructed for RPC, but being used with binder.");
694
Ganesh Mahendran58e5daa2017-10-11 18:05:13 +0800695 status_t err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800696
697 flags |= TF_ACCEPT_FDS;
698
699 IF_LOG_TRANSACTIONS() {
700 TextOutput::Bundle _b(alog);
701 alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
702 << handle << " / code " << TypeCode(code) << ": "
703 << indent << data << dedent << endl;
704 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800705
Ganesh Mahendran58e5daa2017-10-11 18:05:13 +0800706 LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
707 (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
Yi Kongfdd8da92018-06-07 17:52:27 -0700708 err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, nullptr);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800709
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800710 if (err != NO_ERROR) {
711 if (reply) reply->setError(err);
712 return (mLastError = err);
713 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800714
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800715 if ((flags & TF_ONE_WAY) == 0) {
Steven Moreland7732a092019-01-02 17:54:16 -0800716 if (UNLIKELY(mCallRestriction != ProcessState::CallRestriction::NONE)) {
717 if (mCallRestriction == ProcessState::CallRestriction::ERROR_IF_NOT_ONEWAY) {
Steven Moreland8cb34fc2019-05-13 11:44:55 -0700718 ALOGE("Process making non-oneway call (code: %u) but is restricted.", code);
Steven Moreland7732a092019-01-02 17:54:16 -0800719 CallStack::logStack("non-oneway call", CallStack::getCurrent(10).get(),
720 ANDROID_LOG_ERROR);
721 } else /* FATAL_IF_NOT_ONEWAY */ {
Steven Morelandfcc77f12020-09-01 01:16:11 +0000722 LOG_ALWAYS_FATAL("Process may not make non-oneway calls (code: %u).", code);
Steven Moreland7732a092019-01-02 17:54:16 -0800723 }
724 }
725
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700726 #if 0
727 if (code == 4) { // relayout
Steve Blocka19954a2012-01-04 20:05:49 +0000728 ALOGI(">>>>>> CALLING transaction 4");
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700729 } else {
Steve Blocka19954a2012-01-04 20:05:49 +0000730 ALOGI(">>>>>> CALLING transaction %d", code);
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700731 }
732 #endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800733 if (reply) {
734 err = waitForResponse(reply);
735 } else {
736 Parcel fakeReply;
737 err = waitForResponse(&fakeReply);
738 }
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700739 #if 0
740 if (code == 4) { // relayout
Steve Blocka19954a2012-01-04 20:05:49 +0000741 ALOGI("<<<<<< RETURNING transaction 4");
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700742 } else {
Steve Blocka19954a2012-01-04 20:05:49 +0000743 ALOGI("<<<<<< RETURNING transaction %d", code);
Dianne Hackborn67f78c42010-09-24 11:16:23 -0700744 }
745 #endif
Tim Murrayd429f4a2017-03-07 09:31:09 -0800746
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800747 IF_LOG_TRANSACTIONS() {
748 TextOutput::Bundle _b(alog);
749 alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
750 << handle << ": ";
751 if (reply) alog << indent << *reply << dedent << endl;
752 else alog << "(none requested)" << endl;
753 }
754 } else {
Yi Kongfdd8da92018-06-07 17:52:27 -0700755 err = waitForResponse(nullptr, nullptr);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800756 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800758 return err;
759}
760
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700761void IPCThreadState::incStrongHandle(int32_t handle, BpBinder *proxy)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800762{
763 LOG_REMOTEREFS("IPCThreadState::incStrongHandle(%d)\n", handle);
764 mOut.writeInt32(BC_ACQUIRE);
765 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100766 if (!flushIfNeeded()) {
767 // Create a temp reference until the driver has handled this command.
768 proxy->incStrong(mProcess.get());
769 mPostWriteStrongDerefs.push(proxy);
770 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800771}
772
773void IPCThreadState::decStrongHandle(int32_t handle)
774{
775 LOG_REMOTEREFS("IPCThreadState::decStrongHandle(%d)\n", handle);
776 mOut.writeInt32(BC_RELEASE);
777 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100778 flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800779}
780
Martijn Coenen7c170bb2018-05-04 17:28:55 -0700781void IPCThreadState::incWeakHandle(int32_t handle, BpBinder *proxy)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800782{
783 LOG_REMOTEREFS("IPCThreadState::incWeakHandle(%d)\n", handle);
784 mOut.writeInt32(BC_INCREFS);
785 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100786 if (!flushIfNeeded()) {
787 // Create a temp reference until the driver has handled this command.
788 proxy->getWeakRefs()->incWeak(mProcess.get());
789 mPostWriteWeakDerefs.push(proxy->getWeakRefs());
790 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800791}
792
793void IPCThreadState::decWeakHandle(int32_t handle)
794{
795 LOG_REMOTEREFS("IPCThreadState::decWeakHandle(%d)\n", handle);
796 mOut.writeInt32(BC_DECREFS);
797 mOut.writeInt32(handle);
Martijn Coenen0442a862017-11-17 10:46:32 +0100798 flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800799}
800
801status_t IPCThreadState::attemptIncStrongHandle(int32_t handle)
802{
Arve HjønnevÄg11cfdcc2014-02-14 20:14:02 -0800803#if HAS_BC_ATTEMPT_ACQUIRE
Andy McFaddenaefc9cd2011-08-31 07:43:40 -0700804 LOG_REMOTEREFS("IPCThreadState::attemptIncStrongHandle(%d)\n", handle);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800805 mOut.writeInt32(BC_ATTEMPT_ACQUIRE);
806 mOut.writeInt32(0); // xxx was thread priority
807 mOut.writeInt32(handle);
808 status_t result = UNKNOWN_ERROR;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800809
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800810 waitForResponse(NULL, &result);
Tim Murrayd429f4a2017-03-07 09:31:09 -0800811
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800812#if LOG_REFCOUNTS
liangweikanga43ee152016-10-25 16:37:54 +0800813 ALOGV("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800814 handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
815#endif
Tim Murrayd429f4a2017-03-07 09:31:09 -0800816
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800817 return result;
Arve HjønnevÄg11cfdcc2014-02-14 20:14:02 -0800818#else
819 (void)handle;
820 ALOGE("%s(%d): Not supported\n", __func__, handle);
821 return INVALID_OPERATION;
822#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800823}
824
825void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
826{
827#if LOG_REFCOUNTS
liangweikanga43ee152016-10-25 16:37:54 +0800828 ALOGV("IPCThreadState::expungeHandle(%ld)\n", handle);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800829#endif
Manoj Gupta9cec85b2017-09-19 16:34:29 -0700830 self()->mProcess->expungeHandle(handle, binder); // NOLINT
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800831}
832
833status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
834{
835 mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
836 mOut.writeInt32((int32_t)handle);
Serban Constantinescuf683e012013-11-05 16:53:55 +0000837 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800838 return NO_ERROR;
839}
840
841status_t IPCThreadState::clearDeathNotification(int32_t handle, BpBinder* proxy)
842{
843 mOut.writeInt32(BC_CLEAR_DEATH_NOTIFICATION);
844 mOut.writeInt32((int32_t)handle);
Serban Constantinescuf683e012013-11-05 16:53:55 +0000845 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800846 return NO_ERROR;
847}
848
849IPCThreadState::IPCThreadState()
Shubang Ludf2e0172021-05-14 23:02:07 +0000850 : mProcess(ProcessState::self()),
851 mServingStackPointer(nullptr),
852 mWorkSource(kUnsetWorkSource),
853 mPropagateWorkSource(false),
854 mIsLooper(false),
855 mStrictModePolicy(0),
856 mLastTransactionBinderFlags(0),
857 mCallRestriction(mProcess->mCallRestriction)
858{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800859 pthread_setspecific(gTLS, this);
Dianne Hackborn8c6cedc2009-12-07 17:59:37 -0800860 clearCaller();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800861 mIn.setDataCapacity(256);
862 mOut.setDataCapacity(256);
863}
864
865IPCThreadState::~IPCThreadState()
866{
867}
868
Martijn Coenenea0090a2017-11-02 18:54:40 +0000869status_t IPCThreadState::sendReply(const Parcel& reply, uint32_t flags)
870{
871 status_t err;
872 status_t statusBuffer;
873 err = writeTransactionData(BC_REPLY, flags, -1, 0, reply, &statusBuffer);
874 if (err < NO_ERROR) return err;
875
Yi Kongfdd8da92018-06-07 17:52:27 -0700876 return waitForResponse(nullptr, nullptr);
Martijn Coenenea0090a2017-11-02 18:54:40 +0000877}
878
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800879status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
880{
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100881 uint32_t cmd;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800882 int32_t err;
883
884 while (1) {
885 if ((err=talkWithDriver()) < NO_ERROR) break;
886 err = mIn.errorCheck();
887 if (err < NO_ERROR) break;
888 if (mIn.dataAvail() == 0) continue;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800889
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +0100890 cmd = (uint32_t)mIn.readInt32();
Tim Murrayd429f4a2017-03-07 09:31:09 -0800891
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800892 IF_LOG_COMMANDS() {
893 alog << "Processing waitForResponse Command: "
894 << getReturnString(cmd) << endl;
895 }
896
897 switch (cmd) {
Hang Lub185ac02021-03-24 13:17:22 +0800898 case BR_ONEWAY_SPAM_SUSPECT:
899 ALOGE("Process seems to be sending too many oneway calls.");
900 CallStack::logStack("oneway spamming", CallStack::getCurrent().get(),
901 ANDROID_LOG_ERROR);
902 [[fallthrough]];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800903 case BR_TRANSACTION_COMPLETE:
904 if (!reply && !acquireResult) goto finish;
905 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800906
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800907 case BR_DEAD_REPLY:
908 err = DEAD_OBJECT;
909 goto finish;
910
911 case BR_FAILED_REPLY:
912 err = FAILED_TRANSACTION;
913 goto finish;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800914
Marco Ballesio7ee17572020-09-08 10:30:03 -0700915 case BR_FROZEN_REPLY:
916 err = FAILED_TRANSACTION;
917 goto finish;
918
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800919 case BR_ACQUIRE_RESULT:
920 {
Steve Block67263472012-01-09 18:35:44 +0000921 ALOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800922 const int32_t result = mIn.readInt32();
923 if (!acquireResult) continue;
924 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;
925 }
926 goto finish;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800927
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800928 case BR_REPLY:
929 {
930 binder_transaction_data tr;
931 err = mIn.read(&tr, sizeof(tr));
Steve Block67263472012-01-09 18:35:44 +0000932 ALOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800933 if (err != NO_ERROR) goto finish;
934
935 if (reply) {
936 if ((tr.flags & TF_STATUS_CODE) == 0) {
937 reply->ipcSetDataReference(
938 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
939 tr.data_size,
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800940 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
941 tr.offsets_size/sizeof(binder_size_t),
Steven Moreland161fe122020-11-12 23:16:47 +0000942 freeBuffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800943 } else {
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800944 err = *reinterpret_cast<const status_t*>(tr.data.ptr.buffer);
Yi Kongfdd8da92018-06-07 17:52:27 -0700945 freeBuffer(nullptr,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800946 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
947 tr.data_size,
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800948 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
Steven Moreland161fe122020-11-12 23:16:47 +0000949 tr.offsets_size/sizeof(binder_size_t));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800950 }
951 } else {
Yi Kongfdd8da92018-06-07 17:52:27 -0700952 freeBuffer(nullptr,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800953 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
954 tr.data_size,
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800955 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
Steven Moreland161fe122020-11-12 23:16:47 +0000956 tr.offsets_size/sizeof(binder_size_t));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800957 continue;
958 }
959 }
960 goto finish;
961
962 default:
963 err = executeCommand(cmd);
964 if (err != NO_ERROR) goto finish;
965 break;
966 }
967 }
968
969finish:
970 if (err != NO_ERROR) {
971 if (acquireResult) *acquireResult = err;
972 if (reply) reply->setError(err);
973 mLastError = err;
974 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800975
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800976 return err;
977}
978
979status_t IPCThreadState::talkWithDriver(bool doReceive)
980{
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -0200981 if (mProcess->mDriverFD < 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +0100982 return -EBADF;
983 }
Tim Murrayd429f4a2017-03-07 09:31:09 -0800984
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800985 binder_write_read bwr;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800986
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800987 // Is the read buffer empty?
988 const bool needRead = mIn.dataPosition() >= mIn.dataSize();
Tim Murrayd429f4a2017-03-07 09:31:09 -0800989
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800990 // We don't want to write anything if we are still reading
991 // from data left in the input buffer and the caller
992 // has requested to read the next data.
993 const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
Tim Murrayd429f4a2017-03-07 09:31:09 -0800994
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800995 bwr.write_size = outAvail;
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -0800996 bwr.write_buffer = (uintptr_t)mOut.data();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800997
998 // This is what we'll read.
999 if (doReceive && needRead) {
1000 bwr.read_size = mIn.dataCapacity();
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001001 bwr.read_buffer = (uintptr_t)mIn.data();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001002 } else {
1003 bwr.read_size = 0;
Ben Chengd640f892011-12-01 17:11:32 -08001004 bwr.read_buffer = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001005 }
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001006
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001007 IF_LOG_COMMANDS() {
1008 TextOutput::Bundle _b(alog);
1009 if (outAvail != 0) {
1010 alog << "Sending commands to driver: " << indent;
1011 const void* cmds = (const void*)bwr.write_buffer;
1012 const void* end = ((const uint8_t*)cmds)+bwr.write_size;
1013 alog << HexDump(cmds, bwr.write_size) << endl;
1014 while (cmds < end) cmds = printCommand(alog, cmds);
1015 alog << dedent;
1016 }
1017 alog << "Size of receive buffer: " << bwr.read_size
1018 << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;
1019 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001020
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001021 // Return immediately if there is nothing to do.
1022 if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001023
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001024 bwr.write_consumed = 0;
1025 bwr.read_consumed = 0;
1026 status_t err;
1027 do {
1028 IF_LOG_COMMANDS() {
1029 alog << "About to read/write, write size = " << mOut.dataSize() << endl;
1030 }
Elliott Hughes6071da72015-08-12 15:27:47 -07001031#if defined(__ANDROID__)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001032 if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
1033 err = NO_ERROR;
1034 else
1035 err = -errno;
1036#else
1037 err = INVALID_OPERATION;
1038#endif
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -02001039 if (mProcess->mDriverFD < 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +01001040 err = -EBADF;
1041 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001042 IF_LOG_COMMANDS() {
1043 alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
1044 }
1045 } while (err == -EINTR);
Andy McFaddenaefc9cd2011-08-31 07:43:40 -07001046
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001047 IF_LOG_COMMANDS() {
Colin Cross6f4f3ab2014-02-05 17:42:44 -08001048 alog << "Our err: " << (void*)(intptr_t)err << ", write consumed: "
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001049 << bwr.write_consumed << " (of " << mOut.dataSize()
Todd Poynor8d96cab2013-06-25 19:12:18 -07001050 << "), read consumed: " << bwr.read_consumed << endl;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001051 }
1052
1053 if (err >= NO_ERROR) {
1054 if (bwr.write_consumed > 0) {
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001055 if (bwr.write_consumed < mOut.dataSize())
Steven Morelandb077deb2020-04-16 16:22:52 -07001056 LOG_ALWAYS_FATAL("Driver did not consume write buffer. "
1057 "err: %s consumed: %zu of %zu",
1058 statusToString(err).c_str(),
1059 (size_t)bwr.write_consumed,
1060 mOut.dataSize());
Martijn Coenen7c170bb2018-05-04 17:28:55 -07001061 else {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001062 mOut.setDataSize(0);
Martijn Coenen7c170bb2018-05-04 17:28:55 -07001063 processPostWriteDerefs();
1064 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001065 }
1066 if (bwr.read_consumed > 0) {
1067 mIn.setDataSize(bwr.read_consumed);
1068 mIn.setDataPosition(0);
1069 }
1070 IF_LOG_COMMANDS() {
1071 TextOutput::Bundle _b(alog);
1072 alog << "Remaining data size: " << mOut.dataSize() << endl;
1073 alog << "Received commands from driver: " << indent;
1074 const void* cmds = mIn.data();
1075 const void* end = mIn.data() + mIn.dataSize();
1076 alog << HexDump(cmds, mIn.dataSize()) << endl;
1077 while (cmds < end) cmds = printReturnCommand(alog, cmds);
1078 alog << dedent;
1079 }
1080 return NO_ERROR;
1081 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001082
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001083 return err;
1084}
1085
1086status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
1087 int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)
1088{
1089 binder_transaction_data tr;
1090
Arve HjønnevÄg07fd0f12014-02-18 21:10:29 -08001091 tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001092 tr.target.handle = handle;
1093 tr.code = code;
1094 tr.flags = binderFlags;
Evgeniy Stepanovd5474322011-04-21 14:15:00 +04001095 tr.cookie = 0;
1096 tr.sender_pid = 0;
1097 tr.sender_euid = 0;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001098
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001099 const status_t err = data.errorCheck();
1100 if (err == NO_ERROR) {
1101 tr.data_size = data.ipcDataSize();
1102 tr.data.ptr.buffer = data.ipcData();
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001103 tr.offsets_size = data.ipcObjectsCount()*sizeof(binder_size_t);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001104 tr.data.ptr.offsets = data.ipcObjects();
1105 } else if (statusBuffer) {
1106 tr.flags |= TF_STATUS_CODE;
1107 *statusBuffer = err;
1108 tr.data_size = sizeof(status_t);
Arve HjønnevÄg87b30d02014-02-18 21:04:31 -08001109 tr.data.ptr.buffer = reinterpret_cast<uintptr_t>(statusBuffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001110 tr.offsets_size = 0;
Arve HjønnevÄg84e625a2014-01-28 20:12:59 -08001111 tr.data.ptr.offsets = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001112 } else {
1113 return (mLastError = err);
1114 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001115
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001116 mOut.writeInt32(cmd);
1117 mOut.write(&tr, sizeof(tr));
Tim Murrayd429f4a2017-03-07 09:31:09 -08001118
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001119 return NO_ERROR;
1120}
1121
1122sp<BBinder> the_context_object;
1123
Jiyong Park384328e2020-11-13 17:16:48 +09001124void IPCThreadState::setTheContextObject(const sp<BBinder>& obj)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001125{
1126 the_context_object = obj;
1127}
1128
1129status_t IPCThreadState::executeCommand(int32_t cmd)
1130{
1131 BBinder* obj;
1132 RefBase::weakref_type* refs;
1133 status_t result = NO_ERROR;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001134
Bernhard RosenkrƤnzer74debb02014-11-25 21:55:33 +01001135 switch ((uint32_t)cmd) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001136 case BR_ERROR:
1137 result = mIn.readInt32();
1138 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001139
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001140 case BR_OK:
1141 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001142
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001143 case BR_ACQUIRE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001144 refs = (RefBase::weakref_type*)mIn.readPointer();
1145 obj = (BBinder*)mIn.readPointer();
Steve Block67263472012-01-09 18:35:44 +00001146 ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001147 "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
1148 refs, obj, refs->refBase());
1149 obj->incStrong(mProcess.get());
1150 IF_LOG_REMOTEREFS() {
1151 LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
1152 obj->printRefs();
1153 }
1154 mOut.writeInt32(BC_ACQUIRE_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001155 mOut.writePointer((uintptr_t)refs);
1156 mOut.writePointer((uintptr_t)obj);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001157 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001158
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001159 case BR_RELEASE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001160 refs = (RefBase::weakref_type*)mIn.readPointer();
1161 obj = (BBinder*)mIn.readPointer();
Steve Block67263472012-01-09 18:35:44 +00001162 ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001163 "BR_RELEASE: object %p does not match cookie %p (expected %p)",
1164 refs, obj, refs->refBase());
1165 IF_LOG_REMOTEREFS() {
1166 LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
1167 obj->printRefs();
1168 }
1169 mPendingStrongDerefs.push(obj);
1170 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001171
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001172 case BR_INCREFS:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001173 refs = (RefBase::weakref_type*)mIn.readPointer();
1174 obj = (BBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001175 refs->incWeak(mProcess.get());
1176 mOut.writeInt32(BC_INCREFS_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001177 mOut.writePointer((uintptr_t)refs);
1178 mOut.writePointer((uintptr_t)obj);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001179 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001180
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001181 case BR_DECREFS:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001182 refs = (RefBase::weakref_type*)mIn.readPointer();
1183 obj = (BBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001184 // NOTE: This assertion is not valid, because the object may no
1185 // longer exist (thus the (BBinder*)cast above resulting in a different
1186 // memory address).
Steve Block67263472012-01-09 18:35:44 +00001187 //ALOG_ASSERT(refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001188 // "BR_DECREFS: object %p does not match cookie %p (expected %p)",
1189 // refs, obj, refs->refBase());
1190 mPendingWeakDerefs.push(refs);
1191 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001192
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001193 case BR_ATTEMPT_ACQUIRE:
Serban Constantinescuf683e012013-11-05 16:53:55 +00001194 refs = (RefBase::weakref_type*)mIn.readPointer();
1195 obj = (BBinder*)mIn.readPointer();
Tim Murrayd429f4a2017-03-07 09:31:09 -08001196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001197 {
1198 const bool success = refs->attemptIncStrong(mProcess.get());
Steve Block67263472012-01-09 18:35:44 +00001199 ALOG_ASSERT(success && refs->refBase() == obj,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001200 "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
1201 refs, obj, refs->refBase());
Tim Murrayd429f4a2017-03-07 09:31:09 -08001202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001203 mOut.writeInt32(BC_ACQUIRE_RESULT);
1204 mOut.writeInt32((int32_t)success);
1205 }
1206 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001207
Steven Morelandf0212002018-12-26 13:59:23 -08001208 case BR_TRANSACTION_SEC_CTX:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001209 case BR_TRANSACTION:
1210 {
Steven Morelandf0212002018-12-26 13:59:23 -08001211 binder_transaction_data_secctx tr_secctx;
1212 binder_transaction_data& tr = tr_secctx.transaction_data;
1213
1214 if (cmd == (int) BR_TRANSACTION_SEC_CTX) {
1215 result = mIn.read(&tr_secctx, sizeof(tr_secctx));
1216 } else {
1217 result = mIn.read(&tr, sizeof(tr));
1218 tr_secctx.secctx = 0;
1219 }
1220
Steve Block67263472012-01-09 18:35:44 +00001221 ALOG_ASSERT(result == NO_ERROR,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001222 "Not enough command data for brTRANSACTION");
1223 if (result != NO_ERROR) break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001224
Martijn Coenenea0090a2017-11-02 18:54:40 +00001225 Parcel buffer;
1226 buffer.ipcSetDataReference(
1227 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
1228 tr.data_size,
1229 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
Steven Moreland161fe122020-11-12 23:16:47 +00001230 tr.offsets_size/sizeof(binder_size_t), freeBuffer);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001231
Steven Moreland39d887d2020-01-31 14:56:45 -08001232 const void* origServingStackPointer = mServingStackPointer;
1233 mServingStackPointer = &origServingStackPointer; // anything on the stack
1234
Martijn Coenenea0090a2017-11-02 18:54:40 +00001235 const pid_t origPid = mCallingPid;
Steven Morelandf0212002018-12-26 13:59:23 -08001236 const char* origSid = mCallingSid;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001237 const uid_t origUid = mCallingUid;
1238 const int32_t origStrictModePolicy = mStrictModePolicy;
1239 const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001240 const int32_t origWorkSource = mWorkSource;
1241 const bool origPropagateWorkSet = mPropagateWorkSource;
1242 // Calling work source will be set by Parcel#enforceInterface. Parcel#enforceInterface
1243 // is only guaranteed to be called for AIDL-generated stubs so we reset the work source
1244 // here to never propagate it.
1245 clearCallingWorkSource();
1246 clearPropagateWorkSource();
Martijn Coenenea0090a2017-11-02 18:54:40 +00001247
1248 mCallingPid = tr.sender_pid;
Steven Morelandf0212002018-12-26 13:59:23 -08001249 mCallingSid = reinterpret_cast<const char*>(tr_secctx.secctx);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001250 mCallingUid = tr.sender_euid;
1251 mLastTransactionBinderFlags = tr.flags;
1252
Steven Morelandf0212002018-12-26 13:59:23 -08001253 // ALOGI(">>>> TRANSACT from pid %d sid %s uid %d\n", mCallingPid,
1254 // (mCallingSid ? mCallingSid : "<N/A>"), mCallingUid);
Martijn Coenenea0090a2017-11-02 18:54:40 +00001255
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001256 Parcel reply;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001257 status_t error;
1258 IF_LOG_TRANSACTIONS() {
1259 TextOutput::Bundle _b(alog);
1260 alog << "BR_TRANSACTION thr " << (void*)pthread_self()
1261 << " / obj " << tr.target.ptr << " / code "
1262 << TypeCode(tr.code) << ": " << indent << buffer
1263 << dedent << endl
1264 << "Data addr = "
1265 << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
1266 << ", offsets addr="
1267 << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
1268 }
1269 if (tr.target.ptr) {
1270 // We only have a weak reference on the target object, so we must first try to
1271 // safely acquire a strong reference before doing anything else with it.
1272 if (reinterpret_cast<RefBase::weakref_type*>(
1273 tr.target.ptr)->attemptIncStrong(this)) {
1274 error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,
1275 &reply, tr.flags);
1276 reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);
Dianne Hackbornc1114612016-03-21 10:36:54 -07001277 } else {
Martijn Coenenea0090a2017-11-02 18:54:40 +00001278 error = UNKNOWN_TRANSACTION;
Dianne Hackbornc1114612016-03-21 10:36:54 -07001279 }
Brad Fitzpatrick52736032010-08-30 16:01:16 -07001280
Martijn Coenenea0090a2017-11-02 18:54:40 +00001281 } else {
1282 error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001283 }
Dianne Hackborn5ee2c9d2014-09-30 11:30:03 -07001284
Steven Morelandf0212002018-12-26 13:59:23 -08001285 //ALOGI("<<<< TRANSACT from pid %d restore pid %d sid %s uid %d\n",
1286 // mCallingPid, origPid, (origSid ? origSid : "<N/A>"), origUid);
Tim Murrayd429f4a2017-03-07 09:31:09 -08001287
Martijn Coenenea0090a2017-11-02 18:54:40 +00001288 if ((tr.flags & TF_ONE_WAY) == 0) {
1289 LOG_ONEWAY("Sending reply to %d!", mCallingPid);
1290 if (error < NO_ERROR) reply.setError(error);
Steven Morelandf183fdd2020-10-27 00:12:12 +00001291
1292 constexpr uint32_t kForwardReplyFlags = TF_CLEAR_BUF;
1293 sendReply(reply, (tr.flags & kForwardReplyFlags));
Martijn Coenenea0090a2017-11-02 18:54:40 +00001294 } else {
Steven Moreland80844f72020-12-12 02:06:08 +00001295 if (error != OK) {
1296 alog << "oneway function results for code " << tr.code
1297 << " on binder at "
1298 << reinterpret_cast<void*>(tr.target.ptr)
1299 << " will be dropped but finished with status "
1300 << statusToString(error);
1301
1302 // ideally we could log this even when error == OK, but it
1303 // causes too much logspam because some manually-written
1304 // interfaces have clients that call methods which always
1305 // write results, sometimes as oneway methods.
1306 if (reply.dataSize() != 0) {
1307 alog << " and reply parcel size " << reply.dataSize();
1308 }
1309
1310 alog << endl;
Steven Morelandce66b8a2020-02-10 14:43:14 -08001311 }
Martijn Coenenea0090a2017-11-02 18:54:40 +00001312 LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
1313 }
1314
Steven Moreland39d887d2020-01-31 14:56:45 -08001315 mServingStackPointer = origServingStackPointer;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001316 mCallingPid = origPid;
Steven Morelandf0212002018-12-26 13:59:23 -08001317 mCallingSid = origSid;
Martijn Coenenea0090a2017-11-02 18:54:40 +00001318 mCallingUid = origUid;
1319 mStrictModePolicy = origStrictModePolicy;
1320 mLastTransactionBinderFlags = origTransactionBinderFlags;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001321 mWorkSource = origWorkSource;
1322 mPropagateWorkSource = origPropagateWorkSet;
Christopher Tate440fd872010-03-18 17:55:03 -07001323
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001324 IF_LOG_TRANSACTIONS() {
1325 TextOutput::Bundle _b(alog);
1326 alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
1327 << tr.target.ptr << ": " << indent << reply << dedent << endl;
1328 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001329
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001330 }
1331 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001332
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001333 case BR_DEAD_BINDER:
1334 {
Serban Constantinescuf683e012013-11-05 16:53:55 +00001335 BpBinder *proxy = (BpBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001336 proxy->sendObituary();
1337 mOut.writeInt32(BC_DEAD_BINDER_DONE);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001338 mOut.writePointer((uintptr_t)proxy);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001339 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001340
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001341 case BR_CLEAR_DEATH_NOTIFICATION_DONE:
1342 {
Serban Constantinescuf683e012013-11-05 16:53:55 +00001343 BpBinder *proxy = (BpBinder*)mIn.readPointer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001344 proxy->getWeakRefs()->decWeak(proxy);
1345 } break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001346
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001347 case BR_FINISHED:
1348 result = TIMED_OUT;
1349 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001351 case BR_NOOP:
1352 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001354 case BR_SPAWN_LOOPER:
1355 mProcess->spawnPooledThread(false);
1356 break;
Tim Murrayd429f4a2017-03-07 09:31:09 -08001357
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001358 default:
liangweikanga43ee152016-10-25 16:37:54 +08001359 ALOGE("*** BAD COMMAND %d received from Binder driver\n", cmd);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001360 result = UNKNOWN_ERROR;
1361 break;
1362 }
1363
1364 if (result != NO_ERROR) {
1365 mLastError = result;
1366 }
Tim Murrayd429f4a2017-03-07 09:31:09 -08001367
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001368 return result;
1369}
1370
Steven Moreland39d887d2020-01-31 14:56:45 -08001371const void* IPCThreadState::getServingStackPointer() const {
1372 return mServingStackPointer;
Jayant Chowdharydac6dc82018-10-01 22:52:44 +00001373}
1374
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001375void IPCThreadState::threadDestructor(void *st)
1376{
Todd Poynor8d96cab2013-06-25 19:12:18 -07001377 IPCThreadState* const self = static_cast<IPCThreadState*>(st);
1378 if (self) {
1379 self->flushCommands();
Elliott Hughes6071da72015-08-12 15:27:47 -07001380#if defined(__ANDROID__)
Alexandre Baiãoc60c4fc2019-07-31 12:29:31 -02001381 if (self->mProcess->mDriverFD >= 0) {
Johannes Carlssondb1597a2011-02-17 14:06:53 +01001382 ioctl(self->mProcess->mDriverFD, BINDER_THREAD_EXIT, 0);
1383 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001384#endif
Todd Poynor8d96cab2013-06-25 19:12:18 -07001385 delete self;
1386 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001387}
1388
Marco Ballesiob09fc4a2020-09-11 16:17:21 -07001389status_t IPCThreadState::getProcessFreezeInfo(pid_t pid, bool *sync_received, bool *async_received)
1390{
1391 int ret = 0;
1392 binder_frozen_status_info info;
1393 info.pid = pid;
1394
1395#if defined(__ANDROID__)
1396 if (ioctl(self()->mProcess->mDriverFD, BINDER_GET_FROZEN_INFO, &info) < 0)
1397 ret = -errno;
1398#endif
1399 *sync_received = info.sync_recv;
1400 *async_received = info.async_recv;
1401
1402 return ret;
1403}
1404
Marco Ballesio7ee17572020-09-08 10:30:03 -07001405status_t IPCThreadState::freeze(pid_t pid, bool enable, uint32_t timeout_ms) {
1406 struct binder_freeze_info info;
1407 int ret = 0;
1408
1409 info.pid = pid;
1410 info.enable = enable;
1411 info.timeout_ms = timeout_ms;
1412
1413
1414#if defined(__ANDROID__)
1415 if (ioctl(self()->mProcess->mDriverFD, BINDER_FREEZE, &info) < 0)
1416 ret = -errno;
1417#endif
1418
1419 //
1420 // ret==-EAGAIN indicates that transactions have not drained.
1421 // Call again to poll for completion.
1422 //
1423 return ret;
1424}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001425
Colin Cross6f4f3ab2014-02-05 17:42:44 -08001426void IPCThreadState::freeBuffer(Parcel* parcel, const uint8_t* data,
1427 size_t /*dataSize*/,
1428 const binder_size_t* /*objects*/,
Steven Moreland161fe122020-11-12 23:16:47 +00001429 size_t /*objectsSize*/)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001430{
Steve Blocka19954a2012-01-04 20:05:49 +00001431 //ALOGI("Freeing parcel %p", &parcel);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001432 IF_LOG_COMMANDS() {
1433 alog << "Writing BC_FREE_BUFFER for " << data << endl;
1434 }
Steve Block67263472012-01-09 18:35:44 +00001435 ALOG_ASSERT(data != NULL, "Called with NULL data");
Yi Kongfdd8da92018-06-07 17:52:27 -07001436 if (parcel != nullptr) parcel->closeFileDescriptors();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001437 IPCThreadState* state = self();
1438 state->mOut.writeInt32(BC_FREE_BUFFER);
Serban Constantinescuf683e012013-11-05 16:53:55 +00001439 state->mOut.writePointer((uintptr_t)data);
Martijn Coenen0442a862017-11-17 10:46:32 +01001440 state->flushIfNeeded();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001441}
1442
Steven Moreland61ff8492019-09-26 16:05:45 -07001443} // namespace android