blob: 59643ba4eec1e8c4c178f6ad5eb5d36f0f2cddd6 [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 Morelandbdb53ab2021-05-05 17:57:41 +000059 if (isRpc && binder->remoteBinder()->getPrivateAccessorForId().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
88 uint64_t actualAddr =
Steven Moreland5553ac42020-11-11 02:14:45 +000089 binder->remoteBinder()->getPrivateAccessorForId().rpcAddress();
Steven Moreland5623d1a2021-09-10 15:45:34 -070090 LOG_ALWAYS_FATAL_IF(addr != actualAddr, "Address mismatch %" PRIu64 " vs %" PRIu64,
91 addr, actualAddr);
Steven Moreland5553ac42020-11-11 02:14:45 +000092 }
93 node.timesSent++;
94 node.sentRef = binder; // might already be set
95 *outAddress = addr;
96 return OK;
97 }
98 }
99 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
100
Steven Moreland91538242021-06-10 23:35:35 +0000101 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +0000102
Steven Moreland5623d1a2021-09-10 15:45:34 -0700103 // arbitrary limit for maximum number of nodes in a process (otherwise we
104 // might run out of addresses)
105 if (mNodeForAddress.size() > 100000) {
106 return NO_MEMORY;
107 }
108
109 while (true) {
110 RpcWireAddress address{
111 .options = RPC_WIRE_ADDRESS_OPTION_CREATED,
112 .address = mNextId,
113 };
114 if (forServer) {
115 address.options |= RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
116 }
117
118 // avoid ubsan abort
119 if (mNextId >= std::numeric_limits<uint32_t>::max()) {
120 mNextId = 0;
121 } else {
122 mNextId++;
123 }
124
125 auto&& [it, inserted] = mNodeForAddress.insert({RpcWireAddress::toRaw(address),
Steven Moreland91538242021-06-10 23:35:35 +0000126 BinderNode{
127 .binder = binder,
128 .timesSent = 1,
129 .sentRef = binder,
130 }});
131 if (inserted) {
132 *outAddress = it->first;
133 return OK;
134 }
Steven Moreland91538242021-06-10 23:35:35 +0000135 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000136}
137
Steven Moreland5623d1a2021-09-10 15:45:34 -0700138status_t RpcState::onBinderEntering(const sp<RpcSession>& session, uint64_t address,
Steven Moreland7227c8a2021-06-02 00:24:32 +0000139 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000140 // ensure that: if we want to use addresses for something else in the future (for
141 // instance, allowing transitive binder sends), that we don't accidentally
142 // send those addresses to old server. Accidentally ignoring this in that
143 // case and considering the binder to be recognized could cause this
144 // process to accidentally proxy transactions for that binder. Of course,
145 // if we communicate with a binder, it could always be proxying
146 // information. However, we want to make sure that isn't done on accident
147 // by a client.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700148 RpcWireAddress addr = RpcWireAddress::fromRaw(address);
149 constexpr uint32_t kKnownOptions =
150 RPC_WIRE_ADDRESS_OPTION_CREATED | RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
151 if (addr.options & ~kKnownOptions) {
152 ALOGE("Address is of an unknown type, rejecting: %" PRIu64, address);
Steven Moreland91538242021-06-10 23:35:35 +0000153 return BAD_VALUE;
154 }
155
Steven Moreland5553ac42020-11-11 02:14:45 +0000156 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000157 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000158
159 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000160 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000161
162 // implicitly have strong RPC refcount, since we received this binder
163 it->second.timesRecd++;
164
165 _l.unlock();
166
167 // We have timesRecd RPC refcounts, but we only need to hold on to one
168 // when we keep the object. All additional dec strongs are sent
169 // immediately, we wait to send the last one in BpBinder::onLastDecStrong.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000170 (void)session->sendDecStrong(address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000171
Steven Moreland7227c8a2021-06-02 00:24:32 +0000172 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000173 }
174
Steven Moreland91538242021-06-10 23:35:35 +0000175 // we don't know about this binder, so the other side of the connection
176 // should have created it.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700177 if ((addr.options & RPC_WIRE_ADDRESS_OPTION_FOR_SERVER) == !!session->server()) {
178 ALOGE("Server received unrecognized address which we should own the creation of %" PRIu64,
179 address);
Steven Moreland91538242021-06-10 23:35:35 +0000180 return BAD_VALUE;
181 }
182
Steven Moreland5553ac42020-11-11 02:14:45 +0000183 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
184 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
185
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000186 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000187 // device global binders in the RPC world).
Steven Moreland7227c8a2021-06-02 00:24:32 +0000188 it->second.binder = *out = BpBinder::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000189 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000190 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000191}
192
193size_t RpcState::countBinders() {
194 std::lock_guard<std::mutex> _l(mNodeMutex);
195 return mNodeForAddress.size();
196}
197
198void RpcState::dump() {
199 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000200 dumpLocked();
201}
202
Steven Morelandc9d7b532021-06-04 20:57:41 +0000203void RpcState::clear() {
Steven Moreland583a14a2021-06-04 02:04:58 +0000204 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000205
206 if (mTerminated) {
207 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
208 "New state should be impossible after terminating!");
209 return;
210 }
211
212 if (SHOULD_LOG_RPC_DETAIL) {
213 ALOGE("RpcState::clear()");
214 dumpLocked();
215 }
216
217 // if the destructor of a binder object makes another RPC call, then calling
218 // decStrong could deadlock. So, we must hold onto these binders until
219 // mNodeMutex is no longer taken.
220 std::vector<sp<IBinder>> tempHoldBinder;
221
222 mTerminated = true;
223 for (auto& [address, node] : mNodeForAddress) {
224 sp<IBinder> binder = node.binder.promote();
225 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
226
227 if (node.sentRef != nullptr) {
228 tempHoldBinder.push_back(node.sentRef);
229 }
230 }
231
232 mNodeForAddress.clear();
233
234 _l.unlock();
235 tempHoldBinder.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000236}
237
238void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000239 ALOGE("DUMP OF RpcState %p", this);
240 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
241 for (const auto& [address, node] : mNodeForAddress) {
242 sp<IBinder> binder = node.binder.promote();
243
244 const char* desc;
245 if (binder) {
246 if (binder->remoteBinder()) {
247 if (binder->remoteBinder()->isRpcBinder()) {
248 desc = "(rpc binder proxy)";
249 } else {
250 desc = "(binder proxy)";
251 }
252 } else {
253 desc = "(local binder)";
254 }
255 } else {
256 desc = "(null)";
257 }
258
Steven Moreland5623d1a2021-09-10 15:45:34 -0700259 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a: %" PRIu64 " type: %s",
260 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address, desc);
Steven Moreland5553ac42020-11-11 02:14:45 +0000261 }
262 ALOGE("END DUMP OF RpcState");
263}
264
Steven Moreland5553ac42020-11-11 02:14:45 +0000265
Steven Morelanddbe71832021-05-12 23:31:00 +0000266RpcState::CommandData::CommandData(size_t size) : mSize(size) {
267 // The maximum size for regular binder is 1MB for all concurrent
268 // transactions. A very small proportion of transactions are even
269 // larger than a page, but we need to avoid allocating too much
270 // data on behalf of an arbitrary client, or we could risk being in
271 // a position where a single additional allocation could run out of
272 // memory.
273 //
274 // Note, this limit may not reflect the total amount of data allocated for a
275 // transaction (in some cases, additional fixed size amounts are added),
276 // though for rough consistency, we should avoid cases where this data type
277 // is used for multiple dynamic allocations for a single transaction.
278 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
279 if (size == 0) return;
280 if (size > kMaxTransactionAllocation) {
281 ALOGW("Transaction requested too much data allocation %zu", size);
282 return;
283 }
284 mData.reset(new (std::nothrow) uint8_t[size]);
285}
286
Steven Moreland5ae62562021-06-10 03:21:42 +0000287status_t RpcState::rpcSend(const sp<RpcSession::RpcConnection>& connection,
288 const sp<RpcSession>& session, const char* what, const void* data,
289 size_t size) {
Yifan Hong702115c2021-06-24 15:39:18 -0700290 LOG_RPC_DETAIL("Sending %s on RpcTransport %p: %s", what, connection->rpcTransport.get(),
Steven Moreland62129012021-07-29 12:14:44 -0700291 android::base::HexString(data, size).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000292
293 if (size > std::numeric_limits<ssize_t>::max()) {
294 ALOGE("Cannot send %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000295 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000296 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000297 }
298
Yifan Hong702115c2021-06-24 15:39:18 -0700299 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700300 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
301 data, size);
Steven Moreland798e0d12021-07-14 23:19:25 +0000302 status != OK) {
Yifan Hong702115c2021-06-24 15:39:18 -0700303 LOG_RPC_DETAIL("Failed to write %s (%zu bytes) on RpcTransport %p, error: %s", what, size,
304 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000305 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000306 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000307 }
308
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000309 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000310}
311
Steven Moreland5ae62562021-06-10 03:21:42 +0000312status_t RpcState::rpcRec(const sp<RpcSession::RpcConnection>& connection,
313 const sp<RpcSession>& session, const char* what, void* data,
314 size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000315 if (size > std::numeric_limits<ssize_t>::max()) {
316 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000317 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000318 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000319 }
320
Steven Moreland5ae62562021-06-10 03:21:42 +0000321 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700322 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
323 data, size);
Steven Morelandee3f4662021-05-22 01:07:33 +0000324 status != OK) {
Yifan Hong702115c2021-06-24 15:39:18 -0700325 LOG_RPC_DETAIL("Failed to read %s (%zu bytes) on RpcTransport %p, error: %s", what, size,
326 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000327 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000328 }
329
Yifan Hong702115c2021-06-24 15:39:18 -0700330 LOG_RPC_DETAIL("Received %s on RpcTransport %p: %s", what, connection->rpcTransport.get(),
Steven Moreland62129012021-07-29 12:14:44 -0700331 android::base::HexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000332 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000333}
334
Steven Morelandbf57bce2021-07-26 15:26:12 -0700335status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
336 const sp<RpcSession>& session, uint32_t* version) {
337 RpcNewSessionResponse response;
338 if (status_t status =
339 rpcRec(connection, session, "new session response", &response, sizeof(response));
340 status != OK) {
341 return status;
342 }
343 *version = response.version;
344 return OK;
345}
346
Steven Moreland5ae62562021-06-10 03:21:42 +0000347status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
348 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000349 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000350 .msg = RPC_CONNECTION_INIT_OKAY,
351 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000352 return rpcSend(connection, session, "connection init", &init, sizeof(init));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000353}
354
Steven Moreland5ae62562021-06-10 03:21:42 +0000355status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
356 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000357 RpcOutgoingConnectionInit init;
Steven Moreland5ae62562021-06-10 03:21:42 +0000358 if (status_t status = rpcRec(connection, session, "connection init", &init, sizeof(init));
359 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000360 return status;
361
362 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
363 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
364 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
365 init.msg);
366 return BAD_VALUE;
367 }
368 return OK;
369}
370
Steven Moreland5ae62562021-06-10 03:21:42 +0000371sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
372 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000373 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000374 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000375 Parcel reply;
376
Steven Moreland5623d1a2021-09-10 15:45:34 -0700377 status_t status =
378 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000379 if (status != OK) {
380 ALOGE("Error getting root object: %s", statusToString(status).c_str());
381 return nullptr;
382 }
383
384 return reply.readStrongBinder();
385}
386
Steven Moreland5ae62562021-06-10 03:21:42 +0000387status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
388 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000389 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000390 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000391 Parcel reply;
392
Steven Moreland5623d1a2021-09-10 15:45:34 -0700393 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
394 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000395 if (status != OK) {
396 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
397 return status;
398 }
399
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000400 int32_t maxThreads;
401 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000402 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000403 if (maxThreads <= 0) {
404 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000405 return BAD_VALUE;
406 }
407
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000408 *maxThreadsOut = maxThreads;
409 return OK;
410}
411
Steven Moreland5ae62562021-06-10 03:21:42 +0000412status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700413 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000414 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000415 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000416 Parcel reply;
417
Steven Moreland5623d1a2021-09-10 15:45:34 -0700418 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
419 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000420 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000421 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000422 return status;
423 }
424
Steven Moreland826367f2021-09-10 14:05:31 -0700425 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000426}
427
Steven Moreland5ae62562021-06-10 03:21:42 +0000428status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
429 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
430 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000431 if (!data.isForRpc()) {
432 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
433 return BAD_TYPE;
434 }
435
436 if (data.objectsCount() != 0) {
437 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
438 return BAD_TYPE;
439 }
440
Steven Moreland5623d1a2021-09-10 15:45:34 -0700441 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000442 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
443
Steven Moreland5ae62562021-06-10 03:21:42 +0000444 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000445}
446
Steven Moreland5ae62562021-06-10 03:21:42 +0000447status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700448 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000449 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000450 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
451 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
452
Steven Moreland5553ac42020-11-11 02:14:45 +0000453 uint64_t asyncNumber = 0;
454
Steven Moreland5623d1a2021-09-10 15:45:34 -0700455 if (address != 0) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000456 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000457 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
458 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700459 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
460 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000461
462 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000463 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000464 if (!nodeProgressAsyncNumber(&it->second)) {
465 _l.unlock();
466 (void)session->shutdownAndWait(false);
467 return DEAD_OBJECT;
468 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000469 }
470 }
471
Steven Moreland77c30112021-06-02 20:45:46 +0000472 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
473 sizeof(RpcWireTransaction) <
474 data.dataSize(),
475 "Too much data %zu", data.dataSize());
476
477 RpcWireHeader command{
478 .command = RPC_COMMAND_TRANSACT,
479 .bodySize = static_cast<uint32_t>(sizeof(RpcWireTransaction) + data.dataSize()),
480 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700481
Steven Moreland5553ac42020-11-11 02:14:45 +0000482 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700483 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000484 .code = code,
485 .flags = flags,
486 .asyncNumber = asyncNumber,
487 };
Steven Moreland77c30112021-06-02 20:45:46 +0000488 CommandData transactionData(sizeof(RpcWireHeader) + sizeof(RpcWireTransaction) +
489 data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000490 if (!transactionData.valid()) {
491 return NO_MEMORY;
492 }
493
Steven Moreland77c30112021-06-02 20:45:46 +0000494 memcpy(transactionData.data() + 0, &command, sizeof(RpcWireHeader));
495 memcpy(transactionData.data() + sizeof(RpcWireHeader), &transaction,
496 sizeof(RpcWireTransaction));
497 memcpy(transactionData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireTransaction), data.data(),
498 data.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000499
Steven Moreland5ae62562021-06-10 03:21:42 +0000500 if (status_t status = rpcSend(connection, session, "transaction", transactionData.data(),
501 transactionData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000502 status != OK)
Steven Morelanda5036f02021-06-08 02:26:57 +0000503 // TODO(b/167966510): need to undo onBinderLeaving - we know the
504 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000505 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000506
507 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700508 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
509 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000510
511 // Do not wait on result.
512 // However, too many oneway calls may cause refcounts to build up and fill up the socket,
513 // so process those.
Steven Moreland5ae62562021-06-10 03:21:42 +0000514 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
Steven Moreland5553ac42020-11-11 02:14:45 +0000515 }
516
517 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
518
Steven Moreland5ae62562021-06-10 03:21:42 +0000519 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000520}
521
Steven Moreland438cce82021-04-02 18:04:08 +0000522static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
523 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000524 (void)p;
525 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
526 (void)dataSize;
527 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Yifan Hong239a2ca2021-06-24 16:05:16 -0700528 LOG_ALWAYS_FATAL_IF(objectsCount != 0, "%zu objects remaining", objectsCount);
Steven Moreland5553ac42020-11-11 02:14:45 +0000529}
530
Steven Moreland5ae62562021-06-10 03:21:42 +0000531status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
532 const sp<RpcSession>& session, Parcel* reply) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000533 RpcWireHeader command;
534 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000535 if (status_t status =
536 rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000537 status != OK)
538 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000539
540 if (command.command == RPC_COMMAND_REPLY) break;
541
Steven Moreland19fc9f72021-06-10 03:57:30 +0000542 if (status_t status = processCommand(connection, session, command, CommandType::ANY);
Steven Moreland52eee942021-06-03 00:59:28 +0000543 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000544 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000545 }
546
Steven Morelanddbe71832021-05-12 23:31:00 +0000547 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000548 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000549
Steven Moreland5ae62562021-06-10 03:21:42 +0000550 if (status_t status = rpcRec(connection, session, "reply body", data.data(), command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000551 status != OK)
552 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000553
554 if (command.bodySize < sizeof(RpcWireReply)) {
555 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
556 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000557 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000558 return BAD_VALUE;
559 }
Steven Morelande8393342021-05-05 23:27:53 +0000560 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000561 if (rpcReply->status != OK) return rpcReply->status;
562
Steven Morelande8393342021-05-05 23:27:53 +0000563 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000564 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000565 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000566
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000567 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000568
569 return OK;
570}
571
Steven Moreland5ae62562021-06-10 03:21:42 +0000572status_t RpcState::sendDecStrong(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700573 const sp<RpcSession>& session, uint64_t addr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000574 {
575 std::lock_guard<std::mutex> _l(mNodeMutex);
576 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
577 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700578 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
579 "Sending dec strong on unknown address %" PRIu64, addr);
580 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000581
582 it->second.timesRecd--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000583 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
584 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000585 }
586
587 RpcWireHeader cmd = {
588 .command = RPC_COMMAND_DEC_STRONG,
589 .bodySize = sizeof(RpcWireAddress),
590 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000591 if (status_t status = rpcSend(connection, session, "dec ref header", &cmd, sizeof(cmd));
592 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000593 return status;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700594 if (status_t status = rpcSend(connection, session, "dec ref body", &addr, sizeof(addr));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000595 status != OK)
596 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000597 return OK;
598}
599
Steven Moreland5ae62562021-06-10 03:21:42 +0000600status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
601 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700602 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000603
604 RpcWireHeader command;
Steven Moreland5ae62562021-06-10 03:21:42 +0000605 if (status_t status = rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000606 status != OK)
607 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000608
Steven Moreland19fc9f72021-06-10 03:57:30 +0000609 return processCommand(connection, session, command, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000610}
611
Steven Moreland5ae62562021-06-10 03:21:42 +0000612status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
613 const sp<RpcSession>& session, CommandType type) {
Steven Moreland52eee942021-06-03 00:59:28 +0000614 uint8_t buf;
Yifan Hong218c4072021-08-04 14:59:10 -0700615 while (connection->rpcTransport->peek(&buf, sizeof(buf)).value_or(0) > 0) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000616 status_t status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000617 if (status != OK) return status;
618 }
619 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000620}
621
Steven Moreland19fc9f72021-06-10 03:57:30 +0000622status_t RpcState::processCommand(const sp<RpcSession::RpcConnection>& connection,
623 const sp<RpcSession>& session, const RpcWireHeader& command,
624 CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000625 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
626 IPCThreadState::SpGuard spGuard{
627 .address = __builtin_frame_address(0),
628 .context = "processing binder RPC command",
629 };
630 const IPCThreadState::SpGuard* origGuard;
631 if (kernelBinderState != nullptr) {
632 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
633 }
634 ScopeGuard guardUnguard = [&]() {
635 if (kernelBinderState != nullptr) {
636 kernelBinderState->restoreGetCallingSpGuard(origGuard);
637 }
638 };
639
Steven Moreland5553ac42020-11-11 02:14:45 +0000640 switch (command.command) {
641 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000642 if (type != CommandType::ANY) return BAD_TYPE;
Steven Moreland5ae62562021-06-10 03:21:42 +0000643 return processTransact(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000644 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000645 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000646 }
647
648 // We should always know the version of the opposing side, and since the
649 // RPC-binder-level wire protocol is not self synchronizing, we have no way
650 // to understand where the current command ends and the next one begins. We
651 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000652 // to kill us, so ending the session for misbehaving client.
653 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000654 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000655 return DEAD_OBJECT;
656}
Steven Moreland5ae62562021-06-10 03:21:42 +0000657status_t RpcState::processTransact(const sp<RpcSession::RpcConnection>& connection,
658 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000659 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
660
Steven Morelanddbe71832021-05-12 23:31:00 +0000661 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000662 if (!transactionData.valid()) {
663 return NO_MEMORY;
664 }
Steven Moreland5ae62562021-06-10 03:21:42 +0000665 if (status_t status = rpcRec(connection, session, "transaction body", transactionData.data(),
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000666 transactionData.size());
667 status != OK)
668 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000669
Steven Moreland5ae62562021-06-10 03:21:42 +0000670 return processTransactInternal(connection, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000671}
672
Steven Moreland438cce82021-04-02 18:04:08 +0000673static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
674 const binder_size_t* objects, size_t objectsCount) {
675 (void)p;
676 (void)data;
677 (void)dataSize;
678 (void)objects;
679 (void)objectsCount;
680}
681
Steven Moreland5ae62562021-06-10 03:21:42 +0000682status_t RpcState::processTransactInternal(const sp<RpcSession::RpcConnection>& connection,
683 const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000684 CommandData transactionData) {
685 // for 'recursive' calls to this, we have already read and processed the
686 // binder from the transaction data and taken reference counts into account,
687 // so it is cached here.
688 sp<IBinder> targetRef;
689processTransactInternalTailCall:
690
Steven Moreland5553ac42020-11-11 02:14:45 +0000691 if (transactionData.size() < sizeof(RpcWireTransaction)) {
692 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
693 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000694 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000695 return BAD_VALUE;
696 }
697 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
698
Steven Moreland5623d1a2021-09-10 15:45:34 -0700699 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000700 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000701
702 status_t replyStatus = OK;
703 sp<IBinder> target;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700704 if (addr != 0) {
Steven Morelandf5174272021-05-25 00:39:28 +0000705 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000706 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000707 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000708 target = targetRef;
709 }
710
Steven Moreland7227c8a2021-06-02 00:24:32 +0000711 if (replyStatus != OK) {
712 // do nothing
713 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000714 // This can happen if the binder is remote in this process, and
715 // another thread has called the last decStrong on this binder.
716 // However, for local binders, it indicates a misbehaving client
717 // (any binder which is being transacted on should be holding a
718 // strong ref count), so in either case, terminating the
719 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700720 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
721 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000722 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000723 replyStatus = BAD_VALUE;
724 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700725 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
726 ". Terminating!",
727 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000728 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000729 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000730 } else if (oneway) {
Steven Morelandd45be622021-06-04 02:19:37 +0000731 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000732 auto it = mNodeForAddress.find(addr);
733 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700734 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000735 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000736 } else if (transaction->asyncNumber != it->second.asyncNumber) {
737 // we need to process some other asynchronous transaction
738 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000739 it->second.asyncTodo.push(BinderNode::AsyncTodo{
740 .ref = target,
741 .data = std::move(transactionData),
742 .asyncNumber = transaction->asyncNumber,
743 });
Steven Morelandd45be622021-06-04 02:19:37 +0000744
745 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700746 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
747 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000748
749 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
750 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
751 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
752
753 if (numPending >= kArbitraryOnewayCallWarnLevel) {
754 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
755 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
756 _l.unlock();
757 (void)session->shutdownAndWait(false);
758 return FAILED_TRANSACTION;
759 }
760
761 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
762 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
763 target.get(), numPending);
764 }
765 }
Steven Morelandf5174272021-05-25 00:39:28 +0000766 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000767 }
768 }
769 }
770
Steven Moreland5553ac42020-11-11 02:14:45 +0000771 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000772 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000773
774 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000775 Parcel data;
776 // transaction->data is owned by this function. Parcel borrows this data and
777 // only holds onto it for the duration of this function call. Parcel will be
778 // deleted before the 'transactionData' object.
779 data.ipcSetDataReference(transaction->data,
780 transactionData.size() - offsetof(RpcWireTransaction, data),
781 nullptr /*object*/, 0 /*objectCount*/,
782 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000783 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000784
Steven Moreland5553ac42020-11-11 02:14:45 +0000785 if (target) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000786 bool origAllowNested = connection->allowNested;
787 connection->allowNested = !oneway;
788
Steven Moreland5553ac42020-11-11 02:14:45 +0000789 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000790
791 connection->allowNested = origAllowNested;
Steven Moreland5553ac42020-11-11 02:14:45 +0000792 } else {
793 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000794
Steven Moreland103424e2021-06-02 18:16:19 +0000795 switch (transaction->code) {
796 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
797 replyStatus = reply.writeInt32(session->getMaxThreads());
798 break;
799 }
800 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
801 // for client connections, this should always report the value
Steven Moreland01a6bad2021-06-11 00:59:20 +0000802 // originally returned from the server, so this is asserting
803 // that it exists
Steven Moreland826367f2021-09-10 14:05:31 -0700804 replyStatus = reply.writeByteVector(session->mId);
Steven Moreland103424e2021-06-02 18:16:19 +0000805 break;
806 }
807 default: {
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000808 sp<RpcServer> server = session->server();
Steven Moreland103424e2021-06-02 18:16:19 +0000809 if (server) {
810 switch (transaction->code) {
811 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
812 replyStatus = reply.writeStrongBinder(server->getRootObject());
813 break;
814 }
815 default: {
816 replyStatus = UNKNOWN_TRANSACTION;
817 }
818 }
819 } else {
820 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000821 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000822 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000823 }
824 }
825 }
826
Steven Morelandc7d40132021-06-10 03:42:11 +0000827 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000828 if (replyStatus != OK) {
829 ALOGW("Oneway call failed with error: %d", replyStatus);
830 }
831
Steven Moreland5623d1a2021-09-10 15:45:34 -0700832 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
833 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000834
835 // Check to see if there is another asynchronous transaction to process.
836 // This behavior differs from binder behavior, since in the binder
837 // driver, asynchronous transactions will be processed after existing
838 // pending binder transactions on the queue. The downside of this is
839 // that asynchronous transactions can be drowned out by synchronous
840 // transactions. However, we have no easy way to queue these
841 // transactions after the synchronous transactions we may want to read
842 // from the wire. So, in socket binder here, we have the opposite
843 // downside: asynchronous transactions may drown out synchronous
844 // transactions.
845 {
846 std::unique_lock<std::mutex> _l(mNodeMutex);
847 auto it = mNodeForAddress.find(addr);
848 // last refcount dropped after this transaction happened
849 if (it == mNodeForAddress.end()) return OK;
850
Steven Morelandc9d7b532021-06-04 20:57:41 +0000851 if (!nodeProgressAsyncNumber(&it->second)) {
852 _l.unlock();
853 (void)session->shutdownAndWait(false);
854 return DEAD_OBJECT;
855 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000856
857 if (it->second.asyncTodo.size() == 0) return OK;
858 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700859 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
860 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000861
862 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000863 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000864 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000865 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
866
Steven Morelandada72bd2021-06-09 23:29:13 +0000867 // reset up arguments
868 transactionData = std::move(todo.data);
869 targetRef = std::move(todo.ref);
Steven Morelandf5174272021-05-25 00:39:28 +0000870
Steven Moreland5553ac42020-11-11 02:14:45 +0000871 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000872 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000873 }
874 }
875 return OK;
876 }
877
Steven Moreland77c30112021-06-02 20:45:46 +0000878 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
879 sizeof(RpcWireReply) <
880 reply.dataSize(),
881 "Too much data for reply %zu", reply.dataSize());
882
883 RpcWireHeader cmdReply{
884 .command = RPC_COMMAND_REPLY,
885 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
886 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000887 RpcWireReply rpcReply{
888 .status = replyStatus,
889 };
890
Steven Moreland77c30112021-06-02 20:45:46 +0000891 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000892 if (!replyData.valid()) {
893 return NO_MEMORY;
894 }
Steven Moreland77c30112021-06-02 20:45:46 +0000895 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
896 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
897 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
898 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000899
Steven Moreland5ae62562021-06-10 03:21:42 +0000900 return rpcSend(connection, session, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000901}
902
Steven Moreland5ae62562021-06-10 03:21:42 +0000903status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
904 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000905 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
906
Steven Morelanddbe71832021-05-12 23:31:00 +0000907 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000908 if (!commandData.valid()) {
909 return NO_MEMORY;
910 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000911 if (status_t status =
Steven Moreland5ae62562021-06-10 03:21:42 +0000912 rpcRec(connection, session, "dec ref body", commandData.data(), commandData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000913 status != OK)
914 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000915
Steven Moreland5623d1a2021-09-10 15:45:34 -0700916 if (command.bodySize != sizeof(RpcWireAddress)) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000917 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
918 sizeof(RpcWireAddress), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000919 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000920 return BAD_VALUE;
921 }
922 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
923
Steven Moreland5623d1a2021-09-10 15:45:34 -0700924 uint64_t addr = RpcWireAddress::toRaw(*address);
925
Steven Moreland5553ac42020-11-11 02:14:45 +0000926 std::unique_lock<std::mutex> _l(mNodeMutex);
927 auto it = mNodeForAddress.find(addr);
928 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700929 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000930 return OK;
931 }
932
933 sp<IBinder> target = it->second.binder.promote();
934 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700935 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
936 ". Terminating!",
937 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000938 _l.unlock();
939 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000940 return BAD_VALUE;
941 }
942
943 if (it->second.timesSent == 0) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700944 ALOGE("No record of sending binder, but requested decStrong: %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000945 return OK;
946 }
947
Steven Moreland5623d1a2021-09-10 15:45:34 -0700948 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
949 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000950
Steven Moreland5553ac42020-11-11 02:14:45 +0000951 it->second.timesSent--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000952 sp<IBinder> tempHold = tryEraseNode(it);
953 _l.unlock();
954 tempHold = nullptr; // destructor may make binder calls on this session
955
956 return OK;
957}
958
Steven Moreland5623d1a2021-09-10 15:45:34 -0700959sp<IBinder> RpcState::tryEraseNode(std::map<uint64_t, BinderNode>::iterator& it) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000960 sp<IBinder> ref;
961
Steven Moreland5553ac42020-11-11 02:14:45 +0000962 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000963 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000964
965 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +0000966 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
967 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +0000968 mNodeForAddress.erase(it);
969 }
970 }
971
Steven Moreland31bde7a2021-06-04 00:57:36 +0000972 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +0000973}
974
Steven Morelandc9d7b532021-06-04 20:57:41 +0000975bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000976 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
977 // a single binder
978 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
979 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +0000980 return false;
981 }
982 node->asyncNumber++;
983 return true;
984}
985
Steven Moreland5553ac42020-11-11 02:14:45 +0000986} // namespace android