blob: 11a083ac1182786405851b6c3cc4772b4b60b037 [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 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
17#define LOG_TAG "RpcState"
18
19#include "RpcState.h"
20
Steven Moreland62129012021-07-29 12:14:44 -070021#include <android-base/hex.h>
Steven Morelandd7302072021-05-15 01:32:04 +000022#include <android-base/scopeguard.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000023#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000024#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000025#include <binder/RpcServer.h>
26
27#include "Debug.h"
28#include "RpcWireFormat.h"
29
Steven Morelandb8176792021-06-22 20:29:21 +000030#include <random>
31
Steven Moreland5553ac42020-11-11 02:14:45 +000032#include <inttypes.h>
33
34namespace android {
35
Steven Morelandd7302072021-05-15 01:32:04 +000036using base::ScopeGuard;
37
Devin Moore08256432021-07-02 13:03:49 -070038#if RPC_FLAKE_PRONE
Steven Morelandb8176792021-06-22 20:29:21 +000039void rpcMaybeWaitToFlake() {
Devin Moore08256432021-07-02 13:03:49 -070040 [[clang::no_destroy]] static std::random_device r;
41 [[clang::no_destroy]] static std::mutex m;
Steven Morelandb8176792021-06-22 20:29:21 +000042 unsigned num;
43 {
44 std::lock_guard<std::mutex> lock(m);
45 num = r();
46 }
47 if (num % 10 == 0) usleep(num % 1000);
48}
49#endif
50
Steven Moreland5553ac42020-11-11 02:14:45 +000051RpcState::RpcState() {}
52RpcState::~RpcState() {}
53
Steven Morelandbdb53ab2021-05-05 17:57:41 +000054status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5623d1a2021-09-10 15:45:34 -070055 uint64_t* outAddress) {
Steven Moreland5553ac42020-11-11 02:14:45 +000056 bool isRemote = binder->remoteBinder();
57 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
58
Steven Moreland99157622021-09-13 16:27:34 -070059 if (isRpc && binder->remoteBinder()->getPrivateAccessor().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000060 // We need to be able to send instructions over the socket for how to
61 // connect to a different server, and we also need to let the host
62 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000063 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000064 return INVALID_OPERATION;
65 }
66
67 if (isRemote && !isRpc) {
68 // Without additional work, this would have the effect of using this
69 // process to proxy calls from the socket over to the other process, and
70 // it would make those calls look like they come from us (not over the
71 // sockets). In order to make this work transparently like binder, we
72 // would instead need to send instructions over the socket for how to
73 // connect to the host process, and we also need to let the host process
74 // know this was happening.
75 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
76 return INVALID_OPERATION;
77 }
78
79 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000080 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +000081
82 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
83 // in RpcState
84 for (auto& [addr, node] : mNodeForAddress) {
85 if (binder == node.binder) {
86 if (isRpc) {
Steven Moreland5623d1a2021-09-10 15:45:34 -070087 // check integrity of data structure
Steven Moreland99157622021-09-13 16:27:34 -070088 uint64_t actualAddr = binder->remoteBinder()->getPrivateAccessor().rpcAddress();
Steven Moreland5623d1a2021-09-10 15:45:34 -070089 LOG_ALWAYS_FATAL_IF(addr != actualAddr, "Address mismatch %" PRIu64 " vs %" PRIu64,
90 addr, actualAddr);
Steven Moreland5553ac42020-11-11 02:14:45 +000091 }
92 node.timesSent++;
93 node.sentRef = binder; // might already be set
94 *outAddress = addr;
95 return OK;
96 }
97 }
98 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
99
Steven Moreland91538242021-06-10 23:35:35 +0000100 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +0000101
Steven Moreland5623d1a2021-09-10 15:45:34 -0700102 // arbitrary limit for maximum number of nodes in a process (otherwise we
103 // might run out of addresses)
104 if (mNodeForAddress.size() > 100000) {
105 return NO_MEMORY;
106 }
107
108 while (true) {
109 RpcWireAddress address{
110 .options = RPC_WIRE_ADDRESS_OPTION_CREATED,
111 .address = mNextId,
112 };
113 if (forServer) {
114 address.options |= RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
115 }
116
117 // avoid ubsan abort
118 if (mNextId >= std::numeric_limits<uint32_t>::max()) {
119 mNextId = 0;
120 } else {
121 mNextId++;
122 }
123
124 auto&& [it, inserted] = mNodeForAddress.insert({RpcWireAddress::toRaw(address),
Steven Moreland91538242021-06-10 23:35:35 +0000125 BinderNode{
126 .binder = binder,
127 .timesSent = 1,
128 .sentRef = binder,
129 }});
130 if (inserted) {
131 *outAddress = it->first;
132 return OK;
133 }
Steven Moreland91538242021-06-10 23:35:35 +0000134 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000135}
136
Steven Moreland5623d1a2021-09-10 15:45:34 -0700137status_t RpcState::onBinderEntering(const sp<RpcSession>& session, uint64_t address,
Steven Moreland7227c8a2021-06-02 00:24:32 +0000138 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000139 // ensure that: if we want to use addresses for something else in the future (for
140 // instance, allowing transitive binder sends), that we don't accidentally
141 // send those addresses to old server. Accidentally ignoring this in that
142 // case and considering the binder to be recognized could cause this
143 // process to accidentally proxy transactions for that binder. Of course,
144 // if we communicate with a binder, it could always be proxying
145 // information. However, we want to make sure that isn't done on accident
146 // by a client.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700147 RpcWireAddress addr = RpcWireAddress::fromRaw(address);
148 constexpr uint32_t kKnownOptions =
149 RPC_WIRE_ADDRESS_OPTION_CREATED | RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
150 if (addr.options & ~kKnownOptions) {
151 ALOGE("Address is of an unknown type, rejecting: %" PRIu64, address);
Steven Moreland91538242021-06-10 23:35:35 +0000152 return BAD_VALUE;
153 }
154
Steven Moreland5553ac42020-11-11 02:14:45 +0000155 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000156 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000157
158 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000159 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000160
161 // implicitly have strong RPC refcount, since we received this binder
162 it->second.timesRecd++;
163
164 _l.unlock();
165
166 // We have timesRecd RPC refcounts, but we only need to hold on to one
167 // when we keep the object. All additional dec strongs are sent
168 // immediately, we wait to send the last one in BpBinder::onLastDecStrong.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000169 (void)session->sendDecStrong(address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000170
Steven Moreland7227c8a2021-06-02 00:24:32 +0000171 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000172 }
173
Steven Moreland91538242021-06-10 23:35:35 +0000174 // we don't know about this binder, so the other side of the connection
175 // should have created it.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700176 if ((addr.options & RPC_WIRE_ADDRESS_OPTION_FOR_SERVER) == !!session->server()) {
177 ALOGE("Server received unrecognized address which we should own the creation of %" PRIu64,
178 address);
Steven Moreland91538242021-06-10 23:35:35 +0000179 return BAD_VALUE;
180 }
181
Steven Moreland5553ac42020-11-11 02:14:45 +0000182 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
183 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
184
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000185 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000186 // device global binders in the RPC world).
Steven Moreland99157622021-09-13 16:27:34 -0700187 it->second.binder = *out = BpBinder::PrivateAccessor::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000188 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000189 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000190}
191
192size_t RpcState::countBinders() {
193 std::lock_guard<std::mutex> _l(mNodeMutex);
194 return mNodeForAddress.size();
195}
196
197void RpcState::dump() {
198 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000199 dumpLocked();
200}
201
Steven Morelandc9d7b532021-06-04 20:57:41 +0000202void RpcState::clear() {
Steven Moreland583a14a2021-06-04 02:04:58 +0000203 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000204
205 if (mTerminated) {
206 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
207 "New state should be impossible after terminating!");
208 return;
209 }
210
211 if (SHOULD_LOG_RPC_DETAIL) {
212 ALOGE("RpcState::clear()");
213 dumpLocked();
214 }
215
216 // if the destructor of a binder object makes another RPC call, then calling
217 // decStrong could deadlock. So, we must hold onto these binders until
218 // mNodeMutex is no longer taken.
219 std::vector<sp<IBinder>> tempHoldBinder;
220
221 mTerminated = true;
222 for (auto& [address, node] : mNodeForAddress) {
223 sp<IBinder> binder = node.binder.promote();
224 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
225
226 if (node.sentRef != nullptr) {
227 tempHoldBinder.push_back(node.sentRef);
228 }
229 }
230
231 mNodeForAddress.clear();
232
233 _l.unlock();
234 tempHoldBinder.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000235}
236
237void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000238 ALOGE("DUMP OF RpcState %p", this);
239 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
240 for (const auto& [address, node] : mNodeForAddress) {
241 sp<IBinder> binder = node.binder.promote();
242
243 const char* desc;
244 if (binder) {
245 if (binder->remoteBinder()) {
246 if (binder->remoteBinder()->isRpcBinder()) {
247 desc = "(rpc binder proxy)";
248 } else {
249 desc = "(binder proxy)";
250 }
251 } else {
252 desc = "(local binder)";
253 }
254 } else {
255 desc = "(null)";
256 }
257
Steven Moreland5623d1a2021-09-10 15:45:34 -0700258 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a: %" PRIu64 " type: %s",
259 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address, desc);
Steven Moreland5553ac42020-11-11 02:14:45 +0000260 }
261 ALOGE("END DUMP OF RpcState");
262}
263
Steven Moreland5553ac42020-11-11 02:14:45 +0000264
Steven Morelanddbe71832021-05-12 23:31:00 +0000265RpcState::CommandData::CommandData(size_t size) : mSize(size) {
266 // The maximum size for regular binder is 1MB for all concurrent
267 // transactions. A very small proportion of transactions are even
268 // larger than a page, but we need to avoid allocating too much
269 // data on behalf of an arbitrary client, or we could risk being in
270 // a position where a single additional allocation could run out of
271 // memory.
272 //
273 // Note, this limit may not reflect the total amount of data allocated for a
274 // transaction (in some cases, additional fixed size amounts are added),
275 // though for rough consistency, we should avoid cases where this data type
276 // is used for multiple dynamic allocations for a single transaction.
277 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
278 if (size == 0) return;
279 if (size > kMaxTransactionAllocation) {
280 ALOGW("Transaction requested too much data allocation %zu", size);
281 return;
282 }
283 mData.reset(new (std::nothrow) uint8_t[size]);
284}
285
Steven Moreland5ae62562021-06-10 03:21:42 +0000286status_t RpcState::rpcSend(const sp<RpcSession::RpcConnection>& connection,
287 const sp<RpcSession>& session, const char* what, const void* data,
288 size_t size) {
Yifan Hong702115c2021-06-24 15:39:18 -0700289 LOG_RPC_DETAIL("Sending %s on RpcTransport %p: %s", what, connection->rpcTransport.get(),
Steven Moreland62129012021-07-29 12:14:44 -0700290 android::base::HexString(data, size).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000291
292 if (size > std::numeric_limits<ssize_t>::max()) {
293 ALOGE("Cannot send %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000294 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000295 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000296 }
297
Yifan Hong702115c2021-06-24 15:39:18 -0700298 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700299 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
300 data, size);
Steven Moreland798e0d12021-07-14 23:19:25 +0000301 status != OK) {
Yifan Hong702115c2021-06-24 15:39:18 -0700302 LOG_RPC_DETAIL("Failed to write %s (%zu bytes) on RpcTransport %p, error: %s", what, size,
303 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000304 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000305 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000306 }
307
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000308 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000309}
310
Steven Moreland5ae62562021-06-10 03:21:42 +0000311status_t RpcState::rpcRec(const sp<RpcSession::RpcConnection>& connection,
312 const sp<RpcSession>& session, const char* what, void* data,
313 size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000314 if (size > std::numeric_limits<ssize_t>::max()) {
315 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000316 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000317 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000318 }
319
Steven Moreland5ae62562021-06-10 03:21:42 +0000320 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700321 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
322 data, size);
Steven Morelandee3f4662021-05-22 01:07:33 +0000323 status != OK) {
Yifan Hong702115c2021-06-24 15:39:18 -0700324 LOG_RPC_DETAIL("Failed to read %s (%zu bytes) on RpcTransport %p, error: %s", what, size,
325 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000326 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000327 }
328
Yifan Hong702115c2021-06-24 15:39:18 -0700329 LOG_RPC_DETAIL("Received %s on RpcTransport %p: %s", what, connection->rpcTransport.get(),
Steven Moreland62129012021-07-29 12:14:44 -0700330 android::base::HexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000331 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000332}
333
Steven Morelandbf57bce2021-07-26 15:26:12 -0700334status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
335 const sp<RpcSession>& session, uint32_t* version) {
336 RpcNewSessionResponse response;
337 if (status_t status =
338 rpcRec(connection, session, "new session response", &response, sizeof(response));
339 status != OK) {
340 return status;
341 }
342 *version = response.version;
343 return OK;
344}
345
Steven Moreland5ae62562021-06-10 03:21:42 +0000346status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
347 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000348 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000349 .msg = RPC_CONNECTION_INIT_OKAY,
350 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000351 return rpcSend(connection, session, "connection init", &init, sizeof(init));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000352}
353
Steven Moreland5ae62562021-06-10 03:21:42 +0000354status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
355 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000356 RpcOutgoingConnectionInit init;
Steven Moreland5ae62562021-06-10 03:21:42 +0000357 if (status_t status = rpcRec(connection, session, "connection init", &init, sizeof(init));
358 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000359 return status;
360
361 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
362 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
363 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
364 init.msg);
365 return BAD_VALUE;
366 }
367 return OK;
368}
369
Steven Moreland5ae62562021-06-10 03:21:42 +0000370sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
371 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000372 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000373 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000374 Parcel reply;
375
Steven Moreland5623d1a2021-09-10 15:45:34 -0700376 status_t status =
377 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000378 if (status != OK) {
379 ALOGE("Error getting root object: %s", statusToString(status).c_str());
380 return nullptr;
381 }
382
383 return reply.readStrongBinder();
384}
385
Steven Moreland5ae62562021-06-10 03:21:42 +0000386status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
387 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000388 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000389 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000390 Parcel reply;
391
Steven Moreland5623d1a2021-09-10 15:45:34 -0700392 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
393 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000394 if (status != OK) {
395 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
396 return status;
397 }
398
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000399 int32_t maxThreads;
400 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000401 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000402 if (maxThreads <= 0) {
403 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000404 return BAD_VALUE;
405 }
406
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000407 *maxThreadsOut = maxThreads;
408 return OK;
409}
410
Steven Moreland5ae62562021-06-10 03:21:42 +0000411status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700412 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000413 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000414 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000415 Parcel reply;
416
Steven Moreland5623d1a2021-09-10 15:45:34 -0700417 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
418 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000419 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000420 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000421 return status;
422 }
423
Steven Moreland826367f2021-09-10 14:05:31 -0700424 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000425}
426
Steven Moreland5ae62562021-06-10 03:21:42 +0000427status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
428 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
429 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000430 if (!data.isForRpc()) {
431 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
432 return BAD_TYPE;
433 }
434
435 if (data.objectsCount() != 0) {
436 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
437 return BAD_TYPE;
438 }
439
Steven Moreland5623d1a2021-09-10 15:45:34 -0700440 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000441 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
442
Steven Moreland5ae62562021-06-10 03:21:42 +0000443 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000444}
445
Steven Moreland5ae62562021-06-10 03:21:42 +0000446status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700447 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000448 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000449 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
450 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
451
Steven Moreland5553ac42020-11-11 02:14:45 +0000452 uint64_t asyncNumber = 0;
453
Steven Moreland5623d1a2021-09-10 15:45:34 -0700454 if (address != 0) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000455 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000456 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
457 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700458 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
459 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000460
461 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000462 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000463 if (!nodeProgressAsyncNumber(&it->second)) {
464 _l.unlock();
465 (void)session->shutdownAndWait(false);
466 return DEAD_OBJECT;
467 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000468 }
469 }
470
Steven Moreland77c30112021-06-02 20:45:46 +0000471 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
472 sizeof(RpcWireTransaction) <
473 data.dataSize(),
474 "Too much data %zu", data.dataSize());
475
476 RpcWireHeader command{
477 .command = RPC_COMMAND_TRANSACT,
478 .bodySize = static_cast<uint32_t>(sizeof(RpcWireTransaction) + data.dataSize()),
479 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700480
Steven Moreland5553ac42020-11-11 02:14:45 +0000481 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700482 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000483 .code = code,
484 .flags = flags,
485 .asyncNumber = asyncNumber,
486 };
Steven Moreland77c30112021-06-02 20:45:46 +0000487 CommandData transactionData(sizeof(RpcWireHeader) + sizeof(RpcWireTransaction) +
488 data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000489 if (!transactionData.valid()) {
490 return NO_MEMORY;
491 }
492
Steven Moreland77c30112021-06-02 20:45:46 +0000493 memcpy(transactionData.data() + 0, &command, sizeof(RpcWireHeader));
494 memcpy(transactionData.data() + sizeof(RpcWireHeader), &transaction,
495 sizeof(RpcWireTransaction));
496 memcpy(transactionData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireTransaction), data.data(),
497 data.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000498
Steven Moreland5ae62562021-06-10 03:21:42 +0000499 if (status_t status = rpcSend(connection, session, "transaction", transactionData.data(),
500 transactionData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000501 status != OK)
Steven Morelanda5036f02021-06-08 02:26:57 +0000502 // TODO(b/167966510): need to undo onBinderLeaving - we know the
503 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000504 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000505
506 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700507 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
508 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000509
510 // Do not wait on result.
511 // However, too many oneway calls may cause refcounts to build up and fill up the socket,
512 // so process those.
Steven Moreland5ae62562021-06-10 03:21:42 +0000513 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
Steven Moreland5553ac42020-11-11 02:14:45 +0000514 }
515
516 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
517
Steven Moreland5ae62562021-06-10 03:21:42 +0000518 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000519}
520
Steven Moreland438cce82021-04-02 18:04:08 +0000521static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
522 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000523 (void)p;
524 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
525 (void)dataSize;
526 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Yifan Hong239a2ca2021-06-24 16:05:16 -0700527 LOG_ALWAYS_FATAL_IF(objectsCount != 0, "%zu objects remaining", objectsCount);
Steven Moreland5553ac42020-11-11 02:14:45 +0000528}
529
Steven Moreland5ae62562021-06-10 03:21:42 +0000530status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
531 const sp<RpcSession>& session, Parcel* reply) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000532 RpcWireHeader command;
533 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000534 if (status_t status =
535 rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000536 status != OK)
537 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000538
539 if (command.command == RPC_COMMAND_REPLY) break;
540
Steven Moreland19fc9f72021-06-10 03:57:30 +0000541 if (status_t status = processCommand(connection, session, command, CommandType::ANY);
Steven Moreland52eee942021-06-03 00:59:28 +0000542 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000543 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000544 }
545
Steven Morelanddbe71832021-05-12 23:31:00 +0000546 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000547 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000548
Steven Moreland5ae62562021-06-10 03:21:42 +0000549 if (status_t status = rpcRec(connection, session, "reply body", data.data(), command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000550 status != OK)
551 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000552
553 if (command.bodySize < sizeof(RpcWireReply)) {
554 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
555 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000556 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000557 return BAD_VALUE;
558 }
Steven Morelande8393342021-05-05 23:27:53 +0000559 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000560 if (rpcReply->status != OK) return rpcReply->status;
561
Steven Morelande8393342021-05-05 23:27:53 +0000562 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000563 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000564 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000565
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000566 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000567
568 return OK;
569}
570
Steven Moreland5ae62562021-06-10 03:21:42 +0000571status_t RpcState::sendDecStrong(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700572 const sp<RpcSession>& session, uint64_t addr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000573 {
574 std::lock_guard<std::mutex> _l(mNodeMutex);
575 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
576 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700577 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
578 "Sending dec strong on unknown address %" PRIu64, addr);
579 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000580
581 it->second.timesRecd--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000582 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
583 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000584 }
585
586 RpcWireHeader cmd = {
587 .command = RPC_COMMAND_DEC_STRONG,
588 .bodySize = sizeof(RpcWireAddress),
589 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000590 if (status_t status = rpcSend(connection, session, "dec ref header", &cmd, sizeof(cmd));
591 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000592 return status;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700593 if (status_t status = rpcSend(connection, session, "dec ref body", &addr, sizeof(addr));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000594 status != OK)
595 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000596 return OK;
597}
598
Steven Moreland5ae62562021-06-10 03:21:42 +0000599status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
600 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700601 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000602
603 RpcWireHeader command;
Steven Moreland5ae62562021-06-10 03:21:42 +0000604 if (status_t status = rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000605 status != OK)
606 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000607
Steven Moreland19fc9f72021-06-10 03:57:30 +0000608 return processCommand(connection, session, command, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000609}
610
Steven Moreland5ae62562021-06-10 03:21:42 +0000611status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
612 const sp<RpcSession>& session, CommandType type) {
Steven Moreland52eee942021-06-03 00:59:28 +0000613 uint8_t buf;
Yifan Hong218c4072021-08-04 14:59:10 -0700614 while (connection->rpcTransport->peek(&buf, sizeof(buf)).value_or(0) > 0) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000615 status_t status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000616 if (status != OK) return status;
617 }
618 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000619}
620
Steven Moreland19fc9f72021-06-10 03:57:30 +0000621status_t RpcState::processCommand(const sp<RpcSession::RpcConnection>& connection,
622 const sp<RpcSession>& session, const RpcWireHeader& command,
623 CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000624 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
625 IPCThreadState::SpGuard spGuard{
626 .address = __builtin_frame_address(0),
627 .context = "processing binder RPC command",
628 };
629 const IPCThreadState::SpGuard* origGuard;
630 if (kernelBinderState != nullptr) {
631 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
632 }
633 ScopeGuard guardUnguard = [&]() {
634 if (kernelBinderState != nullptr) {
635 kernelBinderState->restoreGetCallingSpGuard(origGuard);
636 }
637 };
638
Steven Moreland5553ac42020-11-11 02:14:45 +0000639 switch (command.command) {
640 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000641 if (type != CommandType::ANY) return BAD_TYPE;
Steven Moreland5ae62562021-06-10 03:21:42 +0000642 return processTransact(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000643 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000644 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000645 }
646
647 // We should always know the version of the opposing side, and since the
648 // RPC-binder-level wire protocol is not self synchronizing, we have no way
649 // to understand where the current command ends and the next one begins. We
650 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000651 // to kill us, so ending the session for misbehaving client.
652 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000653 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000654 return DEAD_OBJECT;
655}
Steven Moreland5ae62562021-06-10 03:21:42 +0000656status_t RpcState::processTransact(const sp<RpcSession::RpcConnection>& connection,
657 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000658 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
659
Steven Morelanddbe71832021-05-12 23:31:00 +0000660 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000661 if (!transactionData.valid()) {
662 return NO_MEMORY;
663 }
Steven Moreland5ae62562021-06-10 03:21:42 +0000664 if (status_t status = rpcRec(connection, session, "transaction body", transactionData.data(),
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000665 transactionData.size());
666 status != OK)
667 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000668
Steven Moreland5ae62562021-06-10 03:21:42 +0000669 return processTransactInternal(connection, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000670}
671
Steven Moreland438cce82021-04-02 18:04:08 +0000672static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
673 const binder_size_t* objects, size_t objectsCount) {
674 (void)p;
675 (void)data;
676 (void)dataSize;
677 (void)objects;
678 (void)objectsCount;
679}
680
Steven Moreland5ae62562021-06-10 03:21:42 +0000681status_t RpcState::processTransactInternal(const sp<RpcSession::RpcConnection>& connection,
682 const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000683 CommandData transactionData) {
684 // for 'recursive' calls to this, we have already read and processed the
685 // binder from the transaction data and taken reference counts into account,
686 // so it is cached here.
687 sp<IBinder> targetRef;
688processTransactInternalTailCall:
689
Steven Moreland5553ac42020-11-11 02:14:45 +0000690 if (transactionData.size() < sizeof(RpcWireTransaction)) {
691 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
692 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000693 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000694 return BAD_VALUE;
695 }
696 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
697
Steven Moreland5623d1a2021-09-10 15:45:34 -0700698 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000699 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000700
701 status_t replyStatus = OK;
702 sp<IBinder> target;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700703 if (addr != 0) {
Steven Morelandf5174272021-05-25 00:39:28 +0000704 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000705 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000706 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000707 target = targetRef;
708 }
709
Steven Moreland7227c8a2021-06-02 00:24:32 +0000710 if (replyStatus != OK) {
711 // do nothing
712 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000713 // This can happen if the binder is remote in this process, and
714 // another thread has called the last decStrong on this binder.
715 // However, for local binders, it indicates a misbehaving client
716 // (any binder which is being transacted on should be holding a
717 // strong ref count), so in either case, terminating the
718 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700719 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
720 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000721 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000722 replyStatus = BAD_VALUE;
723 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700724 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
725 ". Terminating!",
726 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000727 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000728 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000729 } else if (oneway) {
Steven Morelandd45be622021-06-04 02:19:37 +0000730 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000731 auto it = mNodeForAddress.find(addr);
732 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700733 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000734 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000735 } else if (transaction->asyncNumber != it->second.asyncNumber) {
736 // we need to process some other asynchronous transaction
737 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000738 it->second.asyncTodo.push(BinderNode::AsyncTodo{
739 .ref = target,
740 .data = std::move(transactionData),
741 .asyncNumber = transaction->asyncNumber,
742 });
Steven Morelandd45be622021-06-04 02:19:37 +0000743
744 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700745 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
746 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000747
748 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
749 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
750 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
751
752 if (numPending >= kArbitraryOnewayCallWarnLevel) {
753 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
754 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
755 _l.unlock();
756 (void)session->shutdownAndWait(false);
757 return FAILED_TRANSACTION;
758 }
759
760 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
761 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
762 target.get(), numPending);
763 }
764 }
Steven Morelandf5174272021-05-25 00:39:28 +0000765 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000766 }
767 }
768 }
769
Steven Moreland5553ac42020-11-11 02:14:45 +0000770 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000771 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000772
773 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000774 Parcel data;
775 // transaction->data is owned by this function. Parcel borrows this data and
776 // only holds onto it for the duration of this function call. Parcel will be
777 // deleted before the 'transactionData' object.
778 data.ipcSetDataReference(transaction->data,
779 transactionData.size() - offsetof(RpcWireTransaction, data),
780 nullptr /*object*/, 0 /*objectCount*/,
781 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000782 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000783
Steven Moreland5553ac42020-11-11 02:14:45 +0000784 if (target) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000785 bool origAllowNested = connection->allowNested;
786 connection->allowNested = !oneway;
787
Steven Moreland5553ac42020-11-11 02:14:45 +0000788 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000789
790 connection->allowNested = origAllowNested;
Steven Moreland5553ac42020-11-11 02:14:45 +0000791 } else {
792 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000793
Steven Moreland103424e2021-06-02 18:16:19 +0000794 switch (transaction->code) {
795 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
796 replyStatus = reply.writeInt32(session->getMaxThreads());
797 break;
798 }
799 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
800 // for client connections, this should always report the value
Steven Moreland01a6bad2021-06-11 00:59:20 +0000801 // originally returned from the server, so this is asserting
802 // that it exists
Steven Moreland826367f2021-09-10 14:05:31 -0700803 replyStatus = reply.writeByteVector(session->mId);
Steven Moreland103424e2021-06-02 18:16:19 +0000804 break;
805 }
806 default: {
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000807 sp<RpcServer> server = session->server();
Steven Moreland103424e2021-06-02 18:16:19 +0000808 if (server) {
809 switch (transaction->code) {
810 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
811 replyStatus = reply.writeStrongBinder(server->getRootObject());
812 break;
813 }
814 default: {
815 replyStatus = UNKNOWN_TRANSACTION;
816 }
817 }
818 } else {
819 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000820 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000821 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000822 }
823 }
824 }
825
Steven Morelandc7d40132021-06-10 03:42:11 +0000826 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000827 if (replyStatus != OK) {
828 ALOGW("Oneway call failed with error: %d", replyStatus);
829 }
830
Steven Moreland5623d1a2021-09-10 15:45:34 -0700831 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
832 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000833
834 // Check to see if there is another asynchronous transaction to process.
835 // This behavior differs from binder behavior, since in the binder
836 // driver, asynchronous transactions will be processed after existing
837 // pending binder transactions on the queue. The downside of this is
838 // that asynchronous transactions can be drowned out by synchronous
839 // transactions. However, we have no easy way to queue these
840 // transactions after the synchronous transactions we may want to read
841 // from the wire. So, in socket binder here, we have the opposite
842 // downside: asynchronous transactions may drown out synchronous
843 // transactions.
844 {
845 std::unique_lock<std::mutex> _l(mNodeMutex);
846 auto it = mNodeForAddress.find(addr);
847 // last refcount dropped after this transaction happened
848 if (it == mNodeForAddress.end()) return OK;
849
Steven Morelandc9d7b532021-06-04 20:57:41 +0000850 if (!nodeProgressAsyncNumber(&it->second)) {
851 _l.unlock();
852 (void)session->shutdownAndWait(false);
853 return DEAD_OBJECT;
854 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000855
856 if (it->second.asyncTodo.size() == 0) return OK;
857 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700858 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
859 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000860
861 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000862 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000863 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000864 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
865
Steven Morelandada72bd2021-06-09 23:29:13 +0000866 // reset up arguments
867 transactionData = std::move(todo.data);
868 targetRef = std::move(todo.ref);
Steven Morelandf5174272021-05-25 00:39:28 +0000869
Steven Moreland5553ac42020-11-11 02:14:45 +0000870 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000871 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000872 }
873 }
874 return OK;
875 }
876
Steven Moreland77c30112021-06-02 20:45:46 +0000877 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
878 sizeof(RpcWireReply) <
879 reply.dataSize(),
880 "Too much data for reply %zu", reply.dataSize());
881
882 RpcWireHeader cmdReply{
883 .command = RPC_COMMAND_REPLY,
884 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
885 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000886 RpcWireReply rpcReply{
887 .status = replyStatus,
888 };
889
Steven Moreland77c30112021-06-02 20:45:46 +0000890 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000891 if (!replyData.valid()) {
892 return NO_MEMORY;
893 }
Steven Moreland77c30112021-06-02 20:45:46 +0000894 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
895 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
896 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
897 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000898
Steven Moreland5ae62562021-06-10 03:21:42 +0000899 return rpcSend(connection, session, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000900}
901
Steven Moreland5ae62562021-06-10 03:21:42 +0000902status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
903 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000904 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
905
Steven Morelanddbe71832021-05-12 23:31:00 +0000906 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000907 if (!commandData.valid()) {
908 return NO_MEMORY;
909 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000910 if (status_t status =
Steven Moreland5ae62562021-06-10 03:21:42 +0000911 rpcRec(connection, session, "dec ref body", commandData.data(), commandData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000912 status != OK)
913 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000914
Steven Moreland5623d1a2021-09-10 15:45:34 -0700915 if (command.bodySize != sizeof(RpcWireAddress)) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000916 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
917 sizeof(RpcWireAddress), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000918 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000919 return BAD_VALUE;
920 }
921 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
922
Steven Moreland5623d1a2021-09-10 15:45:34 -0700923 uint64_t addr = RpcWireAddress::toRaw(*address);
924
Steven Moreland5553ac42020-11-11 02:14:45 +0000925 std::unique_lock<std::mutex> _l(mNodeMutex);
926 auto it = mNodeForAddress.find(addr);
927 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700928 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000929 return OK;
930 }
931
932 sp<IBinder> target = it->second.binder.promote();
933 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700934 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
935 ". Terminating!",
936 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000937 _l.unlock();
938 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000939 return BAD_VALUE;
940 }
941
942 if (it->second.timesSent == 0) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700943 ALOGE("No record of sending binder, but requested decStrong: %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000944 return OK;
945 }
946
Steven Moreland5623d1a2021-09-10 15:45:34 -0700947 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
948 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000949
Steven Moreland5553ac42020-11-11 02:14:45 +0000950 it->second.timesSent--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000951 sp<IBinder> tempHold = tryEraseNode(it);
952 _l.unlock();
953 tempHold = nullptr; // destructor may make binder calls on this session
954
955 return OK;
956}
957
Steven Moreland5623d1a2021-09-10 15:45:34 -0700958sp<IBinder> RpcState::tryEraseNode(std::map<uint64_t, BinderNode>::iterator& it) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000959 sp<IBinder> ref;
960
Steven Moreland5553ac42020-11-11 02:14:45 +0000961 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000962 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000963
964 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +0000965 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
966 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +0000967 mNodeForAddress.erase(it);
968 }
969 }
970
Steven Moreland31bde7a2021-06-04 00:57:36 +0000971 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +0000972}
973
Steven Morelandc9d7b532021-06-04 20:57:41 +0000974bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000975 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
976 // a single binder
977 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
978 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +0000979 return false;
980 }
981 node->asyncNumber++;
982 return true;
983}
984
Steven Moreland5553ac42020-11-11 02:14:45 +0000985} // namespace android