blob: 15eec20d1d80f63c938638feba9685d9b4e3953e [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
29#include <inttypes.h>
30
31namespace android {
32
Steven Morelandd7302072021-05-15 01:32:04 +000033using base::ScopeGuard;
34
Steven Moreland5553ac42020-11-11 02:14:45 +000035RpcState::RpcState() {}
36RpcState::~RpcState() {}
37
Steven Morelandbdb53ab2021-05-05 17:57:41 +000038status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5553ac42020-11-11 02:14:45 +000039 RpcAddress* outAddress) {
40 bool isRemote = binder->remoteBinder();
41 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
42
Steven Morelandbdb53ab2021-05-05 17:57:41 +000043 if (isRpc && binder->remoteBinder()->getPrivateAccessorForId().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000044 // We need to be able to send instructions over the socket for how to
45 // connect to a different server, and we also need to let the host
46 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000047 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000048 return INVALID_OPERATION;
49 }
50
51 if (isRemote && !isRpc) {
52 // Without additional work, this would have the effect of using this
53 // process to proxy calls from the socket over to the other process, and
54 // it would make those calls look like they come from us (not over the
55 // sockets). In order to make this work transparently like binder, we
56 // would instead need to send instructions over the socket for how to
57 // connect to the host process, and we also need to let the host process
58 // know this was happening.
59 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
60 return INVALID_OPERATION;
61 }
62
63 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000064 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +000065
66 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
67 // in RpcState
68 for (auto& [addr, node] : mNodeForAddress) {
69 if (binder == node.binder) {
70 if (isRpc) {
71 const RpcAddress& actualAddr =
72 binder->remoteBinder()->getPrivateAccessorForId().rpcAddress();
73 // TODO(b/182939933): this is only checking integrity of data structure
74 // a different data structure doesn't need this
75 LOG_ALWAYS_FATAL_IF(addr < actualAddr, "Address mismatch");
76 LOG_ALWAYS_FATAL_IF(actualAddr < addr, "Address mismatch");
77 }
78 node.timesSent++;
79 node.sentRef = binder; // might already be set
80 *outAddress = addr;
81 return OK;
82 }
83 }
84 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
85
Steven Moreland91538242021-06-10 23:35:35 +000086 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +000087
Steven Moreland91538242021-06-10 23:35:35 +000088 for (size_t tries = 0; tries < 5; tries++) {
89 auto&& [it, inserted] = mNodeForAddress.insert({RpcAddress::random(forServer),
90 BinderNode{
91 .binder = binder,
92 .timesSent = 1,
93 .sentRef = binder,
94 }});
95 if (inserted) {
96 *outAddress = it->first;
97 return OK;
98 }
99
100 // well, we don't have visibility into the header here, but still
101 static_assert(sizeof(RpcWireAddress) == 40, "this log needs updating");
102 ALOGW("2**256 is 1e77. If you see this log, you probably have some entropy issue, or maybe "
103 "you witness something incredible!");
104 }
105
106 ALOGE("Unable to create an address in order to send out %p", binder.get());
107 return WOULD_BLOCK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000108}
109
Steven Moreland7227c8a2021-06-02 00:24:32 +0000110status_t RpcState::onBinderEntering(const sp<RpcSession>& session, const RpcAddress& address,
111 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000112 // ensure that: if we want to use addresses for something else in the future (for
113 // instance, allowing transitive binder sends), that we don't accidentally
114 // send those addresses to old server. Accidentally ignoring this in that
115 // case and considering the binder to be recognized could cause this
116 // process to accidentally proxy transactions for that binder. Of course,
117 // if we communicate with a binder, it could always be proxying
118 // information. However, we want to make sure that isn't done on accident
119 // by a client.
120 if (!address.isRecognizedType()) {
121 ALOGE("Address is of an unknown type, rejecting: %s", address.toString().c_str());
122 return BAD_VALUE;
123 }
124
Steven Moreland5553ac42020-11-11 02:14:45 +0000125 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000126 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000127
128 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000129 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000130
131 // implicitly have strong RPC refcount, since we received this binder
132 it->second.timesRecd++;
133
134 _l.unlock();
135
136 // We have timesRecd RPC refcounts, but we only need to hold on to one
137 // when we keep the object. All additional dec strongs are sent
138 // immediately, we wait to send the last one in BpBinder::onLastDecStrong.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000139 (void)session->sendDecStrong(address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000140
Steven Moreland7227c8a2021-06-02 00:24:32 +0000141 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000142 }
143
Steven Moreland91538242021-06-10 23:35:35 +0000144 // we don't know about this binder, so the other side of the connection
145 // should have created it.
146 if (address.isForServer() == !!session->server()) {
147 ALOGE("Server received unrecognized address which we should own the creation of %s.",
148 address.toString().c_str());
149 return BAD_VALUE;
150 }
151
Steven Moreland5553ac42020-11-11 02:14:45 +0000152 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
153 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
154
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000155 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000156 // device global binders in the RPC world).
Steven Moreland7227c8a2021-06-02 00:24:32 +0000157 it->second.binder = *out = BpBinder::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000158 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000159 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000160}
161
162size_t RpcState::countBinders() {
163 std::lock_guard<std::mutex> _l(mNodeMutex);
164 return mNodeForAddress.size();
165}
166
167void RpcState::dump() {
168 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000169 dumpLocked();
170}
171
Steven Morelandc9d7b532021-06-04 20:57:41 +0000172void RpcState::clear() {
Steven Moreland583a14a2021-06-04 02:04:58 +0000173 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000174
175 if (mTerminated) {
176 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
177 "New state should be impossible after terminating!");
178 return;
179 }
180
181 if (SHOULD_LOG_RPC_DETAIL) {
182 ALOGE("RpcState::clear()");
183 dumpLocked();
184 }
185
186 // if the destructor of a binder object makes another RPC call, then calling
187 // decStrong could deadlock. So, we must hold onto these binders until
188 // mNodeMutex is no longer taken.
189 std::vector<sp<IBinder>> tempHoldBinder;
190
191 mTerminated = true;
192 for (auto& [address, node] : mNodeForAddress) {
193 sp<IBinder> binder = node.binder.promote();
194 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
195
196 if (node.sentRef != nullptr) {
197 tempHoldBinder.push_back(node.sentRef);
198 }
199 }
200
201 mNodeForAddress.clear();
202
203 _l.unlock();
204 tempHoldBinder.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000205}
206
207void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000208 ALOGE("DUMP OF RpcState %p", this);
209 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
210 for (const auto& [address, node] : mNodeForAddress) {
211 sp<IBinder> binder = node.binder.promote();
212
213 const char* desc;
214 if (binder) {
215 if (binder->remoteBinder()) {
216 if (binder->remoteBinder()->isRpcBinder()) {
217 desc = "(rpc binder proxy)";
218 } else {
219 desc = "(binder proxy)";
220 }
221 } else {
222 desc = "(local binder)";
223 }
224 } else {
225 desc = "(null)";
226 }
227
228 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a:%s type:%s",
229 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address.toString().c_str(),
230 desc);
231 }
232 ALOGE("END DUMP OF RpcState");
233}
234
Steven Moreland5553ac42020-11-11 02:14:45 +0000235
Steven Morelanddbe71832021-05-12 23:31:00 +0000236RpcState::CommandData::CommandData(size_t size) : mSize(size) {
237 // The maximum size for regular binder is 1MB for all concurrent
238 // transactions. A very small proportion of transactions are even
239 // larger than a page, but we need to avoid allocating too much
240 // data on behalf of an arbitrary client, or we could risk being in
241 // a position where a single additional allocation could run out of
242 // memory.
243 //
244 // Note, this limit may not reflect the total amount of data allocated for a
245 // transaction (in some cases, additional fixed size amounts are added),
246 // though for rough consistency, we should avoid cases where this data type
247 // is used for multiple dynamic allocations for a single transaction.
248 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
249 if (size == 0) return;
250 if (size > kMaxTransactionAllocation) {
251 ALOGW("Transaction requested too much data allocation %zu", size);
252 return;
253 }
254 mData.reset(new (std::nothrow) uint8_t[size]);
255}
256
Steven Moreland5ae62562021-06-10 03:21:42 +0000257status_t RpcState::rpcSend(const sp<RpcSession::RpcConnection>& connection,
258 const sp<RpcSession>& session, const char* what, const void* data,
259 size_t size) {
260 LOG_RPC_DETAIL("Sending %s on fd %d: %s", what, connection->fd.get(),
261 hexString(data, size).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000262
263 if (size > std::numeric_limits<ssize_t>::max()) {
264 ALOGE("Cannot send %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000265 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000266 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000267 }
268
Steven Moreland5ae62562021-06-10 03:21:42 +0000269 ssize_t sent = TEMP_FAILURE_RETRY(send(connection->fd.get(), data, size, MSG_NOSIGNAL));
Steven Moreland5553ac42020-11-11 02:14:45 +0000270
271 if (sent < 0 || sent != static_cast<ssize_t>(size)) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000272 int savedErrno = errno;
Steven Morelandc12c9d92021-05-26 18:44:11 +0000273 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 +0000274 size, connection->fd.get(), strerror(savedErrno));
Steven Moreland5553ac42020-11-11 02:14:45 +0000275
Steven Morelandc9d7b532021-06-04 20:57:41 +0000276 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000277 return -savedErrno;
Steven Moreland5553ac42020-11-11 02:14:45 +0000278 }
279
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000280 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000281}
282
Steven Moreland5ae62562021-06-10 03:21:42 +0000283status_t RpcState::rpcRec(const sp<RpcSession::RpcConnection>& connection,
284 const sp<RpcSession>& session, const char* what, void* data,
285 size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000286 if (size > std::numeric_limits<ssize_t>::max()) {
287 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000288 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000289 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000290 }
291
Steven Moreland5ae62562021-06-10 03:21:42 +0000292 if (status_t status =
293 session->mShutdownTrigger->interruptableReadFully(connection->fd.get(), data, size);
Steven Morelandee3f4662021-05-22 01:07:33 +0000294 status != OK) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000295 LOG_RPC_DETAIL("Failed to read %s (%zu bytes) on fd %d, error: %s", what, size,
296 connection->fd.get(), statusToString(status).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000297 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000298 }
299
Steven Moreland5ae62562021-06-10 03:21:42 +0000300 LOG_RPC_DETAIL("Received %s on fd %d: %s", what, connection->fd.get(),
301 hexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000302 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000303}
304
Steven Moreland5ae62562021-06-10 03:21:42 +0000305status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
306 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000307 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000308 .msg = RPC_CONNECTION_INIT_OKAY,
309 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000310 return rpcSend(connection, session, "connection init", &init, sizeof(init));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000311}
312
Steven Moreland5ae62562021-06-10 03:21:42 +0000313status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
314 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000315 RpcOutgoingConnectionInit init;
Steven Moreland5ae62562021-06-10 03:21:42 +0000316 if (status_t status = rpcRec(connection, session, "connection init", &init, sizeof(init));
317 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000318 return status;
319
320 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
321 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
322 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
323 init.msg);
324 return BAD_VALUE;
325 }
326 return OK;
327}
328
Steven Moreland5ae62562021-06-10 03:21:42 +0000329sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
330 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000331 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000332 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000333 Parcel reply;
334
Steven Moreland5ae62562021-06-10 03:21:42 +0000335 status_t status = transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT,
336 data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000337 if (status != OK) {
338 ALOGE("Error getting root object: %s", statusToString(status).c_str());
339 return nullptr;
340 }
341
342 return reply.readStrongBinder();
343}
344
Steven Moreland5ae62562021-06-10 03:21:42 +0000345status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
346 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000347 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000348 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000349 Parcel reply;
350
Steven Moreland5ae62562021-06-10 03:21:42 +0000351 status_t status =
352 transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS,
353 data, session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000354 if (status != OK) {
355 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
356 return status;
357 }
358
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000359 int32_t maxThreads;
360 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000361 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000362 if (maxThreads <= 0) {
363 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000364 return BAD_VALUE;
365 }
366
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000367 *maxThreadsOut = maxThreads;
368 return OK;
369}
370
Steven Moreland5ae62562021-06-10 03:21:42 +0000371status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
372 const sp<RpcSession>& session, int32_t* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000373 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000374 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000375 Parcel reply;
376
Steven Moreland5ae62562021-06-10 03:21:42 +0000377 status_t status =
378 transactAddress(connection, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_SESSION_ID,
379 data, session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000380 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000381 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000382 return status;
383 }
384
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000385 int32_t sessionId;
386 status = reply.readInt32(&sessionId);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000387 if (status != OK) return status;
388
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000389 *sessionIdOut = sessionId;
Steven Morelandf137de92021-04-24 01:54:26 +0000390 return OK;
391}
392
Steven Moreland5ae62562021-06-10 03:21:42 +0000393status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
394 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
395 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000396 if (!data.isForRpc()) {
397 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
398 return BAD_TYPE;
399 }
400
401 if (data.objectsCount() != 0) {
402 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
403 return BAD_TYPE;
404 }
405
406 RpcAddress address = RpcAddress::zero();
407 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
408
Steven Moreland5ae62562021-06-10 03:21:42 +0000409 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000410}
411
Steven Moreland5ae62562021-06-10 03:21:42 +0000412status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
413 const RpcAddress& address, uint32_t code, const Parcel& data,
414 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000415 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
416 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
417
Steven Moreland5553ac42020-11-11 02:14:45 +0000418 uint64_t asyncNumber = 0;
419
420 if (!address.isZero()) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000421 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000422 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
423 auto it = mNodeForAddress.find(address);
424 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
425 address.toString().c_str());
426
427 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000428 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000429 if (!nodeProgressAsyncNumber(&it->second)) {
430 _l.unlock();
431 (void)session->shutdownAndWait(false);
432 return DEAD_OBJECT;
433 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000434 }
435 }
436
Steven Moreland77c30112021-06-02 20:45:46 +0000437 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
438 sizeof(RpcWireTransaction) <
439 data.dataSize(),
440 "Too much data %zu", data.dataSize());
441
442 RpcWireHeader command{
443 .command = RPC_COMMAND_TRANSACT,
444 .bodySize = static_cast<uint32_t>(sizeof(RpcWireTransaction) + data.dataSize()),
445 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000446 RpcWireTransaction transaction{
447 .address = address.viewRawEmbedded(),
448 .code = code,
449 .flags = flags,
450 .asyncNumber = asyncNumber,
451 };
Steven Moreland77c30112021-06-02 20:45:46 +0000452 CommandData transactionData(sizeof(RpcWireHeader) + sizeof(RpcWireTransaction) +
453 data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000454 if (!transactionData.valid()) {
455 return NO_MEMORY;
456 }
457
Steven Moreland77c30112021-06-02 20:45:46 +0000458 memcpy(transactionData.data() + 0, &command, sizeof(RpcWireHeader));
459 memcpy(transactionData.data() + sizeof(RpcWireHeader), &transaction,
460 sizeof(RpcWireTransaction));
461 memcpy(transactionData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireTransaction), data.data(),
462 data.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000463
Steven Moreland5ae62562021-06-10 03:21:42 +0000464 if (status_t status = rpcSend(connection, session, "transaction", transactionData.data(),
465 transactionData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000466 status != OK)
Steven Morelanda5036f02021-06-08 02:26:57 +0000467 // TODO(b/167966510): need to undo onBinderLeaving - we know the
468 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000469 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000470
471 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000472 LOG_RPC_DETAIL("Oneway command, so no longer waiting on %d", connection->fd.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000473
474 // Do not wait on result.
475 // However, too many oneway calls may cause refcounts to build up and fill up the socket,
476 // so process those.
Steven Moreland5ae62562021-06-10 03:21:42 +0000477 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
Steven Moreland5553ac42020-11-11 02:14:45 +0000478 }
479
480 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
481
Steven Moreland5ae62562021-06-10 03:21:42 +0000482 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000483}
484
Steven Moreland438cce82021-04-02 18:04:08 +0000485static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
486 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000487 (void)p;
488 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
489 (void)dataSize;
490 LOG_ALWAYS_FATAL_IF(objects != nullptr);
491 LOG_ALWAYS_FATAL_IF(objectsCount, 0);
492}
493
Steven Moreland5ae62562021-06-10 03:21:42 +0000494status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
495 const sp<RpcSession>& session, Parcel* reply) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000496 RpcWireHeader command;
497 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000498 if (status_t status =
499 rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000500 status != OK)
501 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000502
503 if (command.command == RPC_COMMAND_REPLY) break;
504
Steven Moreland19fc9f72021-06-10 03:57:30 +0000505 if (status_t status = processCommand(connection, session, command, CommandType::ANY);
Steven Moreland52eee942021-06-03 00:59:28 +0000506 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000507 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000508 }
509
Steven Morelanddbe71832021-05-12 23:31:00 +0000510 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000511 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000512
Steven Moreland5ae62562021-06-10 03:21:42 +0000513 if (status_t status = rpcRec(connection, session, "reply body", data.data(), command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000514 status != OK)
515 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000516
517 if (command.bodySize < sizeof(RpcWireReply)) {
518 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
519 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000520 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000521 return BAD_VALUE;
522 }
Steven Morelande8393342021-05-05 23:27:53 +0000523 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000524 if (rpcReply->status != OK) return rpcReply->status;
525
Steven Morelande8393342021-05-05 23:27:53 +0000526 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000527 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000528 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000529
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000530 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000531
532 return OK;
533}
534
Steven Moreland5ae62562021-06-10 03:21:42 +0000535status_t RpcState::sendDecStrong(const sp<RpcSession::RpcConnection>& connection,
536 const sp<RpcSession>& session, const RpcAddress& addr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000537 {
538 std::lock_guard<std::mutex> _l(mNodeMutex);
539 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
540 auto it = mNodeForAddress.find(addr);
541 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
542 addr.toString().c_str());
543 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
544 addr.toString().c_str());
545
546 it->second.timesRecd--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000547 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
548 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000549 }
550
551 RpcWireHeader cmd = {
552 .command = RPC_COMMAND_DEC_STRONG,
553 .bodySize = sizeof(RpcWireAddress),
554 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000555 if (status_t status = rpcSend(connection, session, "dec ref header", &cmd, sizeof(cmd));
556 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000557 return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000558 if (status_t status = rpcSend(connection, session, "dec ref body", &addr.viewRawEmbedded(),
Steven Morelandc9d7b532021-06-04 20:57:41 +0000559 sizeof(RpcWireAddress));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000560 status != OK)
561 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000562 return OK;
563}
564
Steven Moreland5ae62562021-06-10 03:21:42 +0000565status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
566 const sp<RpcSession>& session, CommandType type) {
567 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", connection->fd.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000568
569 RpcWireHeader command;
Steven Moreland5ae62562021-06-10 03:21:42 +0000570 if (status_t status = rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000571 status != OK)
572 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000573
Steven Moreland19fc9f72021-06-10 03:57:30 +0000574 return processCommand(connection, session, command, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000575}
576
Steven Moreland5ae62562021-06-10 03:21:42 +0000577status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
578 const sp<RpcSession>& session, CommandType type) {
Steven Moreland52eee942021-06-03 00:59:28 +0000579 uint8_t buf;
Steven Moreland5ae62562021-06-10 03:21:42 +0000580 while (0 < TEMP_FAILURE_RETRY(
581 recv(connection->fd.get(), &buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT))) {
582 status_t status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000583 if (status != OK) return status;
584 }
585 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000586}
587
Steven Moreland19fc9f72021-06-10 03:57:30 +0000588status_t RpcState::processCommand(const sp<RpcSession::RpcConnection>& connection,
589 const sp<RpcSession>& session, const RpcWireHeader& command,
590 CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000591 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
592 IPCThreadState::SpGuard spGuard{
593 .address = __builtin_frame_address(0),
594 .context = "processing binder RPC command",
595 };
596 const IPCThreadState::SpGuard* origGuard;
597 if (kernelBinderState != nullptr) {
598 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
599 }
600 ScopeGuard guardUnguard = [&]() {
601 if (kernelBinderState != nullptr) {
602 kernelBinderState->restoreGetCallingSpGuard(origGuard);
603 }
604 };
605
Steven Moreland5553ac42020-11-11 02:14:45 +0000606 switch (command.command) {
607 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000608 if (type != CommandType::ANY) return BAD_TYPE;
Steven Moreland5ae62562021-06-10 03:21:42 +0000609 return processTransact(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000610 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000611 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000612 }
613
614 // We should always know the version of the opposing side, and since the
615 // RPC-binder-level wire protocol is not self synchronizing, we have no way
616 // to understand where the current command ends and the next one begins. We
617 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000618 // to kill us, so ending the session for misbehaving client.
619 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000620 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000621 return DEAD_OBJECT;
622}
Steven Moreland5ae62562021-06-10 03:21:42 +0000623status_t RpcState::processTransact(const sp<RpcSession::RpcConnection>& connection,
624 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000625 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
626
Steven Morelanddbe71832021-05-12 23:31:00 +0000627 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000628 if (!transactionData.valid()) {
629 return NO_MEMORY;
630 }
Steven Moreland5ae62562021-06-10 03:21:42 +0000631 if (status_t status = rpcRec(connection, session, "transaction body", transactionData.data(),
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000632 transactionData.size());
633 status != OK)
634 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000635
Steven Moreland5ae62562021-06-10 03:21:42 +0000636 return processTransactInternal(connection, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000637}
638
Steven Moreland438cce82021-04-02 18:04:08 +0000639static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
640 const binder_size_t* objects, size_t objectsCount) {
641 (void)p;
642 (void)data;
643 (void)dataSize;
644 (void)objects;
645 (void)objectsCount;
646}
647
Steven Moreland5ae62562021-06-10 03:21:42 +0000648status_t RpcState::processTransactInternal(const sp<RpcSession::RpcConnection>& connection,
649 const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000650 CommandData transactionData) {
651 // for 'recursive' calls to this, we have already read and processed the
652 // binder from the transaction data and taken reference counts into account,
653 // so it is cached here.
654 sp<IBinder> targetRef;
655processTransactInternalTailCall:
656
Steven Moreland5553ac42020-11-11 02:14:45 +0000657 if (transactionData.size() < sizeof(RpcWireTransaction)) {
658 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
659 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000660 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000661 return BAD_VALUE;
662 }
663 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
664
665 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
666 // maybe add an RpcAddress 'view' if the type remains 'heavy'
667 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000668 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000669
670 status_t replyStatus = OK;
671 sp<IBinder> target;
672 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000673 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000674 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000675 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000676 target = targetRef;
677 }
678
Steven Moreland7227c8a2021-06-02 00:24:32 +0000679 if (replyStatus != OK) {
680 // do nothing
681 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000682 // This can happen if the binder is remote in this process, and
683 // another thread has called the last decStrong on this binder.
684 // However, for local binders, it indicates a misbehaving client
685 // (any binder which is being transacted on should be holding a
686 // strong ref count), so in either case, terminating the
687 // session.
688 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
689 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000690 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000691 replyStatus = BAD_VALUE;
692 } else if (target->localBinder() == nullptr) {
693 ALOGE("Unknown binder address or non-local binder, not address %s. Terminating!",
694 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000695 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000696 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000697 } else if (oneway) {
Steven Morelandd45be622021-06-04 02:19:37 +0000698 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000699 auto it = mNodeForAddress.find(addr);
700 if (it->second.binder.promote() != target) {
701 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000702 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000703 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000704 } else if (transaction->asyncNumber != it->second.asyncNumber) {
705 // we need to process some other asynchronous transaction
706 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000707 it->second.asyncTodo.push(BinderNode::AsyncTodo{
708 .ref = target,
709 .data = std::move(transactionData),
710 .asyncNumber = transaction->asyncNumber,
711 });
Steven Morelandd45be622021-06-04 02:19:37 +0000712
713 size_t numPending = it->second.asyncTodo.size();
714 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s (%zu pending)",
715 transaction->asyncNumber, addr.toString().c_str(), numPending);
716
717 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
718 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
719 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
720
721 if (numPending >= kArbitraryOnewayCallWarnLevel) {
722 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
723 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
724 _l.unlock();
725 (void)session->shutdownAndWait(false);
726 return FAILED_TRANSACTION;
727 }
728
729 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
730 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
731 target.get(), numPending);
732 }
733 }
Steven Morelandf5174272021-05-25 00:39:28 +0000734 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000735 }
736 }
737 }
738
Steven Moreland5553ac42020-11-11 02:14:45 +0000739 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000740 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000741
742 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000743 Parcel data;
744 // transaction->data is owned by this function. Parcel borrows this data and
745 // only holds onto it for the duration of this function call. Parcel will be
746 // deleted before the 'transactionData' object.
747 data.ipcSetDataReference(transaction->data,
748 transactionData.size() - offsetof(RpcWireTransaction, data),
749 nullptr /*object*/, 0 /*objectCount*/,
750 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000751 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000752
Steven Moreland5553ac42020-11-11 02:14:45 +0000753 if (target) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000754 bool origAllowNested = connection->allowNested;
755 connection->allowNested = !oneway;
756
Steven Moreland5553ac42020-11-11 02:14:45 +0000757 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000758
759 connection->allowNested = origAllowNested;
Steven Moreland5553ac42020-11-11 02:14:45 +0000760 } else {
761 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000762
Steven Moreland103424e2021-06-02 18:16:19 +0000763 switch (transaction->code) {
764 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
765 replyStatus = reply.writeInt32(session->getMaxThreads());
766 break;
767 }
768 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
769 // for client connections, this should always report the value
770 // originally returned from the server
771 int32_t id = session->mId.value();
772 replyStatus = reply.writeInt32(id);
773 break;
774 }
775 default: {
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000776 sp<RpcServer> server = session->server();
Steven Moreland103424e2021-06-02 18:16:19 +0000777 if (server) {
778 switch (transaction->code) {
779 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
780 replyStatus = reply.writeStrongBinder(server->getRootObject());
781 break;
782 }
783 default: {
784 replyStatus = UNKNOWN_TRANSACTION;
785 }
786 }
787 } else {
788 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000789 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000790 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000791 }
792 }
793 }
794
Steven Morelandc7d40132021-06-10 03:42:11 +0000795 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000796 if (replyStatus != OK) {
797 ALOGW("Oneway call failed with error: %d", replyStatus);
798 }
799
800 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
801 addr.toString().c_str());
802
803 // Check to see if there is another asynchronous transaction to process.
804 // This behavior differs from binder behavior, since in the binder
805 // driver, asynchronous transactions will be processed after existing
806 // pending binder transactions on the queue. The downside of this is
807 // that asynchronous transactions can be drowned out by synchronous
808 // transactions. However, we have no easy way to queue these
809 // transactions after the synchronous transactions we may want to read
810 // from the wire. So, in socket binder here, we have the opposite
811 // downside: asynchronous transactions may drown out synchronous
812 // transactions.
813 {
814 std::unique_lock<std::mutex> _l(mNodeMutex);
815 auto it = mNodeForAddress.find(addr);
816 // last refcount dropped after this transaction happened
817 if (it == mNodeForAddress.end()) return OK;
818
Steven Morelandc9d7b532021-06-04 20:57:41 +0000819 if (!nodeProgressAsyncNumber(&it->second)) {
820 _l.unlock();
821 (void)session->shutdownAndWait(false);
822 return DEAD_OBJECT;
823 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000824
825 if (it->second.asyncTodo.size() == 0) return OK;
826 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
827 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
828 it->second.asyncNumber, addr.toString().c_str());
829
830 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000831 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000832 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000833 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
834
Steven Morelandada72bd2021-06-09 23:29:13 +0000835 // reset up arguments
836 transactionData = std::move(todo.data);
837 targetRef = std::move(todo.ref);
Steven Morelandf5174272021-05-25 00:39:28 +0000838
Steven Moreland5553ac42020-11-11 02:14:45 +0000839 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000840 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000841 }
842 }
843 return OK;
844 }
845
Steven Moreland77c30112021-06-02 20:45:46 +0000846 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
847 sizeof(RpcWireReply) <
848 reply.dataSize(),
849 "Too much data for reply %zu", reply.dataSize());
850
851 RpcWireHeader cmdReply{
852 .command = RPC_COMMAND_REPLY,
853 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
854 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000855 RpcWireReply rpcReply{
856 .status = replyStatus,
857 };
858
Steven Moreland77c30112021-06-02 20:45:46 +0000859 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000860 if (!replyData.valid()) {
861 return NO_MEMORY;
862 }
Steven Moreland77c30112021-06-02 20:45:46 +0000863 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
864 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
865 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
866 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000867
Steven Moreland5ae62562021-06-10 03:21:42 +0000868 return rpcSend(connection, session, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000869}
870
Steven Moreland5ae62562021-06-10 03:21:42 +0000871status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
872 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000873 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
874
Steven Morelanddbe71832021-05-12 23:31:00 +0000875 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000876 if (!commandData.valid()) {
877 return NO_MEMORY;
878 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000879 if (status_t status =
Steven Moreland5ae62562021-06-10 03:21:42 +0000880 rpcRec(connection, session, "dec ref body", commandData.data(), commandData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000881 status != OK)
882 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000883
884 if (command.bodySize < sizeof(RpcWireAddress)) {
885 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
886 sizeof(RpcWireAddress), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000887 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000888 return BAD_VALUE;
889 }
890 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
891
892 // TODO(b/182939933): heap allocation just for lookup
893 auto addr = RpcAddress::fromRawEmbedded(address);
894 std::unique_lock<std::mutex> _l(mNodeMutex);
895 auto it = mNodeForAddress.find(addr);
896 if (it == mNodeForAddress.end()) {
897 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000898 return OK;
899 }
900
901 sp<IBinder> target = it->second.binder.promote();
902 if (target == nullptr) {
903 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
904 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000905 _l.unlock();
906 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000907 return BAD_VALUE;
908 }
909
910 if (it->second.timesSent == 0) {
911 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
912 return OK;
913 }
914
915 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
916 addr.toString().c_str());
917
Steven Moreland5553ac42020-11-11 02:14:45 +0000918 it->second.timesSent--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000919 sp<IBinder> tempHold = tryEraseNode(it);
920 _l.unlock();
921 tempHold = nullptr; // destructor may make binder calls on this session
922
923 return OK;
924}
925
926sp<IBinder> RpcState::tryEraseNode(std::map<RpcAddress, BinderNode>::iterator& it) {
927 sp<IBinder> ref;
928
Steven Moreland5553ac42020-11-11 02:14:45 +0000929 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000930 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000931
932 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +0000933 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
934 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +0000935 mNodeForAddress.erase(it);
936 }
937 }
938
Steven Moreland31bde7a2021-06-04 00:57:36 +0000939 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +0000940}
941
Steven Morelandc9d7b532021-06-04 20:57:41 +0000942bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000943 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
944 // a single binder
945 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
946 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +0000947 return false;
948 }
949 node->asyncNumber++;
950 return true;
951}
952
Steven Moreland5553ac42020-11-11 02:14:45 +0000953} // namespace android