blob: 36c03c5097dae41b6e364b7e78e00b6d6a28305b [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) {
276 LOG_RPC_DETAIL("Sending %s on fd %d: %s", what, connection->fd.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
Steven Moreland798e0d12021-07-14 23:19:25 +0000285 if (status_t status = session->mShutdownTrigger->interruptableWriteFully(connection->fd.get(),
286 data, size);
287 status != OK) {
288 LOG_RPC_DETAIL("Failed to write %s (%zu bytes) on fd %d, error: %s", what, size,
289 connection->fd.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000290 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000291 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000292 }
293
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000294 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000295}
296
Steven Moreland5ae62562021-06-10 03:21:42 +0000297status_t RpcState::rpcRec(const sp<RpcSession::RpcConnection>& connection,
298 const sp<RpcSession>& session, const char* what, void* data,
299 size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000300 if (size > std::numeric_limits<ssize_t>::max()) {
301 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000302 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000303 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000304 }
305
Steven Moreland5ae62562021-06-10 03:21:42 +0000306 if (status_t status =
307 session->mShutdownTrigger->interruptableReadFully(connection->fd.get(), data, size);
Steven Morelandee3f4662021-05-22 01:07:33 +0000308 status != OK) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000309 LOG_RPC_DETAIL("Failed to read %s (%zu bytes) on fd %d, error: %s", what, size,
310 connection->fd.get(), statusToString(status).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000311 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000312 }
313
Steven Moreland5ae62562021-06-10 03:21:42 +0000314 LOG_RPC_DETAIL("Received %s on fd %d: %s", what, connection->fd.get(),
Steven Moreland62129012021-07-29 12:14:44 -0700315 android::base::HexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000316 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000317}
318
Steven Morelandbf57bce2021-07-26 15:26:12 -0700319status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
320 const sp<RpcSession>& session, uint32_t* version) {
321 RpcNewSessionResponse response;
322 if (status_t status =
323 rpcRec(connection, session, "new session response", &response, sizeof(response));
324 status != OK) {
325 return status;
326 }
327 *version = response.version;
328 return OK;
329}
330
Steven Moreland5ae62562021-06-10 03:21:42 +0000331status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
332 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000333 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000334 .msg = RPC_CONNECTION_INIT_OKAY,
335 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000336 return rpcSend(connection, session, "connection init", &init, sizeof(init));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000337}
338
Steven Moreland5ae62562021-06-10 03:21:42 +0000339status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
340 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000341 RpcOutgoingConnectionInit init;
Steven Moreland5ae62562021-06-10 03:21:42 +0000342 if (status_t status = rpcRec(connection, session, "connection init", &init, sizeof(init));
343 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000344 return status;
345
346 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
347 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
348 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
349 init.msg);
350 return BAD_VALUE;
351 }
352 return OK;
353}
354
Steven Moreland5ae62562021-06-10 03:21:42 +0000355sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
356 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000357 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000358 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000359 Parcel reply;
360
Steven Moreland5ae62562021-06-10 03:21:42 +0000361 status_t status = transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT,
362 data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000363 if (status != OK) {
364 ALOGE("Error getting root object: %s", statusToString(status).c_str());
365 return nullptr;
366 }
367
368 return reply.readStrongBinder();
369}
370
Steven Moreland5ae62562021-06-10 03:21:42 +0000371status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
372 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000373 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000374 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000375 Parcel reply;
376
Steven Moreland5ae62562021-06-10 03:21:42 +0000377 status_t status =
378 transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS,
379 data, session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000380 if (status != OK) {
381 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
382 return status;
383 }
384
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000385 int32_t maxThreads;
386 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000387 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000388 if (maxThreads <= 0) {
389 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000390 return BAD_VALUE;
391 }
392
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000393 *maxThreadsOut = maxThreads;
394 return OK;
395}
396
Steven Moreland5ae62562021-06-10 03:21:42 +0000397status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000398 const sp<RpcSession>& session, RpcAddress* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000399 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000400 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000401 Parcel reply;
402
Steven Moreland5ae62562021-06-10 03:21:42 +0000403 status_t status =
404 transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_SESSION_ID,
405 data, session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000406 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000407 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000408 return status;
409 }
410
Steven Moreland01a6bad2021-06-11 00:59:20 +0000411 return sessionIdOut->readFromParcel(reply);
Steven Morelandf137de92021-04-24 01:54:26 +0000412}
413
Steven Moreland5ae62562021-06-10 03:21:42 +0000414status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
415 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
416 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000417 if (!data.isForRpc()) {
418 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
419 return BAD_TYPE;
420 }
421
422 if (data.objectsCount() != 0) {
423 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
424 return BAD_TYPE;
425 }
426
427 RpcAddress address = RpcAddress::zero();
428 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
429
Steven Moreland5ae62562021-06-10 03:21:42 +0000430 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000431}
432
Steven Moreland5ae62562021-06-10 03:21:42 +0000433status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
434 const RpcAddress& address, uint32_t code, const Parcel& data,
435 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000436 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
437 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
438
Steven Moreland5553ac42020-11-11 02:14:45 +0000439 uint64_t asyncNumber = 0;
440
441 if (!address.isZero()) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000442 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000443 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
444 auto it = mNodeForAddress.find(address);
445 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
446 address.toString().c_str());
447
448 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000449 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000450 if (!nodeProgressAsyncNumber(&it->second)) {
451 _l.unlock();
452 (void)session->shutdownAndWait(false);
453 return DEAD_OBJECT;
454 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000455 }
456 }
457
Steven Moreland77c30112021-06-02 20:45:46 +0000458 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
459 sizeof(RpcWireTransaction) <
460 data.dataSize(),
461 "Too much data %zu", data.dataSize());
462
463 RpcWireHeader command{
464 .command = RPC_COMMAND_TRANSACT,
465 .bodySize = static_cast<uint32_t>(sizeof(RpcWireTransaction) + data.dataSize()),
466 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000467 RpcWireTransaction transaction{
468 .address = address.viewRawEmbedded(),
469 .code = code,
470 .flags = flags,
471 .asyncNumber = asyncNumber,
472 };
Steven Moreland77c30112021-06-02 20:45:46 +0000473 CommandData transactionData(sizeof(RpcWireHeader) + sizeof(RpcWireTransaction) +
474 data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000475 if (!transactionData.valid()) {
476 return NO_MEMORY;
477 }
478
Steven Moreland77c30112021-06-02 20:45:46 +0000479 memcpy(transactionData.data() + 0, &command, sizeof(RpcWireHeader));
480 memcpy(transactionData.data() + sizeof(RpcWireHeader), &transaction,
481 sizeof(RpcWireTransaction));
482 memcpy(transactionData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireTransaction), data.data(),
483 data.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000484
Steven Moreland5ae62562021-06-10 03:21:42 +0000485 if (status_t status = rpcSend(connection, session, "transaction", transactionData.data(),
486 transactionData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000487 status != OK)
Steven Morelanda5036f02021-06-08 02:26:57 +0000488 // TODO(b/167966510): need to undo onBinderLeaving - we know the
489 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000490 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000491
492 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000493 LOG_RPC_DETAIL("Oneway command, so no longer waiting on %d", connection->fd.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000494
495 // Do not wait on result.
496 // However, too many oneway calls may cause refcounts to build up and fill up the socket,
497 // so process those.
Steven Moreland5ae62562021-06-10 03:21:42 +0000498 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
Steven Moreland5553ac42020-11-11 02:14:45 +0000499 }
500
501 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
502
Steven Moreland5ae62562021-06-10 03:21:42 +0000503 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000504}
505
Steven Moreland438cce82021-04-02 18:04:08 +0000506static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
507 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000508 (void)p;
509 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
510 (void)dataSize;
511 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Yifan Hong239a2ca2021-06-24 16:05:16 -0700512 LOG_ALWAYS_FATAL_IF(objectsCount != 0, "%zu objects remaining", objectsCount);
Steven Moreland5553ac42020-11-11 02:14:45 +0000513}
514
Steven Moreland5ae62562021-06-10 03:21:42 +0000515status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
516 const sp<RpcSession>& session, Parcel* reply) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000517 RpcWireHeader command;
518 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000519 if (status_t status =
520 rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000521 status != OK)
522 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000523
524 if (command.command == RPC_COMMAND_REPLY) break;
525
Steven Moreland19fc9f72021-06-10 03:57:30 +0000526 if (status_t status = processCommand(connection, session, command, CommandType::ANY);
Steven Moreland52eee942021-06-03 00:59:28 +0000527 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000528 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000529 }
530
Steven Morelanddbe71832021-05-12 23:31:00 +0000531 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000532 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000533
Steven Moreland5ae62562021-06-10 03:21:42 +0000534 if (status_t status = rpcRec(connection, session, "reply body", data.data(), command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000535 status != OK)
536 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000537
538 if (command.bodySize < sizeof(RpcWireReply)) {
539 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
540 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000541 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000542 return BAD_VALUE;
543 }
Steven Morelande8393342021-05-05 23:27:53 +0000544 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000545 if (rpcReply->status != OK) return rpcReply->status;
546
Steven Morelande8393342021-05-05 23:27:53 +0000547 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000548 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000549 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000550
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000551 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000552
553 return OK;
554}
555
Steven Moreland5ae62562021-06-10 03:21:42 +0000556status_t RpcState::sendDecStrong(const sp<RpcSession::RpcConnection>& connection,
557 const sp<RpcSession>& session, const RpcAddress& addr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000558 {
559 std::lock_guard<std::mutex> _l(mNodeMutex);
560 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
561 auto it = mNodeForAddress.find(addr);
562 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
563 addr.toString().c_str());
564 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
565 addr.toString().c_str());
566
567 it->second.timesRecd--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000568 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
569 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000570 }
571
572 RpcWireHeader cmd = {
573 .command = RPC_COMMAND_DEC_STRONG,
574 .bodySize = sizeof(RpcWireAddress),
575 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000576 if (status_t status = rpcSend(connection, session, "dec ref header", &cmd, sizeof(cmd));
577 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000578 return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000579 if (status_t status = rpcSend(connection, session, "dec ref body", &addr.viewRawEmbedded(),
Steven Morelandc9d7b532021-06-04 20:57:41 +0000580 sizeof(RpcWireAddress));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000581 status != OK)
582 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000583 return OK;
584}
585
Steven Moreland5ae62562021-06-10 03:21:42 +0000586status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
587 const sp<RpcSession>& session, CommandType type) {
588 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", connection->fd.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000589
590 RpcWireHeader command;
Steven Moreland5ae62562021-06-10 03:21:42 +0000591 if (status_t status = rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000592 status != OK)
593 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000594
Steven Moreland19fc9f72021-06-10 03:57:30 +0000595 return processCommand(connection, session, command, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000596}
597
Steven Moreland5ae62562021-06-10 03:21:42 +0000598status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
599 const sp<RpcSession>& session, CommandType type) {
Steven Moreland52eee942021-06-03 00:59:28 +0000600 uint8_t buf;
Steven Moreland5ae62562021-06-10 03:21:42 +0000601 while (0 < TEMP_FAILURE_RETRY(
602 recv(connection->fd.get(), &buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT))) {
603 status_t status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000604 if (status != OK) return status;
605 }
606 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000607}
608
Steven Moreland19fc9f72021-06-10 03:57:30 +0000609status_t RpcState::processCommand(const sp<RpcSession::RpcConnection>& connection,
610 const sp<RpcSession>& session, const RpcWireHeader& command,
611 CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000612 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
613 IPCThreadState::SpGuard spGuard{
614 .address = __builtin_frame_address(0),
615 .context = "processing binder RPC command",
616 };
617 const IPCThreadState::SpGuard* origGuard;
618 if (kernelBinderState != nullptr) {
619 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
620 }
621 ScopeGuard guardUnguard = [&]() {
622 if (kernelBinderState != nullptr) {
623 kernelBinderState->restoreGetCallingSpGuard(origGuard);
624 }
625 };
626
Steven Moreland5553ac42020-11-11 02:14:45 +0000627 switch (command.command) {
628 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000629 if (type != CommandType::ANY) return BAD_TYPE;
Steven Moreland5ae62562021-06-10 03:21:42 +0000630 return processTransact(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000631 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000632 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000633 }
634
635 // We should always know the version of the opposing side, and since the
636 // RPC-binder-level wire protocol is not self synchronizing, we have no way
637 // to understand where the current command ends and the next one begins. We
638 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000639 // to kill us, so ending the session for misbehaving client.
640 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000641 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000642 return DEAD_OBJECT;
643}
Steven Moreland5ae62562021-06-10 03:21:42 +0000644status_t RpcState::processTransact(const sp<RpcSession::RpcConnection>& connection,
645 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000646 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
647
Steven Morelanddbe71832021-05-12 23:31:00 +0000648 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000649 if (!transactionData.valid()) {
650 return NO_MEMORY;
651 }
Steven Moreland5ae62562021-06-10 03:21:42 +0000652 if (status_t status = rpcRec(connection, session, "transaction body", transactionData.data(),
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000653 transactionData.size());
654 status != OK)
655 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000656
Steven Moreland5ae62562021-06-10 03:21:42 +0000657 return processTransactInternal(connection, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000658}
659
Steven Moreland438cce82021-04-02 18:04:08 +0000660static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
661 const binder_size_t* objects, size_t objectsCount) {
662 (void)p;
663 (void)data;
664 (void)dataSize;
665 (void)objects;
666 (void)objectsCount;
667}
668
Steven Moreland5ae62562021-06-10 03:21:42 +0000669status_t RpcState::processTransactInternal(const sp<RpcSession::RpcConnection>& connection,
670 const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000671 CommandData transactionData) {
672 // for 'recursive' calls to this, we have already read and processed the
673 // binder from the transaction data and taken reference counts into account,
674 // so it is cached here.
675 sp<IBinder> targetRef;
676processTransactInternalTailCall:
677
Steven Moreland5553ac42020-11-11 02:14:45 +0000678 if (transactionData.size() < sizeof(RpcWireTransaction)) {
679 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
680 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000681 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000682 return BAD_VALUE;
683 }
684 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
685
686 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
687 // maybe add an RpcAddress 'view' if the type remains 'heavy'
688 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000689 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000690
691 status_t replyStatus = OK;
692 sp<IBinder> target;
693 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000694 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000695 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000696 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000697 target = targetRef;
698 }
699
Steven Moreland7227c8a2021-06-02 00:24:32 +0000700 if (replyStatus != OK) {
701 // do nothing
702 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000703 // This can happen if the binder is remote in this process, and
704 // another thread has called the last decStrong on this binder.
705 // However, for local binders, it indicates a misbehaving client
706 // (any binder which is being transacted on should be holding a
707 // strong ref count), so in either case, terminating the
708 // session.
709 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
710 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000711 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000712 replyStatus = BAD_VALUE;
713 } else if (target->localBinder() == nullptr) {
714 ALOGE("Unknown binder address or non-local binder, not address %s. Terminating!",
715 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000716 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000717 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000718 } else if (oneway) {
Steven Morelandd45be622021-06-04 02:19:37 +0000719 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000720 auto it = mNodeForAddress.find(addr);
721 if (it->second.binder.promote() != target) {
722 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000723 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000724 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000725 } else if (transaction->asyncNumber != it->second.asyncNumber) {
726 // we need to process some other asynchronous transaction
727 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000728 it->second.asyncTodo.push(BinderNode::AsyncTodo{
729 .ref = target,
730 .data = std::move(transactionData),
731 .asyncNumber = transaction->asyncNumber,
732 });
Steven Morelandd45be622021-06-04 02:19:37 +0000733
734 size_t numPending = it->second.asyncTodo.size();
735 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s (%zu pending)",
736 transaction->asyncNumber, addr.toString().c_str(), numPending);
737
738 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
739 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
740 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
741
742 if (numPending >= kArbitraryOnewayCallWarnLevel) {
743 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
744 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
745 _l.unlock();
746 (void)session->shutdownAndWait(false);
747 return FAILED_TRANSACTION;
748 }
749
750 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
751 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
752 target.get(), numPending);
753 }
754 }
Steven Morelandf5174272021-05-25 00:39:28 +0000755 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000756 }
757 }
758 }
759
Steven Moreland5553ac42020-11-11 02:14:45 +0000760 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000761 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000762
763 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000764 Parcel data;
765 // transaction->data is owned by this function. Parcel borrows this data and
766 // only holds onto it for the duration of this function call. Parcel will be
767 // deleted before the 'transactionData' object.
768 data.ipcSetDataReference(transaction->data,
769 transactionData.size() - offsetof(RpcWireTransaction, data),
770 nullptr /*object*/, 0 /*objectCount*/,
771 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000772 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000773
Steven Moreland5553ac42020-11-11 02:14:45 +0000774 if (target) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000775 bool origAllowNested = connection->allowNested;
776 connection->allowNested = !oneway;
777
Steven Moreland5553ac42020-11-11 02:14:45 +0000778 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000779
780 connection->allowNested = origAllowNested;
Steven Moreland5553ac42020-11-11 02:14:45 +0000781 } else {
782 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000783
Steven Moreland103424e2021-06-02 18:16:19 +0000784 switch (transaction->code) {
785 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
786 replyStatus = reply.writeInt32(session->getMaxThreads());
787 break;
788 }
789 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
790 // for client connections, this should always report the value
Steven Moreland01a6bad2021-06-11 00:59:20 +0000791 // originally returned from the server, so this is asserting
792 // that it exists
793 replyStatus = session->mId.value().writeToParcel(&reply);
Steven Moreland103424e2021-06-02 18:16:19 +0000794 break;
795 }
796 default: {
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000797 sp<RpcServer> server = session->server();
Steven Moreland103424e2021-06-02 18:16:19 +0000798 if (server) {
799 switch (transaction->code) {
800 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
801 replyStatus = reply.writeStrongBinder(server->getRootObject());
802 break;
803 }
804 default: {
805 replyStatus = UNKNOWN_TRANSACTION;
806 }
807 }
808 } else {
809 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000810 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000811 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000812 }
813 }
814 }
815
Steven Morelandc7d40132021-06-10 03:42:11 +0000816 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000817 if (replyStatus != OK) {
818 ALOGW("Oneway call failed with error: %d", replyStatus);
819 }
820
821 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
822 addr.toString().c_str());
823
824 // Check to see if there is another asynchronous transaction to process.
825 // This behavior differs from binder behavior, since in the binder
826 // driver, asynchronous transactions will be processed after existing
827 // pending binder transactions on the queue. The downside of this is
828 // that asynchronous transactions can be drowned out by synchronous
829 // transactions. However, we have no easy way to queue these
830 // transactions after the synchronous transactions we may want to read
831 // from the wire. So, in socket binder here, we have the opposite
832 // downside: asynchronous transactions may drown out synchronous
833 // transactions.
834 {
835 std::unique_lock<std::mutex> _l(mNodeMutex);
836 auto it = mNodeForAddress.find(addr);
837 // last refcount dropped after this transaction happened
838 if (it == mNodeForAddress.end()) return OK;
839
Steven Morelandc9d7b532021-06-04 20:57:41 +0000840 if (!nodeProgressAsyncNumber(&it->second)) {
841 _l.unlock();
842 (void)session->shutdownAndWait(false);
843 return DEAD_OBJECT;
844 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000845
846 if (it->second.asyncTodo.size() == 0) return OK;
847 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
848 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
849 it->second.asyncNumber, addr.toString().c_str());
850
851 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000852 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000853 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000854 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
855
Steven Morelandada72bd2021-06-09 23:29:13 +0000856 // reset up arguments
857 transactionData = std::move(todo.data);
858 targetRef = std::move(todo.ref);
Steven Morelandf5174272021-05-25 00:39:28 +0000859
Steven Moreland5553ac42020-11-11 02:14:45 +0000860 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000861 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000862 }
863 }
864 return OK;
865 }
866
Steven Moreland77c30112021-06-02 20:45:46 +0000867 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
868 sizeof(RpcWireReply) <
869 reply.dataSize(),
870 "Too much data for reply %zu", reply.dataSize());
871
872 RpcWireHeader cmdReply{
873 .command = RPC_COMMAND_REPLY,
874 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
875 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000876 RpcWireReply rpcReply{
877 .status = replyStatus,
878 };
879
Steven Moreland77c30112021-06-02 20:45:46 +0000880 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000881 if (!replyData.valid()) {
882 return NO_MEMORY;
883 }
Steven Moreland77c30112021-06-02 20:45:46 +0000884 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
885 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
886 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
887 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000888
Steven Moreland5ae62562021-06-10 03:21:42 +0000889 return rpcSend(connection, session, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000890}
891
Steven Moreland5ae62562021-06-10 03:21:42 +0000892status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
893 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000894 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
895
Steven Morelanddbe71832021-05-12 23:31:00 +0000896 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000897 if (!commandData.valid()) {
898 return NO_MEMORY;
899 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000900 if (status_t status =
Steven Moreland5ae62562021-06-10 03:21:42 +0000901 rpcRec(connection, session, "dec ref body", commandData.data(), commandData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000902 status != OK)
903 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000904
905 if (command.bodySize < sizeof(RpcWireAddress)) {
906 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
907 sizeof(RpcWireAddress), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000908 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000909 return BAD_VALUE;
910 }
911 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
912
913 // TODO(b/182939933): heap allocation just for lookup
914 auto addr = RpcAddress::fromRawEmbedded(address);
915 std::unique_lock<std::mutex> _l(mNodeMutex);
916 auto it = mNodeForAddress.find(addr);
917 if (it == mNodeForAddress.end()) {
918 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000919 return OK;
920 }
921
922 sp<IBinder> target = it->second.binder.promote();
923 if (target == nullptr) {
924 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
925 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000926 _l.unlock();
927 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000928 return BAD_VALUE;
929 }
930
931 if (it->second.timesSent == 0) {
932 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
933 return OK;
934 }
935
936 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
937 addr.toString().c_str());
938
Steven Moreland5553ac42020-11-11 02:14:45 +0000939 it->second.timesSent--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000940 sp<IBinder> tempHold = tryEraseNode(it);
941 _l.unlock();
942 tempHold = nullptr; // destructor may make binder calls on this session
943
944 return OK;
945}
946
947sp<IBinder> RpcState::tryEraseNode(std::map<RpcAddress, BinderNode>::iterator& it) {
948 sp<IBinder> ref;
949
Steven Moreland5553ac42020-11-11 02:14:45 +0000950 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000951 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000952
953 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +0000954 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
955 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +0000956 mNodeForAddress.erase(it);
957 }
958 }
959
Steven Moreland31bde7a2021-06-04 00:57:36 +0000960 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +0000961}
962
Steven Morelandc9d7b532021-06-04 20:57:41 +0000963bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000964 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
965 // a single binder
966 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
967 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +0000968 return false;
969 }
970 node->asyncNumber++;
971 return true;
972}
973
Steven Moreland5553ac42020-11-11 02:14:45 +0000974} // namespace android