blob: f181a7bbd029334e8d8004d3701bba240127e83a [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 Moreland5553ac42020-11-11 02:14:45 +000055 RpcAddress* outAddress) {
56 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) {
87 const RpcAddress& actualAddr =
88 binder->remoteBinder()->getPrivateAccessorForId().rpcAddress();
89 // TODO(b/182939933): this is only checking integrity of data structure
90 // a different data structure doesn't need this
91 LOG_ALWAYS_FATAL_IF(addr < actualAddr, "Address mismatch");
92 LOG_ALWAYS_FATAL_IF(actualAddr < addr, "Address mismatch");
93 }
94 node.timesSent++;
95 node.sentRef = binder; // might already be set
96 *outAddress = addr;
97 return OK;
98 }
99 }
100 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
101
Steven Moreland91538242021-06-10 23:35:35 +0000102 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +0000103
Steven Moreland91538242021-06-10 23:35:35 +0000104 for (size_t tries = 0; tries < 5; tries++) {
105 auto&& [it, inserted] = mNodeForAddress.insert({RpcAddress::random(forServer),
106 BinderNode{
107 .binder = binder,
108 .timesSent = 1,
109 .sentRef = binder,
110 }});
111 if (inserted) {
112 *outAddress = it->first;
113 return OK;
114 }
115
116 // well, we don't have visibility into the header here, but still
117 static_assert(sizeof(RpcWireAddress) == 40, "this log needs updating");
118 ALOGW("2**256 is 1e77. If you see this log, you probably have some entropy issue, or maybe "
119 "you witness something incredible!");
120 }
121
122 ALOGE("Unable to create an address in order to send out %p", binder.get());
123 return WOULD_BLOCK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000124}
125
Steven Moreland7227c8a2021-06-02 00:24:32 +0000126status_t RpcState::onBinderEntering(const sp<RpcSession>& session, const RpcAddress& address,
127 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000128 // ensure that: if we want to use addresses for something else in the future (for
129 // instance, allowing transitive binder sends), that we don't accidentally
130 // send those addresses to old server. Accidentally ignoring this in that
131 // case and considering the binder to be recognized could cause this
132 // process to accidentally proxy transactions for that binder. Of course,
133 // if we communicate with a binder, it could always be proxying
134 // information. However, we want to make sure that isn't done on accident
135 // by a client.
136 if (!address.isRecognizedType()) {
137 ALOGE("Address is of an unknown type, rejecting: %s", address.toString().c_str());
138 return BAD_VALUE;
139 }
140
Steven Moreland5553ac42020-11-11 02:14:45 +0000141 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000142 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000143
144 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000145 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000146
147 // implicitly have strong RPC refcount, since we received this binder
148 it->second.timesRecd++;
149
150 _l.unlock();
151
152 // We have timesRecd RPC refcounts, but we only need to hold on to one
153 // when we keep the object. All additional dec strongs are sent
154 // immediately, we wait to send the last one in BpBinder::onLastDecStrong.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000155 (void)session->sendDecStrong(address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000156
Steven Moreland7227c8a2021-06-02 00:24:32 +0000157 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000158 }
159
Steven Moreland91538242021-06-10 23:35:35 +0000160 // we don't know about this binder, so the other side of the connection
161 // should have created it.
162 if (address.isForServer() == !!session->server()) {
163 ALOGE("Server received unrecognized address which we should own the creation of %s.",
164 address.toString().c_str());
165 return BAD_VALUE;
166 }
167
Steven Moreland5553ac42020-11-11 02:14:45 +0000168 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
169 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
170
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000171 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000172 // device global binders in the RPC world).
Steven Moreland7227c8a2021-06-02 00:24:32 +0000173 it->second.binder = *out = BpBinder::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000174 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000175 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000176}
177
178size_t RpcState::countBinders() {
179 std::lock_guard<std::mutex> _l(mNodeMutex);
180 return mNodeForAddress.size();
181}
182
183void RpcState::dump() {
184 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000185 dumpLocked();
186}
187
Steven Morelandc9d7b532021-06-04 20:57:41 +0000188void RpcState::clear() {
Steven Moreland583a14a2021-06-04 02:04:58 +0000189 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000190
191 if (mTerminated) {
192 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
193 "New state should be impossible after terminating!");
194 return;
195 }
196
197 if (SHOULD_LOG_RPC_DETAIL) {
198 ALOGE("RpcState::clear()");
199 dumpLocked();
200 }
201
202 // if the destructor of a binder object makes another RPC call, then calling
203 // decStrong could deadlock. So, we must hold onto these binders until
204 // mNodeMutex is no longer taken.
205 std::vector<sp<IBinder>> tempHoldBinder;
206
207 mTerminated = true;
208 for (auto& [address, node] : mNodeForAddress) {
209 sp<IBinder> binder = node.binder.promote();
210 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
211
212 if (node.sentRef != nullptr) {
213 tempHoldBinder.push_back(node.sentRef);
214 }
215 }
216
217 mNodeForAddress.clear();
218
219 _l.unlock();
220 tempHoldBinder.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000221}
222
223void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000224 ALOGE("DUMP OF RpcState %p", this);
225 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
226 for (const auto& [address, node] : mNodeForAddress) {
227 sp<IBinder> binder = node.binder.promote();
228
229 const char* desc;
230 if (binder) {
231 if (binder->remoteBinder()) {
232 if (binder->remoteBinder()->isRpcBinder()) {
233 desc = "(rpc binder proxy)";
234 } else {
235 desc = "(binder proxy)";
236 }
237 } else {
238 desc = "(local binder)";
239 }
240 } else {
241 desc = "(null)";
242 }
243
244 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a:%s type:%s",
245 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address.toString().c_str(),
246 desc);
247 }
248 ALOGE("END DUMP OF RpcState");
249}
250
Steven Moreland5553ac42020-11-11 02:14:45 +0000251
Steven Morelanddbe71832021-05-12 23:31:00 +0000252RpcState::CommandData::CommandData(size_t size) : mSize(size) {
253 // The maximum size for regular binder is 1MB for all concurrent
254 // transactions. A very small proportion of transactions are even
255 // larger than a page, but we need to avoid allocating too much
256 // data on behalf of an arbitrary client, or we could risk being in
257 // a position where a single additional allocation could run out of
258 // memory.
259 //
260 // Note, this limit may not reflect the total amount of data allocated for a
261 // transaction (in some cases, additional fixed size amounts are added),
262 // though for rough consistency, we should avoid cases where this data type
263 // is used for multiple dynamic allocations for a single transaction.
264 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
265 if (size == 0) return;
266 if (size > kMaxTransactionAllocation) {
267 ALOGW("Transaction requested too much data allocation %zu", size);
268 return;
269 }
270 mData.reset(new (std::nothrow) uint8_t[size]);
271}
272
Steven Moreland5ae62562021-06-10 03:21:42 +0000273status_t RpcState::rpcSend(const sp<RpcSession::RpcConnection>& connection,
274 const sp<RpcSession>& session, const char* what, const void* data,
275 size_t size) {
Yifan Hong702115c2021-06-24 15:39:18 -0700276 LOG_RPC_DETAIL("Sending %s on RpcTransport %p: %s", what, connection->rpcTransport.get(),
Steven Moreland62129012021-07-29 12:14:44 -0700277 android::base::HexString(data, size).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000278
279 if (size > std::numeric_limits<ssize_t>::max()) {
280 ALOGE("Cannot send %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000281 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000282 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000283 }
284
Yifan Hong702115c2021-06-24 15:39:18 -0700285 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700286 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
287 data, size);
Steven Moreland798e0d12021-07-14 23:19:25 +0000288 status != OK) {
Yifan Hong702115c2021-06-24 15:39:18 -0700289 LOG_RPC_DETAIL("Failed to write %s (%zu bytes) on RpcTransport %p, error: %s", what, size,
290 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000291 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000292 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000293 }
294
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000295 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000296}
297
Steven Moreland5ae62562021-06-10 03:21:42 +0000298status_t RpcState::rpcRec(const sp<RpcSession::RpcConnection>& connection,
299 const sp<RpcSession>& session, const char* what, void* data,
300 size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000301 if (size > std::numeric_limits<ssize_t>::max()) {
302 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000303 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000304 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000305 }
306
Steven Moreland5ae62562021-06-10 03:21:42 +0000307 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700308 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
309 data, size);
Steven Morelandee3f4662021-05-22 01:07:33 +0000310 status != OK) {
Yifan Hong702115c2021-06-24 15:39:18 -0700311 LOG_RPC_DETAIL("Failed to read %s (%zu bytes) on RpcTransport %p, error: %s", what, size,
312 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000313 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000314 }
315
Yifan Hong702115c2021-06-24 15:39:18 -0700316 LOG_RPC_DETAIL("Received %s on RpcTransport %p: %s", what, connection->rpcTransport.get(),
Steven Moreland62129012021-07-29 12:14:44 -0700317 android::base::HexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000318 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000319}
320
Steven Morelandbf57bce2021-07-26 15:26:12 -0700321status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
322 const sp<RpcSession>& session, uint32_t* version) {
323 RpcNewSessionResponse response;
324 if (status_t status =
325 rpcRec(connection, session, "new session response", &response, sizeof(response));
326 status != OK) {
327 return status;
328 }
329 *version = response.version;
330 return OK;
331}
332
Steven Moreland5ae62562021-06-10 03:21:42 +0000333status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
334 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000335 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000336 .msg = RPC_CONNECTION_INIT_OKAY,
337 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000338 return rpcSend(connection, session, "connection init", &init, sizeof(init));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000339}
340
Steven Moreland5ae62562021-06-10 03:21:42 +0000341status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
342 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000343 RpcOutgoingConnectionInit init;
Steven Moreland5ae62562021-06-10 03:21:42 +0000344 if (status_t status = rpcRec(connection, session, "connection init", &init, sizeof(init));
345 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000346 return status;
347
348 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
349 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
350 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
351 init.msg);
352 return BAD_VALUE;
353 }
354 return OK;
355}
356
Steven Moreland5ae62562021-06-10 03:21:42 +0000357sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
358 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000359 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000360 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000361 Parcel reply;
362
Steven Moreland5ae62562021-06-10 03:21:42 +0000363 status_t status = transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT,
364 data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000365 if (status != OK) {
366 ALOGE("Error getting root object: %s", statusToString(status).c_str());
367 return nullptr;
368 }
369
370 return reply.readStrongBinder();
371}
372
Steven Moreland5ae62562021-06-10 03:21:42 +0000373status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
374 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000375 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000376 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000377 Parcel reply;
378
Steven Moreland5ae62562021-06-10 03:21:42 +0000379 status_t status =
380 transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS,
381 data, session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000382 if (status != OK) {
383 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
384 return status;
385 }
386
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000387 int32_t maxThreads;
388 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000389 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000390 if (maxThreads <= 0) {
391 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000392 return BAD_VALUE;
393 }
394
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000395 *maxThreadsOut = maxThreads;
396 return OK;
397}
398
Steven Moreland5ae62562021-06-10 03:21:42 +0000399status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700400 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000401 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000402 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000403 Parcel reply;
404
Steven Moreland5ae62562021-06-10 03:21:42 +0000405 status_t status =
406 transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_SESSION_ID,
407 data, session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000408 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000410 return status;
411 }
412
Steven Moreland826367f2021-09-10 14:05:31 -0700413 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000414}
415
Steven Moreland5ae62562021-06-10 03:21:42 +0000416status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
417 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
418 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000419 if (!data.isForRpc()) {
420 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
421 return BAD_TYPE;
422 }
423
424 if (data.objectsCount() != 0) {
425 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
426 return BAD_TYPE;
427 }
428
429 RpcAddress address = RpcAddress::zero();
430 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
431
Steven Moreland5ae62562021-06-10 03:21:42 +0000432 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000433}
434
Steven Moreland5ae62562021-06-10 03:21:42 +0000435status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
436 const RpcAddress& address, uint32_t code, const Parcel& data,
437 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000438 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
439 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
440
Steven Moreland5553ac42020-11-11 02:14:45 +0000441 uint64_t asyncNumber = 0;
442
443 if (!address.isZero()) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000444 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000445 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
446 auto it = mNodeForAddress.find(address);
447 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
448 address.toString().c_str());
449
450 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000451 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000452 if (!nodeProgressAsyncNumber(&it->second)) {
453 _l.unlock();
454 (void)session->shutdownAndWait(false);
455 return DEAD_OBJECT;
456 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000457 }
458 }
459
Steven Moreland77c30112021-06-02 20:45:46 +0000460 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
461 sizeof(RpcWireTransaction) <
462 data.dataSize(),
463 "Too much data %zu", data.dataSize());
464
465 RpcWireHeader command{
466 .command = RPC_COMMAND_TRANSACT,
467 .bodySize = static_cast<uint32_t>(sizeof(RpcWireTransaction) + data.dataSize()),
468 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000469 RpcWireTransaction transaction{
470 .address = address.viewRawEmbedded(),
471 .code = code,
472 .flags = flags,
473 .asyncNumber = asyncNumber,
474 };
Steven Moreland77c30112021-06-02 20:45:46 +0000475 CommandData transactionData(sizeof(RpcWireHeader) + sizeof(RpcWireTransaction) +
476 data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000477 if (!transactionData.valid()) {
478 return NO_MEMORY;
479 }
480
Steven Moreland77c30112021-06-02 20:45:46 +0000481 memcpy(transactionData.data() + 0, &command, sizeof(RpcWireHeader));
482 memcpy(transactionData.data() + sizeof(RpcWireHeader), &transaction,
483 sizeof(RpcWireTransaction));
484 memcpy(transactionData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireTransaction), data.data(),
485 data.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000486
Steven Moreland5ae62562021-06-10 03:21:42 +0000487 if (status_t status = rpcSend(connection, session, "transaction", transactionData.data(),
488 transactionData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000489 status != OK)
Steven Morelanda5036f02021-06-08 02:26:57 +0000490 // TODO(b/167966510): need to undo onBinderLeaving - we know the
491 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000492 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000493
494 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700495 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
496 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000497
498 // Do not wait on result.
499 // However, too many oneway calls may cause refcounts to build up and fill up the socket,
500 // so process those.
Steven Moreland5ae62562021-06-10 03:21:42 +0000501 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
Steven Moreland5553ac42020-11-11 02:14:45 +0000502 }
503
504 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
505
Steven Moreland5ae62562021-06-10 03:21:42 +0000506 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000507}
508
Steven Moreland438cce82021-04-02 18:04:08 +0000509static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
510 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000511 (void)p;
512 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
513 (void)dataSize;
514 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Yifan Hong239a2ca2021-06-24 16:05:16 -0700515 LOG_ALWAYS_FATAL_IF(objectsCount != 0, "%zu objects remaining", objectsCount);
Steven Moreland5553ac42020-11-11 02:14:45 +0000516}
517
Steven Moreland5ae62562021-06-10 03:21:42 +0000518status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
519 const sp<RpcSession>& session, Parcel* reply) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000520 RpcWireHeader command;
521 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000522 if (status_t status =
523 rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000524 status != OK)
525 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000526
527 if (command.command == RPC_COMMAND_REPLY) break;
528
Steven Moreland19fc9f72021-06-10 03:57:30 +0000529 if (status_t status = processCommand(connection, session, command, CommandType::ANY);
Steven Moreland52eee942021-06-03 00:59:28 +0000530 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000531 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000532 }
533
Steven Morelanddbe71832021-05-12 23:31:00 +0000534 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000535 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000536
Steven Moreland5ae62562021-06-10 03:21:42 +0000537 if (status_t status = rpcRec(connection, session, "reply body", data.data(), command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000538 status != OK)
539 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000540
541 if (command.bodySize < sizeof(RpcWireReply)) {
542 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
543 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000544 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000545 return BAD_VALUE;
546 }
Steven Morelande8393342021-05-05 23:27:53 +0000547 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000548 if (rpcReply->status != OK) return rpcReply->status;
549
Steven Morelande8393342021-05-05 23:27:53 +0000550 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000551 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000552 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000553
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000554 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000555
556 return OK;
557}
558
Steven Moreland5ae62562021-06-10 03:21:42 +0000559status_t RpcState::sendDecStrong(const sp<RpcSession::RpcConnection>& connection,
560 const sp<RpcSession>& session, const RpcAddress& addr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000561 {
562 std::lock_guard<std::mutex> _l(mNodeMutex);
563 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
564 auto it = mNodeForAddress.find(addr);
565 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
566 addr.toString().c_str());
567 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
568 addr.toString().c_str());
569
570 it->second.timesRecd--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000571 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
572 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000573 }
574
575 RpcWireHeader cmd = {
576 .command = RPC_COMMAND_DEC_STRONG,
577 .bodySize = sizeof(RpcWireAddress),
578 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000579 if (status_t status = rpcSend(connection, session, "dec ref header", &cmd, sizeof(cmd));
580 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000581 return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000582 if (status_t status = rpcSend(connection, session, "dec ref body", &addr.viewRawEmbedded(),
Steven Morelandc9d7b532021-06-04 20:57:41 +0000583 sizeof(RpcWireAddress));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000584 status != OK)
585 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000586 return OK;
587}
588
Steven Moreland5ae62562021-06-10 03:21:42 +0000589status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
590 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700591 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000592
593 RpcWireHeader command;
Steven Moreland5ae62562021-06-10 03:21:42 +0000594 if (status_t status = rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000595 status != OK)
596 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000597
Steven Moreland19fc9f72021-06-10 03:57:30 +0000598 return processCommand(connection, session, command, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000599}
600
Steven Moreland5ae62562021-06-10 03:21:42 +0000601status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
602 const sp<RpcSession>& session, CommandType type) {
Steven Moreland52eee942021-06-03 00:59:28 +0000603 uint8_t buf;
Yifan Hong218c4072021-08-04 14:59:10 -0700604 while (connection->rpcTransport->peek(&buf, sizeof(buf)).value_or(0) > 0) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000605 status_t status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000606 if (status != OK) return status;
607 }
608 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000609}
610
Steven Moreland19fc9f72021-06-10 03:57:30 +0000611status_t RpcState::processCommand(const sp<RpcSession::RpcConnection>& connection,
612 const sp<RpcSession>& session, const RpcWireHeader& command,
613 CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000614 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
615 IPCThreadState::SpGuard spGuard{
616 .address = __builtin_frame_address(0),
617 .context = "processing binder RPC command",
618 };
619 const IPCThreadState::SpGuard* origGuard;
620 if (kernelBinderState != nullptr) {
621 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
622 }
623 ScopeGuard guardUnguard = [&]() {
624 if (kernelBinderState != nullptr) {
625 kernelBinderState->restoreGetCallingSpGuard(origGuard);
626 }
627 };
628
Steven Moreland5553ac42020-11-11 02:14:45 +0000629 switch (command.command) {
630 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000631 if (type != CommandType::ANY) return BAD_TYPE;
Steven Moreland5ae62562021-06-10 03:21:42 +0000632 return processTransact(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000633 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000634 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000635 }
636
637 // We should always know the version of the opposing side, and since the
638 // RPC-binder-level wire protocol is not self synchronizing, we have no way
639 // to understand where the current command ends and the next one begins. We
640 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000641 // to kill us, so ending the session for misbehaving client.
642 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000643 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000644 return DEAD_OBJECT;
645}
Steven Moreland5ae62562021-06-10 03:21:42 +0000646status_t RpcState::processTransact(const sp<RpcSession::RpcConnection>& connection,
647 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000648 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
649
Steven Morelanddbe71832021-05-12 23:31:00 +0000650 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000651 if (!transactionData.valid()) {
652 return NO_MEMORY;
653 }
Steven Moreland5ae62562021-06-10 03:21:42 +0000654 if (status_t status = rpcRec(connection, session, "transaction body", transactionData.data(),
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000655 transactionData.size());
656 status != OK)
657 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000658
Steven Moreland5ae62562021-06-10 03:21:42 +0000659 return processTransactInternal(connection, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000660}
661
Steven Moreland438cce82021-04-02 18:04:08 +0000662static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
663 const binder_size_t* objects, size_t objectsCount) {
664 (void)p;
665 (void)data;
666 (void)dataSize;
667 (void)objects;
668 (void)objectsCount;
669}
670
Steven Moreland5ae62562021-06-10 03:21:42 +0000671status_t RpcState::processTransactInternal(const sp<RpcSession::RpcConnection>& connection,
672 const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000673 CommandData transactionData) {
674 // for 'recursive' calls to this, we have already read and processed the
675 // binder from the transaction data and taken reference counts into account,
676 // so it is cached here.
677 sp<IBinder> targetRef;
678processTransactInternalTailCall:
679
Steven Moreland5553ac42020-11-11 02:14:45 +0000680 if (transactionData.size() < sizeof(RpcWireTransaction)) {
681 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
682 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000683 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000684 return BAD_VALUE;
685 }
686 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
687
688 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
689 // maybe add an RpcAddress 'view' if the type remains 'heavy'
690 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000691 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000692
693 status_t replyStatus = OK;
694 sp<IBinder> target;
695 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000696 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000697 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000698 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000699 target = targetRef;
700 }
701
Steven Moreland7227c8a2021-06-02 00:24:32 +0000702 if (replyStatus != OK) {
703 // do nothing
704 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000705 // This can happen if the binder is remote in this process, and
706 // another thread has called the last decStrong on this binder.
707 // However, for local binders, it indicates a misbehaving client
708 // (any binder which is being transacted on should be holding a
709 // strong ref count), so in either case, terminating the
710 // session.
711 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
712 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000713 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000714 replyStatus = BAD_VALUE;
715 } else if (target->localBinder() == nullptr) {
716 ALOGE("Unknown binder address or non-local binder, not address %s. Terminating!",
717 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000718 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000719 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000720 } else if (oneway) {
Steven Morelandd45be622021-06-04 02:19:37 +0000721 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000722 auto it = mNodeForAddress.find(addr);
723 if (it->second.binder.promote() != target) {
724 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000725 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000726 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000727 } else if (transaction->asyncNumber != it->second.asyncNumber) {
728 // we need to process some other asynchronous transaction
729 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000730 it->second.asyncTodo.push(BinderNode::AsyncTodo{
731 .ref = target,
732 .data = std::move(transactionData),
733 .asyncNumber = transaction->asyncNumber,
734 });
Steven Morelandd45be622021-06-04 02:19:37 +0000735
736 size_t numPending = it->second.asyncTodo.size();
737 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s (%zu pending)",
738 transaction->asyncNumber, addr.toString().c_str(), numPending);
739
740 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
741 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
742 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
743
744 if (numPending >= kArbitraryOnewayCallWarnLevel) {
745 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
746 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
747 _l.unlock();
748 (void)session->shutdownAndWait(false);
749 return FAILED_TRANSACTION;
750 }
751
752 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
753 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
754 target.get(), numPending);
755 }
756 }
Steven Morelandf5174272021-05-25 00:39:28 +0000757 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000758 }
759 }
760 }
761
Steven Moreland5553ac42020-11-11 02:14:45 +0000762 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000763 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000764
765 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000766 Parcel data;
767 // transaction->data is owned by this function. Parcel borrows this data and
768 // only holds onto it for the duration of this function call. Parcel will be
769 // deleted before the 'transactionData' object.
770 data.ipcSetDataReference(transaction->data,
771 transactionData.size() - offsetof(RpcWireTransaction, data),
772 nullptr /*object*/, 0 /*objectCount*/,
773 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000774 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000775
Steven Moreland5553ac42020-11-11 02:14:45 +0000776 if (target) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000777 bool origAllowNested = connection->allowNested;
778 connection->allowNested = !oneway;
779
Steven Moreland5553ac42020-11-11 02:14:45 +0000780 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000781
782 connection->allowNested = origAllowNested;
Steven Moreland5553ac42020-11-11 02:14:45 +0000783 } else {
784 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000785
Steven Moreland103424e2021-06-02 18:16:19 +0000786 switch (transaction->code) {
787 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
788 replyStatus = reply.writeInt32(session->getMaxThreads());
789 break;
790 }
791 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
792 // for client connections, this should always report the value
Steven Moreland01a6bad2021-06-11 00:59:20 +0000793 // originally returned from the server, so this is asserting
794 // that it exists
Steven Moreland826367f2021-09-10 14:05:31 -0700795 replyStatus = reply.writeByteVector(session->mId);
Steven Moreland103424e2021-06-02 18:16:19 +0000796 break;
797 }
798 default: {
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000799 sp<RpcServer> server = session->server();
Steven Moreland103424e2021-06-02 18:16:19 +0000800 if (server) {
801 switch (transaction->code) {
802 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
803 replyStatus = reply.writeStrongBinder(server->getRootObject());
804 break;
805 }
806 default: {
807 replyStatus = UNKNOWN_TRANSACTION;
808 }
809 }
810 } else {
811 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000812 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000813 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000814 }
815 }
816 }
817
Steven Morelandc7d40132021-06-10 03:42:11 +0000818 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000819 if (replyStatus != OK) {
820 ALOGW("Oneway call failed with error: %d", replyStatus);
821 }
822
823 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
824 addr.toString().c_str());
825
826 // Check to see if there is another asynchronous transaction to process.
827 // This behavior differs from binder behavior, since in the binder
828 // driver, asynchronous transactions will be processed after existing
829 // pending binder transactions on the queue. The downside of this is
830 // that asynchronous transactions can be drowned out by synchronous
831 // transactions. However, we have no easy way to queue these
832 // transactions after the synchronous transactions we may want to read
833 // from the wire. So, in socket binder here, we have the opposite
834 // downside: asynchronous transactions may drown out synchronous
835 // transactions.
836 {
837 std::unique_lock<std::mutex> _l(mNodeMutex);
838 auto it = mNodeForAddress.find(addr);
839 // last refcount dropped after this transaction happened
840 if (it == mNodeForAddress.end()) return OK;
841
Steven Morelandc9d7b532021-06-04 20:57:41 +0000842 if (!nodeProgressAsyncNumber(&it->second)) {
843 _l.unlock();
844 (void)session->shutdownAndWait(false);
845 return DEAD_OBJECT;
846 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000847
848 if (it->second.asyncTodo.size() == 0) return OK;
849 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
850 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
851 it->second.asyncNumber, addr.toString().c_str());
852
853 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000854 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000855 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000856 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
857
Steven Morelandada72bd2021-06-09 23:29:13 +0000858 // reset up arguments
859 transactionData = std::move(todo.data);
860 targetRef = std::move(todo.ref);
Steven Morelandf5174272021-05-25 00:39:28 +0000861
Steven Moreland5553ac42020-11-11 02:14:45 +0000862 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000863 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000864 }
865 }
866 return OK;
867 }
868
Steven Moreland77c30112021-06-02 20:45:46 +0000869 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
870 sizeof(RpcWireReply) <
871 reply.dataSize(),
872 "Too much data for reply %zu", reply.dataSize());
873
874 RpcWireHeader cmdReply{
875 .command = RPC_COMMAND_REPLY,
876 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
877 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000878 RpcWireReply rpcReply{
879 .status = replyStatus,
880 };
881
Steven Moreland77c30112021-06-02 20:45:46 +0000882 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000883 if (!replyData.valid()) {
884 return NO_MEMORY;
885 }
Steven Moreland77c30112021-06-02 20:45:46 +0000886 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
887 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
888 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
889 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000890
Steven Moreland5ae62562021-06-10 03:21:42 +0000891 return rpcSend(connection, session, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000892}
893
Steven Moreland5ae62562021-06-10 03:21:42 +0000894status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
895 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000896 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
897
Steven Morelanddbe71832021-05-12 23:31:00 +0000898 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000899 if (!commandData.valid()) {
900 return NO_MEMORY;
901 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000902 if (status_t status =
Steven Moreland5ae62562021-06-10 03:21:42 +0000903 rpcRec(connection, session, "dec ref body", commandData.data(), commandData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000904 status != OK)
905 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000906
907 if (command.bodySize < sizeof(RpcWireAddress)) {
908 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
909 sizeof(RpcWireAddress), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000910 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000911 return BAD_VALUE;
912 }
913 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
914
915 // TODO(b/182939933): heap allocation just for lookup
916 auto addr = RpcAddress::fromRawEmbedded(address);
917 std::unique_lock<std::mutex> _l(mNodeMutex);
918 auto it = mNodeForAddress.find(addr);
919 if (it == mNodeForAddress.end()) {
920 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000921 return OK;
922 }
923
924 sp<IBinder> target = it->second.binder.promote();
925 if (target == nullptr) {
926 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
927 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000928 _l.unlock();
929 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000930 return BAD_VALUE;
931 }
932
933 if (it->second.timesSent == 0) {
934 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
935 return OK;
936 }
937
938 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
939 addr.toString().c_str());
940
Steven Moreland5553ac42020-11-11 02:14:45 +0000941 it->second.timesSent--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000942 sp<IBinder> tempHold = tryEraseNode(it);
943 _l.unlock();
944 tempHold = nullptr; // destructor may make binder calls on this session
945
946 return OK;
947}
948
949sp<IBinder> RpcState::tryEraseNode(std::map<RpcAddress, BinderNode>::iterator& it) {
950 sp<IBinder> ref;
951
Steven Moreland5553ac42020-11-11 02:14:45 +0000952 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000953 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000954
955 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +0000956 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
957 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +0000958 mNodeForAddress.erase(it);
959 }
960 }
961
Steven Moreland31bde7a2021-06-04 00:57:36 +0000962 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +0000963}
964
Steven Morelandc9d7b532021-06-04 20:57:41 +0000965bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000966 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
967 // a single binder
968 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
969 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +0000970 return false;
971 }
972 node->asyncNumber++;
973 return true;
974}
975
Steven Moreland5553ac42020-11-11 02:14:45 +0000976} // namespace android