blob: dcba837a8588f7b03049c1964aaf55a13548a378 [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 Morelandae58f432021-08-05 17:53:16 -0700326 (void)session->shutdownAndWait(false);
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 Morelandae58f432021-08-05 17:53:16 -0700535 if (status_t status = rpcRec(connection, session, "command header (for reply)", &command,
536 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 Morelandae58f432021-08-05 17:53:16 -0700605 if (status_t status = rpcRec(connection, session, "command header (for server)", &command,
606 sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000607 status != OK)
608 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000609
Steven Moreland19fc9f72021-06-10 03:57:30 +0000610 return processCommand(connection, session, command, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000611}
612
Steven Moreland5ae62562021-06-10 03:21:42 +0000613status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
614 const sp<RpcSession>& session, CommandType type) {
Steven Moreland52eee942021-06-03 00:59:28 +0000615 uint8_t buf;
Yifan Hong218c4072021-08-04 14:59:10 -0700616 while (connection->rpcTransport->peek(&buf, sizeof(buf)).value_or(0) > 0) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000617 status_t status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000618 if (status != OK) return status;
619 }
620 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000621}
622
Steven Moreland19fc9f72021-06-10 03:57:30 +0000623status_t RpcState::processCommand(const sp<RpcSession::RpcConnection>& connection,
624 const sp<RpcSession>& session, const RpcWireHeader& command,
625 CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000626 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
627 IPCThreadState::SpGuard spGuard{
628 .address = __builtin_frame_address(0),
629 .context = "processing binder RPC command",
630 };
631 const IPCThreadState::SpGuard* origGuard;
632 if (kernelBinderState != nullptr) {
633 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
634 }
635 ScopeGuard guardUnguard = [&]() {
636 if (kernelBinderState != nullptr) {
637 kernelBinderState->restoreGetCallingSpGuard(origGuard);
638 }
639 };
640
Steven Moreland5553ac42020-11-11 02:14:45 +0000641 switch (command.command) {
642 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000643 if (type != CommandType::ANY) return BAD_TYPE;
Steven Moreland5ae62562021-06-10 03:21:42 +0000644 return processTransact(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000645 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000646 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000647 }
648
649 // We should always know the version of the opposing side, and since the
650 // RPC-binder-level wire protocol is not self synchronizing, we have no way
651 // to understand where the current command ends and the next one begins. We
652 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000653 // to kill us, so ending the session for misbehaving client.
654 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000655 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000656 return DEAD_OBJECT;
657}
Steven Moreland5ae62562021-06-10 03:21:42 +0000658status_t RpcState::processTransact(const sp<RpcSession::RpcConnection>& connection,
659 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000660 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
661
Steven Morelanddbe71832021-05-12 23:31:00 +0000662 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000663 if (!transactionData.valid()) {
664 return NO_MEMORY;
665 }
Steven Moreland5ae62562021-06-10 03:21:42 +0000666 if (status_t status = rpcRec(connection, session, "transaction body", transactionData.data(),
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000667 transactionData.size());
668 status != OK)
669 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000670
Steven Moreland5ae62562021-06-10 03:21:42 +0000671 return processTransactInternal(connection, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000672}
673
Steven Moreland438cce82021-04-02 18:04:08 +0000674static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
675 const binder_size_t* objects, size_t objectsCount) {
676 (void)p;
677 (void)data;
678 (void)dataSize;
679 (void)objects;
680 (void)objectsCount;
681}
682
Steven Moreland5ae62562021-06-10 03:21:42 +0000683status_t RpcState::processTransactInternal(const sp<RpcSession::RpcConnection>& connection,
684 const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000685 CommandData transactionData) {
686 // for 'recursive' calls to this, we have already read and processed the
687 // binder from the transaction data and taken reference counts into account,
688 // so it is cached here.
689 sp<IBinder> targetRef;
690processTransactInternalTailCall:
691
Steven Moreland5553ac42020-11-11 02:14:45 +0000692 if (transactionData.size() < sizeof(RpcWireTransaction)) {
693 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
694 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000695 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000696 return BAD_VALUE;
697 }
698 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
699
Steven Moreland5623d1a2021-09-10 15:45:34 -0700700 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000701 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000702
703 status_t replyStatus = OK;
704 sp<IBinder> target;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700705 if (addr != 0) {
Steven Morelandf5174272021-05-25 00:39:28 +0000706 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000707 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000708 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000709 target = targetRef;
710 }
711
Steven Moreland7227c8a2021-06-02 00:24:32 +0000712 if (replyStatus != OK) {
713 // do nothing
714 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000715 // This can happen if the binder is remote in this process, and
716 // another thread has called the last decStrong on this binder.
717 // However, for local binders, it indicates a misbehaving client
718 // (any binder which is being transacted on should be holding a
719 // strong ref count), so in either case, terminating the
720 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700721 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
722 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000723 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000724 replyStatus = BAD_VALUE;
725 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700726 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
727 ". Terminating!",
728 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000729 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000730 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000731 } else if (oneway) {
Steven Morelandd45be622021-06-04 02:19:37 +0000732 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000733 auto it = mNodeForAddress.find(addr);
734 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700735 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000736 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000737 } else if (transaction->asyncNumber != it->second.asyncNumber) {
738 // we need to process some other asynchronous transaction
739 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000740 it->second.asyncTodo.push(BinderNode::AsyncTodo{
741 .ref = target,
742 .data = std::move(transactionData),
743 .asyncNumber = transaction->asyncNumber,
744 });
Steven Morelandd45be622021-06-04 02:19:37 +0000745
746 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700747 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
748 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000749
750 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
751 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
752 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
753
754 if (numPending >= kArbitraryOnewayCallWarnLevel) {
755 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
756 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
757 _l.unlock();
758 (void)session->shutdownAndWait(false);
759 return FAILED_TRANSACTION;
760 }
761
762 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
763 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
764 target.get(), numPending);
765 }
766 }
Steven Morelandf5174272021-05-25 00:39:28 +0000767 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000768 }
769 }
770 }
771
Steven Moreland5553ac42020-11-11 02:14:45 +0000772 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000773 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000774
775 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000776 Parcel data;
777 // transaction->data is owned by this function. Parcel borrows this data and
778 // only holds onto it for the duration of this function call. Parcel will be
779 // deleted before the 'transactionData' object.
780 data.ipcSetDataReference(transaction->data,
781 transactionData.size() - offsetof(RpcWireTransaction, data),
782 nullptr /*object*/, 0 /*objectCount*/,
783 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000784 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000785
Steven Moreland5553ac42020-11-11 02:14:45 +0000786 if (target) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000787 bool origAllowNested = connection->allowNested;
788 connection->allowNested = !oneway;
789
Steven Moreland5553ac42020-11-11 02:14:45 +0000790 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000791
792 connection->allowNested = origAllowNested;
Steven Moreland5553ac42020-11-11 02:14:45 +0000793 } else {
794 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000795
Steven Moreland103424e2021-06-02 18:16:19 +0000796 switch (transaction->code) {
797 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
798 replyStatus = reply.writeInt32(session->getMaxThreads());
799 break;
800 }
801 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
802 // for client connections, this should always report the value
Steven Moreland01a6bad2021-06-11 00:59:20 +0000803 // originally returned from the server, so this is asserting
804 // that it exists
Steven Moreland826367f2021-09-10 14:05:31 -0700805 replyStatus = reply.writeByteVector(session->mId);
Steven Moreland103424e2021-06-02 18:16:19 +0000806 break;
807 }
808 default: {
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000809 sp<RpcServer> server = session->server();
Steven Moreland103424e2021-06-02 18:16:19 +0000810 if (server) {
811 switch (transaction->code) {
812 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
813 replyStatus = reply.writeStrongBinder(server->getRootObject());
814 break;
815 }
816 default: {
817 replyStatus = UNKNOWN_TRANSACTION;
818 }
819 }
820 } else {
821 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000822 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000823 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000824 }
825 }
826 }
827
Steven Morelandc7d40132021-06-10 03:42:11 +0000828 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000829 if (replyStatus != OK) {
830 ALOGW("Oneway call failed with error: %d", replyStatus);
831 }
832
Steven Moreland5623d1a2021-09-10 15:45:34 -0700833 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
834 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000835
836 // Check to see if there is another asynchronous transaction to process.
837 // This behavior differs from binder behavior, since in the binder
838 // driver, asynchronous transactions will be processed after existing
839 // pending binder transactions on the queue. The downside of this is
840 // that asynchronous transactions can be drowned out by synchronous
841 // transactions. However, we have no easy way to queue these
842 // transactions after the synchronous transactions we may want to read
843 // from the wire. So, in socket binder here, we have the opposite
844 // downside: asynchronous transactions may drown out synchronous
845 // transactions.
846 {
847 std::unique_lock<std::mutex> _l(mNodeMutex);
848 auto it = mNodeForAddress.find(addr);
849 // last refcount dropped after this transaction happened
850 if (it == mNodeForAddress.end()) return OK;
851
Steven Morelandc9d7b532021-06-04 20:57:41 +0000852 if (!nodeProgressAsyncNumber(&it->second)) {
853 _l.unlock();
854 (void)session->shutdownAndWait(false);
855 return DEAD_OBJECT;
856 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000857
858 if (it->second.asyncTodo.size() == 0) return OK;
859 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700860 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
861 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000862
863 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000864 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000865 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000866 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
867
Steven Morelandada72bd2021-06-09 23:29:13 +0000868 // reset up arguments
869 transactionData = std::move(todo.data);
870 targetRef = std::move(todo.ref);
Steven Morelandf5174272021-05-25 00:39:28 +0000871
Steven Moreland5553ac42020-11-11 02:14:45 +0000872 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000873 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000874 }
875 }
876 return OK;
877 }
878
Steven Moreland77c30112021-06-02 20:45:46 +0000879 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
880 sizeof(RpcWireReply) <
881 reply.dataSize(),
882 "Too much data for reply %zu", reply.dataSize());
883
884 RpcWireHeader cmdReply{
885 .command = RPC_COMMAND_REPLY,
886 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
887 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000888 RpcWireReply rpcReply{
889 .status = replyStatus,
890 };
891
Steven Moreland77c30112021-06-02 20:45:46 +0000892 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000893 if (!replyData.valid()) {
894 return NO_MEMORY;
895 }
Steven Moreland77c30112021-06-02 20:45:46 +0000896 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
897 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
898 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
899 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000900
Steven Moreland5ae62562021-06-10 03:21:42 +0000901 return rpcSend(connection, session, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000902}
903
Steven Moreland5ae62562021-06-10 03:21:42 +0000904status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
905 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000906 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
907
Steven Morelanddbe71832021-05-12 23:31:00 +0000908 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000909 if (!commandData.valid()) {
910 return NO_MEMORY;
911 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000912 if (status_t status =
Steven Moreland5ae62562021-06-10 03:21:42 +0000913 rpcRec(connection, session, "dec ref body", commandData.data(), commandData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000914 status != OK)
915 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000916
Steven Moreland5623d1a2021-09-10 15:45:34 -0700917 if (command.bodySize != sizeof(RpcWireAddress)) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000918 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
919 sizeof(RpcWireAddress), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000920 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000921 return BAD_VALUE;
922 }
923 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
924
Steven Moreland5623d1a2021-09-10 15:45:34 -0700925 uint64_t addr = RpcWireAddress::toRaw(*address);
926
Steven Moreland5553ac42020-11-11 02:14:45 +0000927 std::unique_lock<std::mutex> _l(mNodeMutex);
928 auto it = mNodeForAddress.find(addr);
929 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700930 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000931 return OK;
932 }
933
934 sp<IBinder> target = it->second.binder.promote();
935 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700936 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
937 ". Terminating!",
938 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000939 _l.unlock();
940 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000941 return BAD_VALUE;
942 }
943
944 if (it->second.timesSent == 0) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700945 ALOGE("No record of sending binder, but requested decStrong: %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000946 return OK;
947 }
948
Steven Moreland5623d1a2021-09-10 15:45:34 -0700949 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
950 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000951
Steven Moreland5553ac42020-11-11 02:14:45 +0000952 it->second.timesSent--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000953 sp<IBinder> tempHold = tryEraseNode(it);
954 _l.unlock();
955 tempHold = nullptr; // destructor may make binder calls on this session
956
957 return OK;
958}
959
Steven Moreland5623d1a2021-09-10 15:45:34 -0700960sp<IBinder> RpcState::tryEraseNode(std::map<uint64_t, BinderNode>::iterator& it) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000961 sp<IBinder> ref;
962
Steven Moreland5553ac42020-11-11 02:14:45 +0000963 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000964 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000965
966 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +0000967 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
968 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +0000969 mNodeForAddress.erase(it);
970 }
971 }
972
Steven Moreland31bde7a2021-06-04 00:57:36 +0000973 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +0000974}
975
Steven Morelandc9d7b532021-06-04 20:57:41 +0000976bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000977 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
978 // a single binder
979 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
980 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +0000981 return false;
982 }
983 node->asyncNumber++;
984 return true;
985}
986
Steven Moreland5553ac42020-11-11 02:14:45 +0000987} // namespace android