blob: f3406bb10b822d1f13a1c1e3e0bcbdc4bd99902b [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
Devin Moore08256432021-07-02 13:03:49 -070037#if RPC_FLAKE_PRONE
Steven Morelandb8176792021-06-22 20:29:21 +000038void rpcMaybeWaitToFlake() {
Devin Moore08256432021-07-02 13:03:49 -070039 [[clang::no_destroy]] static std::random_device r;
40 [[clang::no_destroy]] static std::mutex m;
Steven Morelandb8176792021-06-22 20:29:21 +000041 unsigned num;
42 {
43 std::lock_guard<std::mutex> lock(m);
44 num = r();
45 }
46 if (num % 10 == 0) usleep(num % 1000);
47}
48#endif
49
Steven Moreland5553ac42020-11-11 02:14:45 +000050RpcState::RpcState() {}
51RpcState::~RpcState() {}
52
Steven Morelandbdb53ab2021-05-05 17:57:41 +000053status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5553ac42020-11-11 02:14:45 +000054 RpcAddress* outAddress) {
55 bool isRemote = binder->remoteBinder();
56 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
57
Steven Morelandbdb53ab2021-05-05 17:57:41 +000058 if (isRpc && binder->remoteBinder()->getPrivateAccessorForId().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000059 // We need to be able to send instructions over the socket for how to
60 // connect to a different server, and we also need to let the host
61 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000062 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000063 return INVALID_OPERATION;
64 }
65
66 if (isRemote && !isRpc) {
67 // Without additional work, this would have the effect of using this
68 // process to proxy calls from the socket over to the other process, and
69 // it would make those calls look like they come from us (not over the
70 // sockets). In order to make this work transparently like binder, we
71 // would instead need to send instructions over the socket for how to
72 // connect to the host process, and we also need to let the host process
73 // know this was happening.
74 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
75 return INVALID_OPERATION;
76 }
77
78 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000079 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +000080
81 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
82 // in RpcState
83 for (auto& [addr, node] : mNodeForAddress) {
84 if (binder == node.binder) {
85 if (isRpc) {
86 const RpcAddress& actualAddr =
87 binder->remoteBinder()->getPrivateAccessorForId().rpcAddress();
88 // TODO(b/182939933): this is only checking integrity of data structure
89 // a different data structure doesn't need this
90 LOG_ALWAYS_FATAL_IF(addr < actualAddr, "Address mismatch");
91 LOG_ALWAYS_FATAL_IF(actualAddr < addr, "Address mismatch");
92 }
93 node.timesSent++;
94 node.sentRef = binder; // might already be set
95 *outAddress = addr;
96 return OK;
97 }
98 }
99 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
100
Steven Moreland91538242021-06-10 23:35:35 +0000101 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +0000102
Steven Moreland91538242021-06-10 23:35:35 +0000103 for (size_t tries = 0; tries < 5; tries++) {
104 auto&& [it, inserted] = mNodeForAddress.insert({RpcAddress::random(forServer),
105 BinderNode{
106 .binder = binder,
107 .timesSent = 1,
108 .sentRef = binder,
109 }});
110 if (inserted) {
111 *outAddress = it->first;
112 return OK;
113 }
114
115 // well, we don't have visibility into the header here, but still
116 static_assert(sizeof(RpcWireAddress) == 40, "this log needs updating");
117 ALOGW("2**256 is 1e77. If you see this log, you probably have some entropy issue, or maybe "
118 "you witness something incredible!");
119 }
120
121 ALOGE("Unable to create an address in order to send out %p", binder.get());
122 return WOULD_BLOCK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000123}
124
Steven Moreland7227c8a2021-06-02 00:24:32 +0000125status_t RpcState::onBinderEntering(const sp<RpcSession>& session, const RpcAddress& address,
126 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000127 // ensure that: if we want to use addresses for something else in the future (for
128 // instance, allowing transitive binder sends), that we don't accidentally
129 // send those addresses to old server. Accidentally ignoring this in that
130 // case and considering the binder to be recognized could cause this
131 // process to accidentally proxy transactions for that binder. Of course,
132 // if we communicate with a binder, it could always be proxying
133 // information. However, we want to make sure that isn't done on accident
134 // by a client.
135 if (!address.isRecognizedType()) {
136 ALOGE("Address is of an unknown type, rejecting: %s", address.toString().c_str());
137 return BAD_VALUE;
138 }
139
Steven Moreland5553ac42020-11-11 02:14:45 +0000140 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000141 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000142
143 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000144 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000145
146 // implicitly have strong RPC refcount, since we received this binder
147 it->second.timesRecd++;
148
149 _l.unlock();
150
151 // We have timesRecd RPC refcounts, but we only need to hold on to one
152 // when we keep the object. All additional dec strongs are sent
153 // immediately, we wait to send the last one in BpBinder::onLastDecStrong.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000154 (void)session->sendDecStrong(address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000155
Steven Moreland7227c8a2021-06-02 00:24:32 +0000156 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000157 }
158
Steven Moreland91538242021-06-10 23:35:35 +0000159 // we don't know about this binder, so the other side of the connection
160 // should have created it.
161 if (address.isForServer() == !!session->server()) {
162 ALOGE("Server received unrecognized address which we should own the creation of %s.",
163 address.toString().c_str());
164 return BAD_VALUE;
165 }
166
Steven Moreland5553ac42020-11-11 02:14:45 +0000167 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
168 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
169
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000170 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000171 // device global binders in the RPC world).
Steven Moreland7227c8a2021-06-02 00:24:32 +0000172 it->second.binder = *out = BpBinder::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000173 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000174 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000175}
176
177size_t RpcState::countBinders() {
178 std::lock_guard<std::mutex> _l(mNodeMutex);
179 return mNodeForAddress.size();
180}
181
182void RpcState::dump() {
183 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000184 dumpLocked();
185}
186
Steven Morelandc9d7b532021-06-04 20:57:41 +0000187void RpcState::clear() {
Steven Moreland583a14a2021-06-04 02:04:58 +0000188 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000189
190 if (mTerminated) {
191 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
192 "New state should be impossible after terminating!");
193 return;
194 }
195
196 if (SHOULD_LOG_RPC_DETAIL) {
197 ALOGE("RpcState::clear()");
198 dumpLocked();
199 }
200
201 // if the destructor of a binder object makes another RPC call, then calling
202 // decStrong could deadlock. So, we must hold onto these binders until
203 // mNodeMutex is no longer taken.
204 std::vector<sp<IBinder>> tempHoldBinder;
205
206 mTerminated = true;
207 for (auto& [address, node] : mNodeForAddress) {
208 sp<IBinder> binder = node.binder.promote();
209 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
210
211 if (node.sentRef != nullptr) {
212 tempHoldBinder.push_back(node.sentRef);
213 }
214 }
215
216 mNodeForAddress.clear();
217
218 _l.unlock();
219 tempHoldBinder.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000220}
221
222void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000223 ALOGE("DUMP OF RpcState %p", this);
224 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
225 for (const auto& [address, node] : mNodeForAddress) {
226 sp<IBinder> binder = node.binder.promote();
227
228 const char* desc;
229 if (binder) {
230 if (binder->remoteBinder()) {
231 if (binder->remoteBinder()->isRpcBinder()) {
232 desc = "(rpc binder proxy)";
233 } else {
234 desc = "(binder proxy)";
235 }
236 } else {
237 desc = "(local binder)";
238 }
239 } else {
240 desc = "(null)";
241 }
242
243 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a:%s type:%s",
244 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address.toString().c_str(),
245 desc);
246 }
247 ALOGE("END DUMP OF RpcState");
248}
249
Steven Moreland5553ac42020-11-11 02:14:45 +0000250
Steven Morelanddbe71832021-05-12 23:31:00 +0000251RpcState::CommandData::CommandData(size_t size) : mSize(size) {
252 // The maximum size for regular binder is 1MB for all concurrent
253 // transactions. A very small proportion of transactions are even
254 // larger than a page, but we need to avoid allocating too much
255 // data on behalf of an arbitrary client, or we could risk being in
256 // a position where a single additional allocation could run out of
257 // memory.
258 //
259 // Note, this limit may not reflect the total amount of data allocated for a
260 // transaction (in some cases, additional fixed size amounts are added),
261 // though for rough consistency, we should avoid cases where this data type
262 // is used for multiple dynamic allocations for a single transaction.
263 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
264 if (size == 0) return;
265 if (size > kMaxTransactionAllocation) {
266 ALOGW("Transaction requested too much data allocation %zu", size);
267 return;
268 }
269 mData.reset(new (std::nothrow) uint8_t[size]);
270}
271
Steven Moreland5ae62562021-06-10 03:21:42 +0000272status_t RpcState::rpcSend(const sp<RpcSession::RpcConnection>& connection,
273 const sp<RpcSession>& session, const char* what, const void* data,
274 size_t size) {
275 LOG_RPC_DETAIL("Sending %s on fd %d: %s", what, connection->fd.get(),
276 hexString(data, size).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000277
278 if (size > std::numeric_limits<ssize_t>::max()) {
279 ALOGE("Cannot send %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000280 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000281 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000282 }
283
Steven Moreland798e0d12021-07-14 23:19:25 +0000284 if (status_t status = session->mShutdownTrigger->interruptableWriteFully(connection->fd.get(),
285 data, size);
286 status != OK) {
287 LOG_RPC_DETAIL("Failed to write %s (%zu bytes) on fd %d, error: %s", what, size,
288 connection->fd.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000289 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000290 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000291 }
292
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000293 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000294}
295
Steven Moreland5ae62562021-06-10 03:21:42 +0000296status_t RpcState::rpcRec(const sp<RpcSession::RpcConnection>& connection,
297 const sp<RpcSession>& session, const char* what, void* data,
298 size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000299 if (size > std::numeric_limits<ssize_t>::max()) {
300 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000301 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000302 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000303 }
304
Steven Moreland5ae62562021-06-10 03:21:42 +0000305 if (status_t status =
306 session->mShutdownTrigger->interruptableReadFully(connection->fd.get(), data, size);
Steven Morelandee3f4662021-05-22 01:07:33 +0000307 status != OK) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000308 LOG_RPC_DETAIL("Failed to read %s (%zu bytes) on fd %d, error: %s", what, size,
309 connection->fd.get(), statusToString(status).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000310 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000311 }
312
Steven Moreland5ae62562021-06-10 03:21:42 +0000313 LOG_RPC_DETAIL("Received %s on fd %d: %s", what, connection->fd.get(),
314 hexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000315 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000316}
317
Steven Morelandbf57bce2021-07-26 15:26:12 -0700318status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
319 const sp<RpcSession>& session, uint32_t* version) {
320 RpcNewSessionResponse response;
321 if (status_t status =
322 rpcRec(connection, session, "new session response", &response, sizeof(response));
323 status != OK) {
324 return status;
325 }
326 *version = response.version;
327 return OK;
328}
329
Steven Moreland5ae62562021-06-10 03:21:42 +0000330status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
331 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000332 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000333 .msg = RPC_CONNECTION_INIT_OKAY,
334 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000335 return rpcSend(connection, session, "connection init", &init, sizeof(init));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000336}
337
Steven Moreland5ae62562021-06-10 03:21:42 +0000338status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
339 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000340 RpcOutgoingConnectionInit init;
Steven Moreland5ae62562021-06-10 03:21:42 +0000341 if (status_t status = rpcRec(connection, session, "connection init", &init, sizeof(init));
342 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000343 return status;
344
345 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
346 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
347 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
348 init.msg);
349 return BAD_VALUE;
350 }
351 return OK;
352}
353
Steven Moreland5ae62562021-06-10 03:21:42 +0000354sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
355 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000356 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000357 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000358 Parcel reply;
359
Steven Moreland5ae62562021-06-10 03:21:42 +0000360 status_t status = transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT,
361 data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000362 if (status != OK) {
363 ALOGE("Error getting root object: %s", statusToString(status).c_str());
364 return nullptr;
365 }
366
367 return reply.readStrongBinder();
368}
369
Steven Moreland5ae62562021-06-10 03:21:42 +0000370status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
371 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000372 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000373 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000374 Parcel reply;
375
Steven Moreland5ae62562021-06-10 03:21:42 +0000376 status_t status =
377 transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS,
378 data, session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000379 if (status != OK) {
380 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
381 return status;
382 }
383
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000384 int32_t maxThreads;
385 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000386 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000387 if (maxThreads <= 0) {
388 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000389 return BAD_VALUE;
390 }
391
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000392 *maxThreadsOut = maxThreads;
393 return OK;
394}
395
Steven Moreland5ae62562021-06-10 03:21:42 +0000396status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000397 const sp<RpcSession>& session, RpcAddress* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000398 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000399 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000400 Parcel reply;
401
Steven Moreland5ae62562021-06-10 03:21:42 +0000402 status_t status =
403 transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_SESSION_ID,
404 data, session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000405 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000406 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000407 return status;
408 }
409
Steven Moreland01a6bad2021-06-11 00:59:20 +0000410 return sessionIdOut->readFromParcel(reply);
Steven Morelandf137de92021-04-24 01:54:26 +0000411}
412
Steven Moreland5ae62562021-06-10 03:21:42 +0000413status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
414 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
415 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000416 if (!data.isForRpc()) {
417 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
418 return BAD_TYPE;
419 }
420
421 if (data.objectsCount() != 0) {
422 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
423 return BAD_TYPE;
424 }
425
426 RpcAddress address = RpcAddress::zero();
427 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
428
Steven Moreland5ae62562021-06-10 03:21:42 +0000429 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000430}
431
Steven Moreland5ae62562021-06-10 03:21:42 +0000432status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
433 const RpcAddress& address, uint32_t code, const Parcel& data,
434 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000435 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
436 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
437
Steven Moreland5553ac42020-11-11 02:14:45 +0000438 uint64_t asyncNumber = 0;
439
440 if (!address.isZero()) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000441 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000442 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
443 auto it = mNodeForAddress.find(address);
444 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
445 address.toString().c_str());
446
447 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000448 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000449 if (!nodeProgressAsyncNumber(&it->second)) {
450 _l.unlock();
451 (void)session->shutdownAndWait(false);
452 return DEAD_OBJECT;
453 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000454 }
455 }
456
Steven Moreland77c30112021-06-02 20:45:46 +0000457 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
458 sizeof(RpcWireTransaction) <
459 data.dataSize(),
460 "Too much data %zu", data.dataSize());
461
462 RpcWireHeader command{
463 .command = RPC_COMMAND_TRANSACT,
464 .bodySize = static_cast<uint32_t>(sizeof(RpcWireTransaction) + data.dataSize()),
465 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000466 RpcWireTransaction transaction{
467 .address = address.viewRawEmbedded(),
468 .code = code,
469 .flags = flags,
470 .asyncNumber = asyncNumber,
471 };
Steven Moreland77c30112021-06-02 20:45:46 +0000472 CommandData transactionData(sizeof(RpcWireHeader) + sizeof(RpcWireTransaction) +
473 data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000474 if (!transactionData.valid()) {
475 return NO_MEMORY;
476 }
477
Steven Moreland77c30112021-06-02 20:45:46 +0000478 memcpy(transactionData.data() + 0, &command, sizeof(RpcWireHeader));
479 memcpy(transactionData.data() + sizeof(RpcWireHeader), &transaction,
480 sizeof(RpcWireTransaction));
481 memcpy(transactionData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireTransaction), data.data(),
482 data.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000483
Steven Moreland5ae62562021-06-10 03:21:42 +0000484 if (status_t status = rpcSend(connection, session, "transaction", transactionData.data(),
485 transactionData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000486 status != OK)
Steven Morelanda5036f02021-06-08 02:26:57 +0000487 // TODO(b/167966510): need to undo onBinderLeaving - we know the
488 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000489 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000490
491 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000492 LOG_RPC_DETAIL("Oneway command, so no longer waiting on %d", connection->fd.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000493
494 // Do not wait on result.
495 // However, too many oneway calls may cause refcounts to build up and fill up the socket,
496 // so process those.
Steven Moreland5ae62562021-06-10 03:21:42 +0000497 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
Steven Moreland5553ac42020-11-11 02:14:45 +0000498 }
499
500 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
501
Steven Moreland5ae62562021-06-10 03:21:42 +0000502 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000503}
504
Steven Moreland438cce82021-04-02 18:04:08 +0000505static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
506 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000507 (void)p;
508 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
509 (void)dataSize;
510 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Yifan Hong239a2ca2021-06-24 16:05:16 -0700511 LOG_ALWAYS_FATAL_IF(objectsCount != 0, "%zu objects remaining", objectsCount);
Steven Moreland5553ac42020-11-11 02:14:45 +0000512}
513
Steven Moreland5ae62562021-06-10 03:21:42 +0000514status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
515 const sp<RpcSession>& session, Parcel* reply) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000516 RpcWireHeader command;
517 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000518 if (status_t status =
519 rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000520 status != OK)
521 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000522
523 if (command.command == RPC_COMMAND_REPLY) break;
524
Steven Moreland19fc9f72021-06-10 03:57:30 +0000525 if (status_t status = processCommand(connection, session, command, CommandType::ANY);
Steven Moreland52eee942021-06-03 00:59:28 +0000526 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000527 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000528 }
529
Steven Morelanddbe71832021-05-12 23:31:00 +0000530 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000531 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000532
Steven Moreland5ae62562021-06-10 03:21:42 +0000533 if (status_t status = rpcRec(connection, session, "reply body", data.data(), command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000534 status != OK)
535 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000536
537 if (command.bodySize < sizeof(RpcWireReply)) {
538 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
539 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000540 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000541 return BAD_VALUE;
542 }
Steven Morelande8393342021-05-05 23:27:53 +0000543 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000544 if (rpcReply->status != OK) return rpcReply->status;
545
Steven Morelande8393342021-05-05 23:27:53 +0000546 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000547 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000548 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000549
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000550 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000551
552 return OK;
553}
554
Steven Moreland5ae62562021-06-10 03:21:42 +0000555status_t RpcState::sendDecStrong(const sp<RpcSession::RpcConnection>& connection,
556 const sp<RpcSession>& session, const RpcAddress& addr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000557 {
558 std::lock_guard<std::mutex> _l(mNodeMutex);
559 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
560 auto it = mNodeForAddress.find(addr);
561 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
562 addr.toString().c_str());
563 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
564 addr.toString().c_str());
565
566 it->second.timesRecd--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000567 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
568 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000569 }
570
571 RpcWireHeader cmd = {
572 .command = RPC_COMMAND_DEC_STRONG,
573 .bodySize = sizeof(RpcWireAddress),
574 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000575 if (status_t status = rpcSend(connection, session, "dec ref header", &cmd, sizeof(cmd));
576 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000577 return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000578 if (status_t status = rpcSend(connection, session, "dec ref body", &addr.viewRawEmbedded(),
Steven Morelandc9d7b532021-06-04 20:57:41 +0000579 sizeof(RpcWireAddress));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000580 status != OK)
581 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000582 return OK;
583}
584
Steven Moreland5ae62562021-06-10 03:21:42 +0000585status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
586 const sp<RpcSession>& session, CommandType type) {
587 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", connection->fd.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000588
589 RpcWireHeader command;
Steven Moreland5ae62562021-06-10 03:21:42 +0000590 if (status_t status = rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000591 status != OK)
592 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000593
Steven Moreland19fc9f72021-06-10 03:57:30 +0000594 return processCommand(connection, session, command, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000595}
596
Steven Moreland5ae62562021-06-10 03:21:42 +0000597status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
598 const sp<RpcSession>& session, CommandType type) {
Steven Moreland52eee942021-06-03 00:59:28 +0000599 uint8_t buf;
Steven Moreland5ae62562021-06-10 03:21:42 +0000600 while (0 < TEMP_FAILURE_RETRY(
601 recv(connection->fd.get(), &buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT))) {
602 status_t status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000603 if (status != OK) return status;
604 }
605 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000606}
607
Steven Moreland19fc9f72021-06-10 03:57:30 +0000608status_t RpcState::processCommand(const sp<RpcSession::RpcConnection>& connection,
609 const sp<RpcSession>& session, const RpcWireHeader& command,
610 CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000611 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
612 IPCThreadState::SpGuard spGuard{
613 .address = __builtin_frame_address(0),
614 .context = "processing binder RPC command",
615 };
616 const IPCThreadState::SpGuard* origGuard;
617 if (kernelBinderState != nullptr) {
618 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
619 }
620 ScopeGuard guardUnguard = [&]() {
621 if (kernelBinderState != nullptr) {
622 kernelBinderState->restoreGetCallingSpGuard(origGuard);
623 }
624 };
625
Steven Moreland5553ac42020-11-11 02:14:45 +0000626 switch (command.command) {
627 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000628 if (type != CommandType::ANY) return BAD_TYPE;
Steven Moreland5ae62562021-06-10 03:21:42 +0000629 return processTransact(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000630 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000631 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000632 }
633
634 // We should always know the version of the opposing side, and since the
635 // RPC-binder-level wire protocol is not self synchronizing, we have no way
636 // to understand where the current command ends and the next one begins. We
637 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000638 // to kill us, so ending the session for misbehaving client.
639 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000640 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000641 return DEAD_OBJECT;
642}
Steven Moreland5ae62562021-06-10 03:21:42 +0000643status_t RpcState::processTransact(const sp<RpcSession::RpcConnection>& connection,
644 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000645 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
646
Steven Morelanddbe71832021-05-12 23:31:00 +0000647 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000648 if (!transactionData.valid()) {
649 return NO_MEMORY;
650 }
Steven Moreland5ae62562021-06-10 03:21:42 +0000651 if (status_t status = rpcRec(connection, session, "transaction body", transactionData.data(),
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000652 transactionData.size());
653 status != OK)
654 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000655
Steven Moreland5ae62562021-06-10 03:21:42 +0000656 return processTransactInternal(connection, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000657}
658
Steven Moreland438cce82021-04-02 18:04:08 +0000659static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
660 const binder_size_t* objects, size_t objectsCount) {
661 (void)p;
662 (void)data;
663 (void)dataSize;
664 (void)objects;
665 (void)objectsCount;
666}
667
Steven Moreland5ae62562021-06-10 03:21:42 +0000668status_t RpcState::processTransactInternal(const sp<RpcSession::RpcConnection>& connection,
669 const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000670 CommandData transactionData) {
671 // for 'recursive' calls to this, we have already read and processed the
672 // binder from the transaction data and taken reference counts into account,
673 // so it is cached here.
674 sp<IBinder> targetRef;
675processTransactInternalTailCall:
676
Steven Moreland5553ac42020-11-11 02:14:45 +0000677 if (transactionData.size() < sizeof(RpcWireTransaction)) {
678 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
679 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000680 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000681 return BAD_VALUE;
682 }
683 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
684
685 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
686 // maybe add an RpcAddress 'view' if the type remains 'heavy'
687 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000688 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000689
690 status_t replyStatus = OK;
691 sp<IBinder> target;
692 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000693 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000694 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000695 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000696 target = targetRef;
697 }
698
Steven Moreland7227c8a2021-06-02 00:24:32 +0000699 if (replyStatus != OK) {
700 // do nothing
701 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000702 // This can happen if the binder is remote in this process, and
703 // another thread has called the last decStrong on this binder.
704 // However, for local binders, it indicates a misbehaving client
705 // (any binder which is being transacted on should be holding a
706 // strong ref count), so in either case, terminating the
707 // session.
708 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
709 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000710 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000711 replyStatus = BAD_VALUE;
712 } else if (target->localBinder() == nullptr) {
713 ALOGE("Unknown binder address or non-local binder, not address %s. Terminating!",
714 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000715 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000716 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000717 } else if (oneway) {
Steven Morelandd45be622021-06-04 02:19:37 +0000718 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000719 auto it = mNodeForAddress.find(addr);
720 if (it->second.binder.promote() != target) {
721 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000722 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000723 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000724 } else if (transaction->asyncNumber != it->second.asyncNumber) {
725 // we need to process some other asynchronous transaction
726 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000727 it->second.asyncTodo.push(BinderNode::AsyncTodo{
728 .ref = target,
729 .data = std::move(transactionData),
730 .asyncNumber = transaction->asyncNumber,
731 });
Steven Morelandd45be622021-06-04 02:19:37 +0000732
733 size_t numPending = it->second.asyncTodo.size();
734 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s (%zu pending)",
735 transaction->asyncNumber, addr.toString().c_str(), numPending);
736
737 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
738 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
739 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
740
741 if (numPending >= kArbitraryOnewayCallWarnLevel) {
742 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
743 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
744 _l.unlock();
745 (void)session->shutdownAndWait(false);
746 return FAILED_TRANSACTION;
747 }
748
749 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
750 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
751 target.get(), numPending);
752 }
753 }
Steven Morelandf5174272021-05-25 00:39:28 +0000754 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000755 }
756 }
757 }
758
Steven Moreland5553ac42020-11-11 02:14:45 +0000759 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000760 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000761
762 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000763 Parcel data;
764 // transaction->data is owned by this function. Parcel borrows this data and
765 // only holds onto it for the duration of this function call. Parcel will be
766 // deleted before the 'transactionData' object.
767 data.ipcSetDataReference(transaction->data,
768 transactionData.size() - offsetof(RpcWireTransaction, data),
769 nullptr /*object*/, 0 /*objectCount*/,
770 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000771 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000772
Steven Moreland5553ac42020-11-11 02:14:45 +0000773 if (target) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000774 bool origAllowNested = connection->allowNested;
775 connection->allowNested = !oneway;
776
Steven Moreland5553ac42020-11-11 02:14:45 +0000777 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000778
779 connection->allowNested = origAllowNested;
Steven Moreland5553ac42020-11-11 02:14:45 +0000780 } else {
781 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000782
Steven Moreland103424e2021-06-02 18:16:19 +0000783 switch (transaction->code) {
784 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
785 replyStatus = reply.writeInt32(session->getMaxThreads());
786 break;
787 }
788 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
789 // for client connections, this should always report the value
Steven Moreland01a6bad2021-06-11 00:59:20 +0000790 // originally returned from the server, so this is asserting
791 // that it exists
792 replyStatus = session->mId.value().writeToParcel(&reply);
Steven Moreland103424e2021-06-02 18:16:19 +0000793 break;
794 }
795 default: {
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000796 sp<RpcServer> server = session->server();
Steven Moreland103424e2021-06-02 18:16:19 +0000797 if (server) {
798 switch (transaction->code) {
799 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
800 replyStatus = reply.writeStrongBinder(server->getRootObject());
801 break;
802 }
803 default: {
804 replyStatus = UNKNOWN_TRANSACTION;
805 }
806 }
807 } else {
808 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000809 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000810 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000811 }
812 }
813 }
814
Steven Morelandc7d40132021-06-10 03:42:11 +0000815 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000816 if (replyStatus != OK) {
817 ALOGW("Oneway call failed with error: %d", replyStatus);
818 }
819
820 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
821 addr.toString().c_str());
822
823 // Check to see if there is another asynchronous transaction to process.
824 // This behavior differs from binder behavior, since in the binder
825 // driver, asynchronous transactions will be processed after existing
826 // pending binder transactions on the queue. The downside of this is
827 // that asynchronous transactions can be drowned out by synchronous
828 // transactions. However, we have no easy way to queue these
829 // transactions after the synchronous transactions we may want to read
830 // from the wire. So, in socket binder here, we have the opposite
831 // downside: asynchronous transactions may drown out synchronous
832 // transactions.
833 {
834 std::unique_lock<std::mutex> _l(mNodeMutex);
835 auto it = mNodeForAddress.find(addr);
836 // last refcount dropped after this transaction happened
837 if (it == mNodeForAddress.end()) return OK;
838
Steven Morelandc9d7b532021-06-04 20:57:41 +0000839 if (!nodeProgressAsyncNumber(&it->second)) {
840 _l.unlock();
841 (void)session->shutdownAndWait(false);
842 return DEAD_OBJECT;
843 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000844
845 if (it->second.asyncTodo.size() == 0) return OK;
846 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
847 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
848 it->second.asyncNumber, addr.toString().c_str());
849
850 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000851 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000852 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000853 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
854
Steven Morelandada72bd2021-06-09 23:29:13 +0000855 // reset up arguments
856 transactionData = std::move(todo.data);
857 targetRef = std::move(todo.ref);
Steven Morelandf5174272021-05-25 00:39:28 +0000858
Steven Moreland5553ac42020-11-11 02:14:45 +0000859 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000860 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000861 }
862 }
863 return OK;
864 }
865
Steven Moreland77c30112021-06-02 20:45:46 +0000866 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
867 sizeof(RpcWireReply) <
868 reply.dataSize(),
869 "Too much data for reply %zu", reply.dataSize());
870
871 RpcWireHeader cmdReply{
872 .command = RPC_COMMAND_REPLY,
873 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
874 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000875 RpcWireReply rpcReply{
876 .status = replyStatus,
877 };
878
Steven Moreland77c30112021-06-02 20:45:46 +0000879 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000880 if (!replyData.valid()) {
881 return NO_MEMORY;
882 }
Steven Moreland77c30112021-06-02 20:45:46 +0000883 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
884 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
885 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
886 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000887
Steven Moreland5ae62562021-06-10 03:21:42 +0000888 return rpcSend(connection, session, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000889}
890
Steven Moreland5ae62562021-06-10 03:21:42 +0000891status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
892 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000893 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
894
Steven Morelanddbe71832021-05-12 23:31:00 +0000895 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000896 if (!commandData.valid()) {
897 return NO_MEMORY;
898 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000899 if (status_t status =
Steven Moreland5ae62562021-06-10 03:21:42 +0000900 rpcRec(connection, session, "dec ref body", commandData.data(), commandData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000901 status != OK)
902 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000903
904 if (command.bodySize < sizeof(RpcWireAddress)) {
905 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
906 sizeof(RpcWireAddress), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000907 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000908 return BAD_VALUE;
909 }
910 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
911
912 // TODO(b/182939933): heap allocation just for lookup
913 auto addr = RpcAddress::fromRawEmbedded(address);
914 std::unique_lock<std::mutex> _l(mNodeMutex);
915 auto it = mNodeForAddress.find(addr);
916 if (it == mNodeForAddress.end()) {
917 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000918 return OK;
919 }
920
921 sp<IBinder> target = it->second.binder.promote();
922 if (target == nullptr) {
923 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
924 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000925 _l.unlock();
926 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000927 return BAD_VALUE;
928 }
929
930 if (it->second.timesSent == 0) {
931 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
932 return OK;
933 }
934
935 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
936 addr.toString().c_str());
937
Steven Moreland5553ac42020-11-11 02:14:45 +0000938 it->second.timesSent--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000939 sp<IBinder> tempHold = tryEraseNode(it);
940 _l.unlock();
941 tempHold = nullptr; // destructor may make binder calls on this session
942
943 return OK;
944}
945
946sp<IBinder> RpcState::tryEraseNode(std::map<RpcAddress, BinderNode>::iterator& it) {
947 sp<IBinder> ref;
948
Steven Moreland5553ac42020-11-11 02:14:45 +0000949 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000950 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000951
952 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +0000953 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
954 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +0000955 mNodeForAddress.erase(it);
956 }
957 }
958
Steven Moreland31bde7a2021-06-04 00:57:36 +0000959 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +0000960}
961
Steven Morelandc9d7b532021-06-04 20:57:41 +0000962bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000963 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
964 // a single binder
965 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
966 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +0000967 return false;
968 }
969 node->asyncNumber++;
970 return true;
971}
972
Steven Moreland5553ac42020-11-11 02:14:45 +0000973} // namespace android