blob: fd2eff68701bd3900580430bf7c597b795853411 [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,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000372 const sp<RpcSession>& session, RpcAddress* 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 Moreland01a6bad2021-06-11 00:59:20 +0000385 return sessionIdOut->readFromParcel(reply);
Steven Morelandf137de92021-04-24 01:54:26 +0000386}
387
Steven Moreland5ae62562021-06-10 03:21:42 +0000388status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
389 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
390 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000391 if (!data.isForRpc()) {
392 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
393 return BAD_TYPE;
394 }
395
396 if (data.objectsCount() != 0) {
397 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
398 return BAD_TYPE;
399 }
400
401 RpcAddress address = RpcAddress::zero();
402 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
403
Steven Moreland5ae62562021-06-10 03:21:42 +0000404 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000405}
406
Steven Moreland5ae62562021-06-10 03:21:42 +0000407status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
408 const RpcAddress& address, uint32_t code, const Parcel& data,
409 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000410 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
411 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
412
Steven Moreland5553ac42020-11-11 02:14:45 +0000413 uint64_t asyncNumber = 0;
414
415 if (!address.isZero()) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000416 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000417 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
418 auto it = mNodeForAddress.find(address);
419 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
420 address.toString().c_str());
421
422 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000423 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000424 if (!nodeProgressAsyncNumber(&it->second)) {
425 _l.unlock();
426 (void)session->shutdownAndWait(false);
427 return DEAD_OBJECT;
428 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000429 }
430 }
431
Steven Moreland77c30112021-06-02 20:45:46 +0000432 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
433 sizeof(RpcWireTransaction) <
434 data.dataSize(),
435 "Too much data %zu", data.dataSize());
436
437 RpcWireHeader command{
438 .command = RPC_COMMAND_TRANSACT,
439 .bodySize = static_cast<uint32_t>(sizeof(RpcWireTransaction) + data.dataSize()),
440 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000441 RpcWireTransaction transaction{
442 .address = address.viewRawEmbedded(),
443 .code = code,
444 .flags = flags,
445 .asyncNumber = asyncNumber,
446 };
Steven Moreland77c30112021-06-02 20:45:46 +0000447 CommandData transactionData(sizeof(RpcWireHeader) + sizeof(RpcWireTransaction) +
448 data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000449 if (!transactionData.valid()) {
450 return NO_MEMORY;
451 }
452
Steven Moreland77c30112021-06-02 20:45:46 +0000453 memcpy(transactionData.data() + 0, &command, sizeof(RpcWireHeader));
454 memcpy(transactionData.data() + sizeof(RpcWireHeader), &transaction,
455 sizeof(RpcWireTransaction));
456 memcpy(transactionData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireTransaction), data.data(),
457 data.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000458
Steven Moreland5ae62562021-06-10 03:21:42 +0000459 if (status_t status = rpcSend(connection, session, "transaction", transactionData.data(),
460 transactionData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000461 status != OK)
Steven Morelanda5036f02021-06-08 02:26:57 +0000462 // TODO(b/167966510): need to undo onBinderLeaving - we know the
463 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000464 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000465
466 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000467 LOG_RPC_DETAIL("Oneway command, so no longer waiting on %d", connection->fd.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000468
469 // Do not wait on result.
470 // However, too many oneway calls may cause refcounts to build up and fill up the socket,
471 // so process those.
Steven Moreland5ae62562021-06-10 03:21:42 +0000472 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
Steven Moreland5553ac42020-11-11 02:14:45 +0000473 }
474
475 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
476
Steven Moreland5ae62562021-06-10 03:21:42 +0000477 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000478}
479
Steven Moreland438cce82021-04-02 18:04:08 +0000480static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
481 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000482 (void)p;
483 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
484 (void)dataSize;
485 LOG_ALWAYS_FATAL_IF(objects != nullptr);
486 LOG_ALWAYS_FATAL_IF(objectsCount, 0);
487}
488
Steven Moreland5ae62562021-06-10 03:21:42 +0000489status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
490 const sp<RpcSession>& session, Parcel* reply) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000491 RpcWireHeader command;
492 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000493 if (status_t status =
494 rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000495 status != OK)
496 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000497
498 if (command.command == RPC_COMMAND_REPLY) break;
499
Steven Moreland19fc9f72021-06-10 03:57:30 +0000500 if (status_t status = processCommand(connection, session, command, CommandType::ANY);
Steven Moreland52eee942021-06-03 00:59:28 +0000501 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000502 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000503 }
504
Steven Morelanddbe71832021-05-12 23:31:00 +0000505 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000506 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000507
Steven Moreland5ae62562021-06-10 03:21:42 +0000508 if (status_t status = rpcRec(connection, session, "reply body", data.data(), command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000509 status != OK)
510 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000511
512 if (command.bodySize < sizeof(RpcWireReply)) {
513 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
514 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000515 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000516 return BAD_VALUE;
517 }
Steven Morelande8393342021-05-05 23:27:53 +0000518 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000519 if (rpcReply->status != OK) return rpcReply->status;
520
Steven Morelande8393342021-05-05 23:27:53 +0000521 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000522 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000523 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000524
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000525 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000526
527 return OK;
528}
529
Steven Moreland5ae62562021-06-10 03:21:42 +0000530status_t RpcState::sendDecStrong(const sp<RpcSession::RpcConnection>& connection,
531 const sp<RpcSession>& session, const RpcAddress& addr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000532 {
533 std::lock_guard<std::mutex> _l(mNodeMutex);
534 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
535 auto it = mNodeForAddress.find(addr);
536 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
537 addr.toString().c_str());
538 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
539 addr.toString().c_str());
540
541 it->second.timesRecd--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000542 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
543 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000544 }
545
546 RpcWireHeader cmd = {
547 .command = RPC_COMMAND_DEC_STRONG,
548 .bodySize = sizeof(RpcWireAddress),
549 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000550 if (status_t status = rpcSend(connection, session, "dec ref header", &cmd, sizeof(cmd));
551 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000552 return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000553 if (status_t status = rpcSend(connection, session, "dec ref body", &addr.viewRawEmbedded(),
Steven Morelandc9d7b532021-06-04 20:57:41 +0000554 sizeof(RpcWireAddress));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000555 status != OK)
556 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000557 return OK;
558}
559
Steven Moreland5ae62562021-06-10 03:21:42 +0000560status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
561 const sp<RpcSession>& session, CommandType type) {
562 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", connection->fd.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000563
564 RpcWireHeader command;
Steven Moreland5ae62562021-06-10 03:21:42 +0000565 if (status_t status = rpcRec(connection, session, "command header", &command, sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000566 status != OK)
567 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000568
Steven Moreland19fc9f72021-06-10 03:57:30 +0000569 return processCommand(connection, session, command, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000570}
571
Steven Moreland5ae62562021-06-10 03:21:42 +0000572status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
573 const sp<RpcSession>& session, CommandType type) {
Steven Moreland52eee942021-06-03 00:59:28 +0000574 uint8_t buf;
Steven Moreland5ae62562021-06-10 03:21:42 +0000575 while (0 < TEMP_FAILURE_RETRY(
576 recv(connection->fd.get(), &buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT))) {
577 status_t status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000578 if (status != OK) return status;
579 }
580 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000581}
582
Steven Moreland19fc9f72021-06-10 03:57:30 +0000583status_t RpcState::processCommand(const sp<RpcSession::RpcConnection>& connection,
584 const sp<RpcSession>& session, const RpcWireHeader& command,
585 CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000586 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
587 IPCThreadState::SpGuard spGuard{
588 .address = __builtin_frame_address(0),
589 .context = "processing binder RPC command",
590 };
591 const IPCThreadState::SpGuard* origGuard;
592 if (kernelBinderState != nullptr) {
593 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
594 }
595 ScopeGuard guardUnguard = [&]() {
596 if (kernelBinderState != nullptr) {
597 kernelBinderState->restoreGetCallingSpGuard(origGuard);
598 }
599 };
600
Steven Moreland5553ac42020-11-11 02:14:45 +0000601 switch (command.command) {
602 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000603 if (type != CommandType::ANY) return BAD_TYPE;
Steven Moreland5ae62562021-06-10 03:21:42 +0000604 return processTransact(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000605 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000606 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000607 }
608
609 // We should always know the version of the opposing side, and since the
610 // RPC-binder-level wire protocol is not self synchronizing, we have no way
611 // to understand where the current command ends and the next one begins. We
612 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000613 // to kill us, so ending the session for misbehaving client.
614 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000615 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000616 return DEAD_OBJECT;
617}
Steven Moreland5ae62562021-06-10 03:21:42 +0000618status_t RpcState::processTransact(const sp<RpcSession::RpcConnection>& connection,
619 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000620 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
621
Steven Morelanddbe71832021-05-12 23:31:00 +0000622 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000623 if (!transactionData.valid()) {
624 return NO_MEMORY;
625 }
Steven Moreland5ae62562021-06-10 03:21:42 +0000626 if (status_t status = rpcRec(connection, session, "transaction body", transactionData.data(),
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000627 transactionData.size());
628 status != OK)
629 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000630
Steven Moreland5ae62562021-06-10 03:21:42 +0000631 return processTransactInternal(connection, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000632}
633
Steven Moreland438cce82021-04-02 18:04:08 +0000634static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
635 const binder_size_t* objects, size_t objectsCount) {
636 (void)p;
637 (void)data;
638 (void)dataSize;
639 (void)objects;
640 (void)objectsCount;
641}
642
Steven Moreland5ae62562021-06-10 03:21:42 +0000643status_t RpcState::processTransactInternal(const sp<RpcSession::RpcConnection>& connection,
644 const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000645 CommandData transactionData) {
646 // for 'recursive' calls to this, we have already read and processed the
647 // binder from the transaction data and taken reference counts into account,
648 // so it is cached here.
649 sp<IBinder> targetRef;
650processTransactInternalTailCall:
651
Steven Moreland5553ac42020-11-11 02:14:45 +0000652 if (transactionData.size() < sizeof(RpcWireTransaction)) {
653 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
654 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000655 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000656 return BAD_VALUE;
657 }
658 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
659
660 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
661 // maybe add an RpcAddress 'view' if the type remains 'heavy'
662 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000663 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000664
665 status_t replyStatus = OK;
666 sp<IBinder> target;
667 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000668 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000669 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000670 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000671 target = targetRef;
672 }
673
Steven Moreland7227c8a2021-06-02 00:24:32 +0000674 if (replyStatus != OK) {
675 // do nothing
676 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000677 // This can happen if the binder is remote in this process, and
678 // another thread has called the last decStrong on this binder.
679 // However, for local binders, it indicates a misbehaving client
680 // (any binder which is being transacted on should be holding a
681 // strong ref count), so in either case, terminating the
682 // session.
683 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
684 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000685 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000686 replyStatus = BAD_VALUE;
687 } else if (target->localBinder() == nullptr) {
688 ALOGE("Unknown binder address or non-local binder, not 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;
Steven Morelandc7d40132021-06-10 03:42:11 +0000692 } else if (oneway) {
Steven Morelandd45be622021-06-04 02:19:37 +0000693 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000694 auto it = mNodeForAddress.find(addr);
695 if (it->second.binder.promote() != target) {
696 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000697 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000698 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000699 } else if (transaction->asyncNumber != it->second.asyncNumber) {
700 // we need to process some other asynchronous transaction
701 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000702 it->second.asyncTodo.push(BinderNode::AsyncTodo{
703 .ref = target,
704 .data = std::move(transactionData),
705 .asyncNumber = transaction->asyncNumber,
706 });
Steven Morelandd45be622021-06-04 02:19:37 +0000707
708 size_t numPending = it->second.asyncTodo.size();
709 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s (%zu pending)",
710 transaction->asyncNumber, addr.toString().c_str(), numPending);
711
712 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
713 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
714 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
715
716 if (numPending >= kArbitraryOnewayCallWarnLevel) {
717 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
718 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
719 _l.unlock();
720 (void)session->shutdownAndWait(false);
721 return FAILED_TRANSACTION;
722 }
723
724 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
725 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
726 target.get(), numPending);
727 }
728 }
Steven Morelandf5174272021-05-25 00:39:28 +0000729 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000730 }
731 }
732 }
733
Steven Moreland5553ac42020-11-11 02:14:45 +0000734 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000735 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000736
737 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000738 Parcel data;
739 // transaction->data is owned by this function. Parcel borrows this data and
740 // only holds onto it for the duration of this function call. Parcel will be
741 // deleted before the 'transactionData' object.
742 data.ipcSetDataReference(transaction->data,
743 transactionData.size() - offsetof(RpcWireTransaction, data),
744 nullptr /*object*/, 0 /*objectCount*/,
745 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000746 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000747
Steven Moreland5553ac42020-11-11 02:14:45 +0000748 if (target) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000749 bool origAllowNested = connection->allowNested;
750 connection->allowNested = !oneway;
751
Steven Moreland5553ac42020-11-11 02:14:45 +0000752 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000753
754 connection->allowNested = origAllowNested;
Steven Moreland5553ac42020-11-11 02:14:45 +0000755 } else {
756 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000757
Steven Moreland103424e2021-06-02 18:16:19 +0000758 switch (transaction->code) {
759 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
760 replyStatus = reply.writeInt32(session->getMaxThreads());
761 break;
762 }
763 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
764 // for client connections, this should always report the value
Steven Moreland01a6bad2021-06-11 00:59:20 +0000765 // originally returned from the server, so this is asserting
766 // that it exists
767 replyStatus = session->mId.value().writeToParcel(&reply);
Steven Moreland103424e2021-06-02 18:16:19 +0000768 break;
769 }
770 default: {
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000771 sp<RpcServer> server = session->server();
Steven Moreland103424e2021-06-02 18:16:19 +0000772 if (server) {
773 switch (transaction->code) {
774 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
775 replyStatus = reply.writeStrongBinder(server->getRootObject());
776 break;
777 }
778 default: {
779 replyStatus = UNKNOWN_TRANSACTION;
780 }
781 }
782 } else {
783 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000784 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000785 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000786 }
787 }
788 }
789
Steven Morelandc7d40132021-06-10 03:42:11 +0000790 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000791 if (replyStatus != OK) {
792 ALOGW("Oneway call failed with error: %d", replyStatus);
793 }
794
795 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
796 addr.toString().c_str());
797
798 // Check to see if there is another asynchronous transaction to process.
799 // This behavior differs from binder behavior, since in the binder
800 // driver, asynchronous transactions will be processed after existing
801 // pending binder transactions on the queue. The downside of this is
802 // that asynchronous transactions can be drowned out by synchronous
803 // transactions. However, we have no easy way to queue these
804 // transactions after the synchronous transactions we may want to read
805 // from the wire. So, in socket binder here, we have the opposite
806 // downside: asynchronous transactions may drown out synchronous
807 // transactions.
808 {
809 std::unique_lock<std::mutex> _l(mNodeMutex);
810 auto it = mNodeForAddress.find(addr);
811 // last refcount dropped after this transaction happened
812 if (it == mNodeForAddress.end()) return OK;
813
Steven Morelandc9d7b532021-06-04 20:57:41 +0000814 if (!nodeProgressAsyncNumber(&it->second)) {
815 _l.unlock();
816 (void)session->shutdownAndWait(false);
817 return DEAD_OBJECT;
818 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000819
820 if (it->second.asyncTodo.size() == 0) return OK;
821 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
822 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
823 it->second.asyncNumber, addr.toString().c_str());
824
825 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000826 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000827 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000828 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
829
Steven Morelandada72bd2021-06-09 23:29:13 +0000830 // reset up arguments
831 transactionData = std::move(todo.data);
832 targetRef = std::move(todo.ref);
Steven Morelandf5174272021-05-25 00:39:28 +0000833
Steven Moreland5553ac42020-11-11 02:14:45 +0000834 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000835 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000836 }
837 }
838 return OK;
839 }
840
Steven Moreland77c30112021-06-02 20:45:46 +0000841 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
842 sizeof(RpcWireReply) <
843 reply.dataSize(),
844 "Too much data for reply %zu", reply.dataSize());
845
846 RpcWireHeader cmdReply{
847 .command = RPC_COMMAND_REPLY,
848 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
849 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000850 RpcWireReply rpcReply{
851 .status = replyStatus,
852 };
853
Steven Moreland77c30112021-06-02 20:45:46 +0000854 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000855 if (!replyData.valid()) {
856 return NO_MEMORY;
857 }
Steven Moreland77c30112021-06-02 20:45:46 +0000858 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
859 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
860 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
861 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000862
Steven Moreland5ae62562021-06-10 03:21:42 +0000863 return rpcSend(connection, session, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000864}
865
Steven Moreland5ae62562021-06-10 03:21:42 +0000866status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
867 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000868 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
869
Steven Morelanddbe71832021-05-12 23:31:00 +0000870 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000871 if (!commandData.valid()) {
872 return NO_MEMORY;
873 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000874 if (status_t status =
Steven Moreland5ae62562021-06-10 03:21:42 +0000875 rpcRec(connection, session, "dec ref body", commandData.data(), commandData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000876 status != OK)
877 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000878
879 if (command.bodySize < sizeof(RpcWireAddress)) {
880 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
881 sizeof(RpcWireAddress), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000882 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000883 return BAD_VALUE;
884 }
885 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
886
887 // TODO(b/182939933): heap allocation just for lookup
888 auto addr = RpcAddress::fromRawEmbedded(address);
889 std::unique_lock<std::mutex> _l(mNodeMutex);
890 auto it = mNodeForAddress.find(addr);
891 if (it == mNodeForAddress.end()) {
892 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000893 return OK;
894 }
895
896 sp<IBinder> target = it->second.binder.promote();
897 if (target == nullptr) {
898 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
899 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000900 _l.unlock();
901 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000902 return BAD_VALUE;
903 }
904
905 if (it->second.timesSent == 0) {
906 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
907 return OK;
908 }
909
910 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
911 addr.toString().c_str());
912
Steven Moreland5553ac42020-11-11 02:14:45 +0000913 it->second.timesSent--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000914 sp<IBinder> tempHold = tryEraseNode(it);
915 _l.unlock();
916 tempHold = nullptr; // destructor may make binder calls on this session
917
918 return OK;
919}
920
921sp<IBinder> RpcState::tryEraseNode(std::map<RpcAddress, BinderNode>::iterator& it) {
922 sp<IBinder> ref;
923
Steven Moreland5553ac42020-11-11 02:14:45 +0000924 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000925 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000926
927 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +0000928 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
929 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +0000930 mNodeForAddress.erase(it);
931 }
932 }
933
Steven Moreland31bde7a2021-06-04 00:57:36 +0000934 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +0000935}
936
Steven Morelandc9d7b532021-06-04 20:57:41 +0000937bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000938 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
939 // a single binder
940 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
941 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +0000942 return false;
943 }
944 node->asyncNumber++;
945 return true;
946}
947
Steven Moreland5553ac42020-11-11 02:14:45 +0000948} // namespace android