blob: b5eaaa34138c78074fcdb77b576b756b8e1c21f5 [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 Morelandd7302072021-05-15 01:32:04 +000021#include <android-base/scopeguard.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000022#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000023#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000024#include <binder/RpcServer.h>
25
26#include "Debug.h"
27#include "RpcWireFormat.h"
28
Steven Morelandb8176792021-06-22 20:29:21 +000029#include <random>
30
Steven Moreland5553ac42020-11-11 02:14:45 +000031#include <inttypes.h>
32
33namespace android {
34
Steven Morelandd7302072021-05-15 01:32:04 +000035using base::ScopeGuard;
36
Steven Morelandb8176792021-06-22 20:29:21 +000037#ifdef RPC_FLAKE_PRONE
38void rpcMaybeWaitToFlake() {
39 static std::random_device r;
40 static std::mutex m;
41
42 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(),
277 hexString(data, size).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000278
Steven Morelandb8176792021-06-22 20:29:21 +0000279 MAYBE_WAIT_IN_FLAKE_MODE;
280
Steven Moreland5553ac42020-11-11 02:14:45 +0000281 if (size > std::numeric_limits<ssize_t>::max()) {
282 ALOGE("Cannot send %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000283 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000284 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000285 }
286
Steven Moreland5ae62562021-06-10 03:21:42 +0000287 ssize_t sent = TEMP_FAILURE_RETRY(send(connection->fd.get(), data, size, MSG_NOSIGNAL));
Steven Moreland5553ac42020-11-11 02:14:45 +0000288
289 if (sent < 0 || sent != static_cast<ssize_t>(size)) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000290 int savedErrno = errno;
Steven Morelandc12c9d92021-05-26 18:44:11 +0000291 LOG_RPC_DETAIL("Failed to send %s (sent %zd of %zu bytes) on fd %d, error: %s", what, sent,
Steven Moreland5ae62562021-06-10 03:21:42 +0000292 size, connection->fd.get(), strerror(savedErrno));
Steven Moreland5553ac42020-11-11 02:14:45 +0000293
Steven Morelandc9d7b532021-06-04 20:57:41 +0000294 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000295 return -savedErrno;
Steven Moreland5553ac42020-11-11 02:14:45 +0000296 }
297
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000298 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000299}
300
Steven Moreland5ae62562021-06-10 03:21:42 +0000301status_t RpcState::rpcRec(const sp<RpcSession::RpcConnection>& connection,
302 const sp<RpcSession>& session, const char* what, void* data,
303 size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000304 if (size > std::numeric_limits<ssize_t>::max()) {
305 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000306 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000307 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000308 }
309
Steven Moreland5ae62562021-06-10 03:21:42 +0000310 if (status_t status =
311 session->mShutdownTrigger->interruptableReadFully(connection->fd.get(), data, size);
Steven Morelandee3f4662021-05-22 01:07:33 +0000312 status != OK) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000313 LOG_RPC_DETAIL("Failed to read %s (%zu bytes) on fd %d, error: %s", what, size,
314 connection->fd.get(), statusToString(status).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000315 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000316 }
317
Steven Moreland5ae62562021-06-10 03:21:42 +0000318 LOG_RPC_DETAIL("Received %s on fd %d: %s", what, connection->fd.get(),
319 hexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000320 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000321}
322
Steven Moreland5ae62562021-06-10 03:21:42 +0000323status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
324 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000325 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000326 .msg = RPC_CONNECTION_INIT_OKAY,
327 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000328 return rpcSend(connection, session, "connection init", &init, sizeof(init));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000329}
330
Steven Moreland5ae62562021-06-10 03:21:42 +0000331status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
332 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000333 RpcOutgoingConnectionInit init;
Steven Moreland5ae62562021-06-10 03:21:42 +0000334 if (status_t status = rpcRec(connection, session, "connection init", &init, sizeof(init));
335 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000336 return status;
337
338 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
339 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
340 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
341 init.msg);
342 return BAD_VALUE;
343 }
344 return OK;
345}
346
Steven Moreland5ae62562021-06-10 03:21:42 +0000347sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
348 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000349 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000350 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000351 Parcel reply;
352
Steven Moreland5ae62562021-06-10 03:21:42 +0000353 status_t status = transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT,
354 data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000355 if (status != OK) {
356 ALOGE("Error getting root object: %s", statusToString(status).c_str());
357 return nullptr;
358 }
359
360 return reply.readStrongBinder();
361}
362
Steven Moreland5ae62562021-06-10 03:21:42 +0000363status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
364 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000365 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000366 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000367 Parcel reply;
368
Steven Moreland5ae62562021-06-10 03:21:42 +0000369 status_t status =
370 transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS,
371 data, session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000372 if (status != OK) {
373 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
374 return status;
375 }
376
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000377 int32_t maxThreads;
378 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000379 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000380 if (maxThreads <= 0) {
381 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000382 return BAD_VALUE;
383 }
384
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000385 *maxThreadsOut = maxThreads;
386 return OK;
387}
388
Steven Moreland5ae62562021-06-10 03:21:42 +0000389status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000390 const sp<RpcSession>& session, RpcAddress* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000391 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000392 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000393 Parcel reply;
394
Steven Moreland5ae62562021-06-10 03:21:42 +0000395 status_t status =
396 transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_SESSION_ID,
397 data, session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000398 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000399 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000400 return status;
401 }
402
Steven Moreland01a6bad2021-06-11 00:59:20 +0000403 return sessionIdOut->readFromParcel(reply);
Steven Morelandf137de92021-04-24 01:54:26 +0000404}
405
Steven Moreland5ae62562021-06-10 03:21:42 +0000406status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
407 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
408 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000409 if (!data.isForRpc()) {
410 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
411 return BAD_TYPE;
412 }
413
414 if (data.objectsCount() != 0) {
415 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
416 return BAD_TYPE;
417 }
418
419 RpcAddress address = RpcAddress::zero();
420 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
421
Steven Moreland5ae62562021-06-10 03:21:42 +0000422 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000423}
424
Steven Moreland5ae62562021-06-10 03:21:42 +0000425status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
426 const RpcAddress& address, uint32_t code, const Parcel& data,
427 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000428 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
429 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
430
Steven Moreland5553ac42020-11-11 02:14:45 +0000431 uint64_t asyncNumber = 0;
432
433 if (!address.isZero()) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000434 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000435 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
436 auto it = mNodeForAddress.find(address);
437 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
438 address.toString().c_str());
439
440 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000441 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000442 if (!nodeProgressAsyncNumber(&it->second)) {
443 _l.unlock();
444 (void)session->shutdownAndWait(false);
445 return DEAD_OBJECT;
446 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000447 }
448 }
449
Steven Moreland77c30112021-06-02 20:45:46 +0000450 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
451 sizeof(RpcWireTransaction) <
452 data.dataSize(),
453 "Too much data %zu", data.dataSize());
454
455 RpcWireHeader command{
456 .command = RPC_COMMAND_TRANSACT,
457 .bodySize = static_cast<uint32_t>(sizeof(RpcWireTransaction) + data.dataSize()),
458 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000459 RpcWireTransaction transaction{
460 .address = address.viewRawEmbedded(),
461 .code = code,
462 .flags = flags,
463 .asyncNumber = asyncNumber,
464 };
Steven Moreland77c30112021-06-02 20:45:46 +0000465 CommandData transactionData(sizeof(RpcWireHeader) + sizeof(RpcWireTransaction) +
466 data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000467 if (!transactionData.valid()) {
468 return NO_MEMORY;
469 }
470
Steven Moreland77c30112021-06-02 20:45:46 +0000471 memcpy(transactionData.data() + 0, &command, sizeof(RpcWireHeader));
472 memcpy(transactionData.data() + sizeof(RpcWireHeader), &transaction,
473 sizeof(RpcWireTransaction));
474 memcpy(transactionData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireTransaction), data.data(),
475 data.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000476
Steven Moreland5ae62562021-06-10 03:21:42 +0000477 if (status_t status = rpcSend(connection, session, "transaction", transactionData.data(),
478 transactionData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000479 status != OK)
Steven Morelanda5036f02021-06-08 02:26:57 +0000480 // TODO(b/167966510): need to undo onBinderLeaving - we know the
481 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000482 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000483
484 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000485 LOG_RPC_DETAIL("Oneway command, so no longer waiting on %d", connection->fd.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000486
487 // Do not wait on result.
488 // However, too many oneway calls may cause refcounts to build up and fill up the socket,
489 // so process those.
Steven Moreland5ae62562021-06-10 03:21:42 +0000490 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
Steven Moreland5553ac42020-11-11 02:14:45 +0000491 }
492
493 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
494
Steven Moreland5ae62562021-06-10 03:21:42 +0000495 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000496}
497
Steven Moreland438cce82021-04-02 18:04:08 +0000498static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
499 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000500 (void)p;
501 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
502 (void)dataSize;
503 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Yifan Hong239a2ca2021-06-24 16:05:16 -0700504 LOG_ALWAYS_FATAL_IF(objectsCount != 0, "%zu objects remaining", objectsCount);
Steven Moreland5553ac42020-11-11 02:14:45 +0000505}
506
Steven Moreland5ae62562021-06-10 03:21:42 +0000507status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
508 const sp<RpcSession>& session, Parcel* reply) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000509 RpcWireHeader command;
510 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000511 if (status_t status =
512 rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000513 status != OK)
514 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000515
516 if (command.command == RPC_COMMAND_REPLY) break;
517
Steven Moreland19fc9f72021-06-10 03:57:30 +0000518 if (status_t status = processCommand(connection, session, command, CommandType::ANY);
Steven Moreland52eee942021-06-03 00:59:28 +0000519 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000520 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000521 }
522
Steven Morelanddbe71832021-05-12 23:31:00 +0000523 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000524 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000525
Steven Moreland5ae62562021-06-10 03:21:42 +0000526 if (status_t status = rpcRec(connection, session, "reply body", data.data(), command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000527 status != OK)
528 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000529
530 if (command.bodySize < sizeof(RpcWireReply)) {
531 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
532 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000533 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000534 return BAD_VALUE;
535 }
Steven Morelande8393342021-05-05 23:27:53 +0000536 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000537 if (rpcReply->status != OK) return rpcReply->status;
538
Steven Morelande8393342021-05-05 23:27:53 +0000539 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000540 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000541 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000542
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000543 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000544
545 return OK;
546}
547
Steven Moreland5ae62562021-06-10 03:21:42 +0000548status_t RpcState::sendDecStrong(const sp<RpcSession::RpcConnection>& connection,
549 const sp<RpcSession>& session, const RpcAddress& addr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000550 {
551 std::lock_guard<std::mutex> _l(mNodeMutex);
552 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
553 auto it = mNodeForAddress.find(addr);
554 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
555 addr.toString().c_str());
556 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
557 addr.toString().c_str());
558
559 it->second.timesRecd--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000560 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
561 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000562 }
563
564 RpcWireHeader cmd = {
565 .command = RPC_COMMAND_DEC_STRONG,
566 .bodySize = sizeof(RpcWireAddress),
567 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000568 if (status_t status = rpcSend(connection, session, "dec ref header", &cmd, sizeof(cmd));
569 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000570 return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000571 if (status_t status = rpcSend(connection, session, "dec ref body", &addr.viewRawEmbedded(),
Steven Morelandc9d7b532021-06-04 20:57:41 +0000572 sizeof(RpcWireAddress));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000573 status != OK)
574 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000575 return OK;
576}
577
Steven Moreland5ae62562021-06-10 03:21:42 +0000578status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
579 const sp<RpcSession>& session, CommandType type) {
580 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", connection->fd.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000581
582 RpcWireHeader command;
Steven Moreland5ae62562021-06-10 03:21:42 +0000583 if (status_t status = rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000584 status != OK)
585 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000586
Steven Moreland19fc9f72021-06-10 03:57:30 +0000587 return processCommand(connection, session, command, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000588}
589
Steven Moreland5ae62562021-06-10 03:21:42 +0000590status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
591 const sp<RpcSession>& session, CommandType type) {
Steven Moreland52eee942021-06-03 00:59:28 +0000592 uint8_t buf;
Steven Moreland5ae62562021-06-10 03:21:42 +0000593 while (0 < TEMP_FAILURE_RETRY(
594 recv(connection->fd.get(), &buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT))) {
595 status_t status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000596 if (status != OK) return status;
597 }
598 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000599}
600
Steven Moreland19fc9f72021-06-10 03:57:30 +0000601status_t RpcState::processCommand(const sp<RpcSession::RpcConnection>& connection,
602 const sp<RpcSession>& session, const RpcWireHeader& command,
603 CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000604 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
605 IPCThreadState::SpGuard spGuard{
606 .address = __builtin_frame_address(0),
607 .context = "processing binder RPC command",
608 };
609 const IPCThreadState::SpGuard* origGuard;
610 if (kernelBinderState != nullptr) {
611 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
612 }
613 ScopeGuard guardUnguard = [&]() {
614 if (kernelBinderState != nullptr) {
615 kernelBinderState->restoreGetCallingSpGuard(origGuard);
616 }
617 };
618
Steven Moreland5553ac42020-11-11 02:14:45 +0000619 switch (command.command) {
620 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000621 if (type != CommandType::ANY) return BAD_TYPE;
Steven Moreland5ae62562021-06-10 03:21:42 +0000622 return processTransact(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000623 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000624 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000625 }
626
627 // We should always know the version of the opposing side, and since the
628 // RPC-binder-level wire protocol is not self synchronizing, we have no way
629 // to understand where the current command ends and the next one begins. We
630 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000631 // to kill us, so ending the session for misbehaving client.
632 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000633 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000634 return DEAD_OBJECT;
635}
Steven Moreland5ae62562021-06-10 03:21:42 +0000636status_t RpcState::processTransact(const sp<RpcSession::RpcConnection>& connection,
637 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000638 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
639
Steven Morelanddbe71832021-05-12 23:31:00 +0000640 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000641 if (!transactionData.valid()) {
642 return NO_MEMORY;
643 }
Steven Moreland5ae62562021-06-10 03:21:42 +0000644 if (status_t status = rpcRec(connection, session, "transaction body", transactionData.data(),
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000645 transactionData.size());
646 status != OK)
647 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000648
Steven Moreland5ae62562021-06-10 03:21:42 +0000649 return processTransactInternal(connection, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000650}
651
Steven Moreland438cce82021-04-02 18:04:08 +0000652static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
653 const binder_size_t* objects, size_t objectsCount) {
654 (void)p;
655 (void)data;
656 (void)dataSize;
657 (void)objects;
658 (void)objectsCount;
659}
660
Steven Moreland5ae62562021-06-10 03:21:42 +0000661status_t RpcState::processTransactInternal(const sp<RpcSession::RpcConnection>& connection,
662 const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000663 CommandData transactionData) {
664 // for 'recursive' calls to this, we have already read and processed the
665 // binder from the transaction data and taken reference counts into account,
666 // so it is cached here.
667 sp<IBinder> targetRef;
668processTransactInternalTailCall:
669
Steven Moreland5553ac42020-11-11 02:14:45 +0000670 if (transactionData.size() < sizeof(RpcWireTransaction)) {
671 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
672 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000673 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000674 return BAD_VALUE;
675 }
676 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
677
678 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
679 // maybe add an RpcAddress 'view' if the type remains 'heavy'
680 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000681 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000682
683 status_t replyStatus = OK;
684 sp<IBinder> target;
685 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000686 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000687 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000688 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000689 target = targetRef;
690 }
691
Steven Moreland7227c8a2021-06-02 00:24:32 +0000692 if (replyStatus != OK) {
693 // do nothing
694 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000695 // This can happen if the binder is remote in this process, and
696 // another thread has called the last decStrong on this binder.
697 // However, for local binders, it indicates a misbehaving client
698 // (any binder which is being transacted on should be holding a
699 // strong ref count), so in either case, terminating the
700 // session.
701 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
702 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000703 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000704 replyStatus = BAD_VALUE;
705 } else if (target->localBinder() == nullptr) {
706 ALOGE("Unknown binder address or non-local binder, not address %s. Terminating!",
707 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000708 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000709 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000710 } else if (oneway) {
Steven Morelandd45be622021-06-04 02:19:37 +0000711 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000712 auto it = mNodeForAddress.find(addr);
713 if (it->second.binder.promote() != target) {
714 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000715 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000716 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000717 } else if (transaction->asyncNumber != it->second.asyncNumber) {
718 // we need to process some other asynchronous transaction
719 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000720 it->second.asyncTodo.push(BinderNode::AsyncTodo{
721 .ref = target,
722 .data = std::move(transactionData),
723 .asyncNumber = transaction->asyncNumber,
724 });
Steven Morelandd45be622021-06-04 02:19:37 +0000725
726 size_t numPending = it->second.asyncTodo.size();
727 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s (%zu pending)",
728 transaction->asyncNumber, addr.toString().c_str(), numPending);
729
730 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
731 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
732 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
733
734 if (numPending >= kArbitraryOnewayCallWarnLevel) {
735 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
736 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
737 _l.unlock();
738 (void)session->shutdownAndWait(false);
739 return FAILED_TRANSACTION;
740 }
741
742 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
743 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
744 target.get(), numPending);
745 }
746 }
Steven Morelandf5174272021-05-25 00:39:28 +0000747 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000748 }
749 }
750 }
751
Steven Moreland5553ac42020-11-11 02:14:45 +0000752 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000753 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000754
755 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000756 Parcel data;
757 // transaction->data is owned by this function. Parcel borrows this data and
758 // only holds onto it for the duration of this function call. Parcel will be
759 // deleted before the 'transactionData' object.
760 data.ipcSetDataReference(transaction->data,
761 transactionData.size() - offsetof(RpcWireTransaction, data),
762 nullptr /*object*/, 0 /*objectCount*/,
763 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000764 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000765
Steven Moreland5553ac42020-11-11 02:14:45 +0000766 if (target) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000767 bool origAllowNested = connection->allowNested;
768 connection->allowNested = !oneway;
769
Steven Moreland5553ac42020-11-11 02:14:45 +0000770 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000771
772 connection->allowNested = origAllowNested;
Steven Moreland5553ac42020-11-11 02:14:45 +0000773 } else {
774 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000775
Steven Moreland103424e2021-06-02 18:16:19 +0000776 switch (transaction->code) {
777 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
778 replyStatus = reply.writeInt32(session->getMaxThreads());
779 break;
780 }
781 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
782 // for client connections, this should always report the value
Steven Moreland01a6bad2021-06-11 00:59:20 +0000783 // originally returned from the server, so this is asserting
784 // that it exists
785 replyStatus = session->mId.value().writeToParcel(&reply);
Steven Moreland103424e2021-06-02 18:16:19 +0000786 break;
787 }
788 default: {
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000789 sp<RpcServer> server = session->server();
Steven Moreland103424e2021-06-02 18:16:19 +0000790 if (server) {
791 switch (transaction->code) {
792 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
793 replyStatus = reply.writeStrongBinder(server->getRootObject());
794 break;
795 }
796 default: {
797 replyStatus = UNKNOWN_TRANSACTION;
798 }
799 }
800 } else {
801 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000802 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000803 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000804 }
805 }
806 }
807
Steven Morelandc7d40132021-06-10 03:42:11 +0000808 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000809 if (replyStatus != OK) {
810 ALOGW("Oneway call failed with error: %d", replyStatus);
811 }
812
813 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
814 addr.toString().c_str());
815
816 // Check to see if there is another asynchronous transaction to process.
817 // This behavior differs from binder behavior, since in the binder
818 // driver, asynchronous transactions will be processed after existing
819 // pending binder transactions on the queue. The downside of this is
820 // that asynchronous transactions can be drowned out by synchronous
821 // transactions. However, we have no easy way to queue these
822 // transactions after the synchronous transactions we may want to read
823 // from the wire. So, in socket binder here, we have the opposite
824 // downside: asynchronous transactions may drown out synchronous
825 // transactions.
826 {
827 std::unique_lock<std::mutex> _l(mNodeMutex);
828 auto it = mNodeForAddress.find(addr);
829 // last refcount dropped after this transaction happened
830 if (it == mNodeForAddress.end()) return OK;
831
Steven Morelandc9d7b532021-06-04 20:57:41 +0000832 if (!nodeProgressAsyncNumber(&it->second)) {
833 _l.unlock();
834 (void)session->shutdownAndWait(false);
835 return DEAD_OBJECT;
836 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000837
838 if (it->second.asyncTodo.size() == 0) return OK;
839 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
840 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
841 it->second.asyncNumber, addr.toString().c_str());
842
843 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000844 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000845 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000846 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
847
Steven Morelandada72bd2021-06-09 23:29:13 +0000848 // reset up arguments
849 transactionData = std::move(todo.data);
850 targetRef = std::move(todo.ref);
Steven Morelandf5174272021-05-25 00:39:28 +0000851
Steven Moreland5553ac42020-11-11 02:14:45 +0000852 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000853 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000854 }
855 }
856 return OK;
857 }
858
Steven Moreland77c30112021-06-02 20:45:46 +0000859 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
860 sizeof(RpcWireReply) <
861 reply.dataSize(),
862 "Too much data for reply %zu", reply.dataSize());
863
864 RpcWireHeader cmdReply{
865 .command = RPC_COMMAND_REPLY,
866 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
867 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000868 RpcWireReply rpcReply{
869 .status = replyStatus,
870 };
871
Steven Moreland77c30112021-06-02 20:45:46 +0000872 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000873 if (!replyData.valid()) {
874 return NO_MEMORY;
875 }
Steven Moreland77c30112021-06-02 20:45:46 +0000876 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
877 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
878 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
879 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000880
Steven Moreland5ae62562021-06-10 03:21:42 +0000881 return rpcSend(connection, session, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000882}
883
Steven Moreland5ae62562021-06-10 03:21:42 +0000884status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
885 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000886 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
887
Steven Morelanddbe71832021-05-12 23:31:00 +0000888 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000889 if (!commandData.valid()) {
890 return NO_MEMORY;
891 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000892 if (status_t status =
Steven Moreland5ae62562021-06-10 03:21:42 +0000893 rpcRec(connection, session, "dec ref body", commandData.data(), commandData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000894 status != OK)
895 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000896
897 if (command.bodySize < sizeof(RpcWireAddress)) {
898 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
899 sizeof(RpcWireAddress), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000900 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000901 return BAD_VALUE;
902 }
903 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
904
905 // TODO(b/182939933): heap allocation just for lookup
906 auto addr = RpcAddress::fromRawEmbedded(address);
907 std::unique_lock<std::mutex> _l(mNodeMutex);
908 auto it = mNodeForAddress.find(addr);
909 if (it == mNodeForAddress.end()) {
910 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000911 return OK;
912 }
913
914 sp<IBinder> target = it->second.binder.promote();
915 if (target == nullptr) {
916 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
917 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000918 _l.unlock();
919 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000920 return BAD_VALUE;
921 }
922
923 if (it->second.timesSent == 0) {
924 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
925 return OK;
926 }
927
928 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
929 addr.toString().c_str());
930
Steven Moreland5553ac42020-11-11 02:14:45 +0000931 it->second.timesSent--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000932 sp<IBinder> tempHold = tryEraseNode(it);
933 _l.unlock();
934 tempHold = nullptr; // destructor may make binder calls on this session
935
936 return OK;
937}
938
939sp<IBinder> RpcState::tryEraseNode(std::map<RpcAddress, BinderNode>::iterator& it) {
940 sp<IBinder> ref;
941
Steven Moreland5553ac42020-11-11 02:14:45 +0000942 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000943 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000944
945 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +0000946 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
947 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +0000948 mNodeForAddress.erase(it);
949 }
950 }
951
Steven Moreland31bde7a2021-06-04 00:57:36 +0000952 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +0000953}
954
Steven Morelandc9d7b532021-06-04 20:57:41 +0000955bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000956 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
957 // a single binder
958 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
959 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +0000960 return false;
961 }
962 node->asyncNumber++;
963 return true;
964}
965
Steven Moreland5553ac42020-11-11 02:14:45 +0000966} // namespace android