blob: 53eba5aea61f5ac906d9612b8225635728582351 [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
86 auto&& [it, inserted] = mNodeForAddress.insert({RpcAddress::unique(),
87 BinderNode{
88 .binder = binder,
89 .timesSent = 1,
90 .sentRef = binder,
91 }});
92 // TODO(b/182939933): better organization could avoid needing this log
93 LOG_ALWAYS_FATAL_IF(!inserted);
94
95 *outAddress = it->first;
96 return OK;
97}
98
Steven Moreland7227c8a2021-06-02 00:24:32 +000099status_t RpcState::onBinderEntering(const sp<RpcSession>& session, const RpcAddress& address,
100 sp<IBinder>* out) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000101 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000102 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000103
104 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000105 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000106
107 // implicitly have strong RPC refcount, since we received this binder
108 it->second.timesRecd++;
109
110 _l.unlock();
111
112 // We have timesRecd RPC refcounts, but we only need to hold on to one
113 // when we keep the object. All additional dec strongs are sent
114 // immediately, we wait to send the last one in BpBinder::onLastDecStrong.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000115 (void)session->sendDecStrong(address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000116
Steven Moreland7227c8a2021-06-02 00:24:32 +0000117 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000118 }
119
120 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
121 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
122
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000123 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000124 // device global binders in the RPC world).
Steven Moreland7227c8a2021-06-02 00:24:32 +0000125 it->second.binder = *out = BpBinder::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000126 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000127 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000128}
129
130size_t RpcState::countBinders() {
131 std::lock_guard<std::mutex> _l(mNodeMutex);
132 return mNodeForAddress.size();
133}
134
135void RpcState::dump() {
136 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000137 dumpLocked();
138}
139
Steven Morelandc9d7b532021-06-04 20:57:41 +0000140void RpcState::clear() {
Steven Moreland583a14a2021-06-04 02:04:58 +0000141 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000142
143 if (mTerminated) {
144 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
145 "New state should be impossible after terminating!");
146 return;
147 }
148
149 if (SHOULD_LOG_RPC_DETAIL) {
150 ALOGE("RpcState::clear()");
151 dumpLocked();
152 }
153
154 // if the destructor of a binder object makes another RPC call, then calling
155 // decStrong could deadlock. So, we must hold onto these binders until
156 // mNodeMutex is no longer taken.
157 std::vector<sp<IBinder>> tempHoldBinder;
158
159 mTerminated = true;
160 for (auto& [address, node] : mNodeForAddress) {
161 sp<IBinder> binder = node.binder.promote();
162 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
163
164 if (node.sentRef != nullptr) {
165 tempHoldBinder.push_back(node.sentRef);
166 }
167 }
168
169 mNodeForAddress.clear();
170
171 _l.unlock();
172 tempHoldBinder.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000173}
174
175void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000176 ALOGE("DUMP OF RpcState %p", this);
177 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
178 for (const auto& [address, node] : mNodeForAddress) {
179 sp<IBinder> binder = node.binder.promote();
180
181 const char* desc;
182 if (binder) {
183 if (binder->remoteBinder()) {
184 if (binder->remoteBinder()->isRpcBinder()) {
185 desc = "(rpc binder proxy)";
186 } else {
187 desc = "(binder proxy)";
188 }
189 } else {
190 desc = "(local binder)";
191 }
192 } else {
193 desc = "(null)";
194 }
195
196 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a:%s type:%s",
197 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address.toString().c_str(),
198 desc);
199 }
200 ALOGE("END DUMP OF RpcState");
201}
202
Steven Moreland5553ac42020-11-11 02:14:45 +0000203
Steven Morelanddbe71832021-05-12 23:31:00 +0000204RpcState::CommandData::CommandData(size_t size) : mSize(size) {
205 // The maximum size for regular binder is 1MB for all concurrent
206 // transactions. A very small proportion of transactions are even
207 // larger than a page, but we need to avoid allocating too much
208 // data on behalf of an arbitrary client, or we could risk being in
209 // a position where a single additional allocation could run out of
210 // memory.
211 //
212 // Note, this limit may not reflect the total amount of data allocated for a
213 // transaction (in some cases, additional fixed size amounts are added),
214 // though for rough consistency, we should avoid cases where this data type
215 // is used for multiple dynamic allocations for a single transaction.
216 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
217 if (size == 0) return;
218 if (size > kMaxTransactionAllocation) {
219 ALOGW("Transaction requested too much data allocation %zu", size);
220 return;
221 }
222 mData.reset(new (std::nothrow) uint8_t[size]);
223}
224
Steven Morelandc9d7b532021-06-04 20:57:41 +0000225status_t RpcState::rpcSend(const base::unique_fd& fd, const sp<RpcSession>& session,
226 const char* what, const void* data, size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000227 LOG_RPC_DETAIL("Sending %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
228
229 if (size > std::numeric_limits<ssize_t>::max()) {
230 ALOGE("Cannot send %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000231 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000232 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000233 }
234
Steven Morelandc6ddf362021-04-02 01:13:36 +0000235 ssize_t sent = TEMP_FAILURE_RETRY(send(fd.get(), data, size, MSG_NOSIGNAL));
Steven Moreland5553ac42020-11-11 02:14:45 +0000236
237 if (sent < 0 || sent != static_cast<ssize_t>(size)) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000238 int savedErrno = errno;
Steven Morelandc12c9d92021-05-26 18:44:11 +0000239 LOG_RPC_DETAIL("Failed to send %s (sent %zd of %zu bytes) on fd %d, error: %s", what, sent,
240 size, fd.get(), strerror(savedErrno));
Steven Moreland5553ac42020-11-11 02:14:45 +0000241
Steven Morelandc9d7b532021-06-04 20:57:41 +0000242 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000243 return -savedErrno;
Steven Moreland5553ac42020-11-11 02:14:45 +0000244 }
245
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000246 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000247}
248
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000249status_t RpcState::rpcRec(const base::unique_fd& fd, const sp<RpcSession>& session,
250 const char* what, void* data, size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000251 if (size > std::numeric_limits<ssize_t>::max()) {
252 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000253 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000254 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000255 }
256
Steven Morelandee3f4662021-05-22 01:07:33 +0000257 if (status_t status = session->mShutdownTrigger->interruptableReadFully(fd.get(), data, size);
258 status != OK) {
Steven Morelandc12c9d92021-05-26 18:44:11 +0000259 LOG_RPC_DETAIL("Failed to read %s (%zu bytes) on fd %d, error: %s", what, size, fd.get(),
260 statusToString(status).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000261 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000262 }
263
Steven Morelandee3f4662021-05-22 01:07:33 +0000264 LOG_RPC_DETAIL("Received %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000265 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000266}
267
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000268status_t RpcState::sendConnectionInit(const base::unique_fd& fd, const sp<RpcSession>& session) {
269 RpcClientConnectionInit init{
270 .msg = RPC_CONNECTION_INIT_OKAY,
271 };
272 return rpcSend(fd, session, "connection init", &init, sizeof(init));
273}
274
275status_t RpcState::readConnectionInit(const base::unique_fd& fd, const sp<RpcSession>& session) {
276 RpcClientConnectionInit init;
277 if (status_t status = rpcRec(fd, session, "connection init", &init, sizeof(init)); status != OK)
278 return status;
279
280 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
281 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
282 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
283 init.msg);
284 return BAD_VALUE;
285 }
286 return OK;
287}
288
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000289sp<IBinder> RpcState::getRootObject(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000290 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000291 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000292 Parcel reply;
293
Steven Morelandf5174272021-05-25 00:39:28 +0000294 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT, data,
295 session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000296 if (status != OK) {
297 ALOGE("Error getting root object: %s", statusToString(status).c_str());
298 return nullptr;
299 }
300
301 return reply.readStrongBinder();
302}
303
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000304status_t RpcState::getMaxThreads(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000305 size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000306 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000307 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000308 Parcel reply;
309
Steven Morelandf5174272021-05-25 00:39:28 +0000310 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS,
311 data, session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000312 if (status != OK) {
313 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
314 return status;
315 }
316
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000317 int32_t maxThreads;
318 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000319 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000320 if (maxThreads <= 0) {
321 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000322 return BAD_VALUE;
323 }
324
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000325 *maxThreadsOut = maxThreads;
326 return OK;
327}
328
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000329status_t RpcState::getSessionId(const base::unique_fd& fd, const sp<RpcSession>& session,
330 int32_t* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000331 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000332 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000333 Parcel reply;
334
Steven Morelandf5174272021-05-25 00:39:28 +0000335 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_SESSION_ID,
336 data, session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000337 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000338 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000339 return status;
340 }
341
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000342 int32_t sessionId;
343 status = reply.readInt32(&sessionId);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000344 if (status != OK) return status;
345
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000346 *sessionIdOut = sessionId;
Steven Morelandf137de92021-04-24 01:54:26 +0000347 return OK;
348}
349
Steven Morelandf5174272021-05-25 00:39:28 +0000350status_t RpcState::transact(const base::unique_fd& fd, const sp<IBinder>& binder, uint32_t code,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000351 const Parcel& data, const sp<RpcSession>& session, Parcel* reply,
Steven Moreland5553ac42020-11-11 02:14:45 +0000352 uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000353 if (!data.isForRpc()) {
354 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
355 return BAD_TYPE;
356 }
357
358 if (data.objectsCount() != 0) {
359 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
360 return BAD_TYPE;
361 }
362
363 RpcAddress address = RpcAddress::zero();
364 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
365
366 return transactAddress(fd, address, code, data, session, reply, flags);
367}
368
369status_t RpcState::transactAddress(const base::unique_fd& fd, const RpcAddress& address,
370 uint32_t code, const Parcel& data, const sp<RpcSession>& session,
371 Parcel* reply, uint32_t flags) {
372 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
373 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
374
Steven Moreland5553ac42020-11-11 02:14:45 +0000375 uint64_t asyncNumber = 0;
376
377 if (!address.isZero()) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000378 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000379 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
380 auto it = mNodeForAddress.find(address);
381 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
382 address.toString().c_str());
383
384 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000385 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000386 if (!nodeProgressAsyncNumber(&it->second)) {
387 _l.unlock();
388 (void)session->shutdownAndWait(false);
389 return DEAD_OBJECT;
390 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000391 }
392 }
393
Steven Moreland77c30112021-06-02 20:45:46 +0000394 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
395 sizeof(RpcWireTransaction) <
396 data.dataSize(),
397 "Too much data %zu", data.dataSize());
398
399 RpcWireHeader command{
400 .command = RPC_COMMAND_TRANSACT,
401 .bodySize = static_cast<uint32_t>(sizeof(RpcWireTransaction) + data.dataSize()),
402 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000403 RpcWireTransaction transaction{
404 .address = address.viewRawEmbedded(),
405 .code = code,
406 .flags = flags,
407 .asyncNumber = asyncNumber,
408 };
Steven Moreland77c30112021-06-02 20:45:46 +0000409 CommandData transactionData(sizeof(RpcWireHeader) + sizeof(RpcWireTransaction) +
410 data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000411 if (!transactionData.valid()) {
412 return NO_MEMORY;
413 }
414
Steven Moreland77c30112021-06-02 20:45:46 +0000415 memcpy(transactionData.data() + 0, &command, sizeof(RpcWireHeader));
416 memcpy(transactionData.data() + sizeof(RpcWireHeader), &transaction,
417 sizeof(RpcWireTransaction));
418 memcpy(transactionData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireTransaction), data.data(),
419 data.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000420
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000421 if (status_t status =
Steven Morelandc9d7b532021-06-04 20:57:41 +0000422 rpcSend(fd, session, "transaction", transactionData.data(), transactionData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000423 status != OK)
Steven Morelanda5036f02021-06-08 02:26:57 +0000424 // TODO(b/167966510): need to undo onBinderLeaving - we know the
425 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000426 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000427
428 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland659416d2021-05-11 00:47:50 +0000429 LOG_RPC_DETAIL("Oneway command, so no longer waiting on %d", fd.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000430
431 // Do not wait on result.
432 // However, too many oneway calls may cause refcounts to build up and fill up the socket,
433 // so process those.
434 return drainCommands(fd, session, CommandType::CONTROL_ONLY);
Steven Moreland5553ac42020-11-11 02:14:45 +0000435 }
436
437 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
438
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000439 return waitForReply(fd, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000440}
441
Steven Moreland438cce82021-04-02 18:04:08 +0000442static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
443 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000444 (void)p;
445 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
446 (void)dataSize;
447 LOG_ALWAYS_FATAL_IF(objects != nullptr);
448 LOG_ALWAYS_FATAL_IF(objectsCount, 0);
449}
450
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000451status_t RpcState::waitForReply(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000452 Parcel* reply) {
453 RpcWireHeader command;
454 while (true) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000455 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
456 status != OK)
457 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000458
459 if (command.command == RPC_COMMAND_REPLY) break;
460
Steven Moreland52eee942021-06-03 00:59:28 +0000461 if (status_t status = processServerCommand(fd, session, command, CommandType::ANY);
462 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000463 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000464 }
465
Steven Morelanddbe71832021-05-12 23:31:00 +0000466 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000467 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000468
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000469 if (status_t status = rpcRec(fd, session, "reply body", data.data(), command.bodySize);
470 status != OK)
471 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000472
473 if (command.bodySize < sizeof(RpcWireReply)) {
474 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
475 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000476 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000477 return BAD_VALUE;
478 }
Steven Morelande8393342021-05-05 23:27:53 +0000479 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000480 if (rpcReply->status != OK) return rpcReply->status;
481
Steven Morelande8393342021-05-05 23:27:53 +0000482 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000483 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000484 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000485
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000486 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000487
488 return OK;
489}
490
Steven Morelandc9d7b532021-06-04 20:57:41 +0000491status_t RpcState::sendDecStrong(const base::unique_fd& fd, const sp<RpcSession>& session,
492 const RpcAddress& addr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000493 {
494 std::lock_guard<std::mutex> _l(mNodeMutex);
495 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
496 auto it = mNodeForAddress.find(addr);
497 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
498 addr.toString().c_str());
499 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
500 addr.toString().c_str());
501
502 it->second.timesRecd--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000503 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
504 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000505 }
506
507 RpcWireHeader cmd = {
508 .command = RPC_COMMAND_DEC_STRONG,
509 .bodySize = sizeof(RpcWireAddress),
510 };
Steven Morelandc9d7b532021-06-04 20:57:41 +0000511 if (status_t status = rpcSend(fd, session, "dec ref header", &cmd, sizeof(cmd)); status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000512 return status;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000513 if (status_t status = rpcSend(fd, session, "dec ref body", &addr.viewRawEmbedded(),
514 sizeof(RpcWireAddress));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000515 status != OK)
516 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000517 return OK;
518}
519
Steven Moreland52eee942021-06-03 00:59:28 +0000520status_t RpcState::getAndExecuteCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
521 CommandType type) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000522 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", fd.get());
523
524 RpcWireHeader command;
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000525 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
526 status != OK)
527 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000528
Steven Moreland52eee942021-06-03 00:59:28 +0000529 return processServerCommand(fd, session, command, type);
530}
531
532status_t RpcState::drainCommands(const base::unique_fd& fd, const sp<RpcSession>& session,
533 CommandType type) {
534 uint8_t buf;
535 while (0 < TEMP_FAILURE_RETRY(recv(fd.get(), &buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT))) {
536 status_t status = getAndExecuteCommand(fd, session, type);
537 if (status != OK) return status;
538 }
539 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000540}
541
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000542status_t RpcState::processServerCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland52eee942021-06-03 00:59:28 +0000543 const RpcWireHeader& command, CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000544 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
545 IPCThreadState::SpGuard spGuard{
546 .address = __builtin_frame_address(0),
547 .context = "processing binder RPC command",
548 };
549 const IPCThreadState::SpGuard* origGuard;
550 if (kernelBinderState != nullptr) {
551 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
552 }
553 ScopeGuard guardUnguard = [&]() {
554 if (kernelBinderState != nullptr) {
555 kernelBinderState->restoreGetCallingSpGuard(origGuard);
556 }
557 };
558
Steven Moreland5553ac42020-11-11 02:14:45 +0000559 switch (command.command) {
560 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000561 if (type != CommandType::ANY) return BAD_TYPE;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000562 return processTransact(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000563 case RPC_COMMAND_DEC_STRONG:
Steven Morelandee3f4662021-05-22 01:07:33 +0000564 return processDecStrong(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000565 }
566
567 // We should always know the version of the opposing side, and since the
568 // RPC-binder-level wire protocol is not self synchronizing, we have no way
569 // to understand where the current command ends and the next one begins. We
570 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000571 // to kill us, so ending the session for misbehaving client.
572 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000573 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000574 return DEAD_OBJECT;
575}
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000576status_t RpcState::processTransact(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000577 const RpcWireHeader& command) {
578 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
579
Steven Morelanddbe71832021-05-12 23:31:00 +0000580 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000581 if (!transactionData.valid()) {
582 return NO_MEMORY;
583 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000584 if (status_t status = rpcRec(fd, session, "transaction body", transactionData.data(),
585 transactionData.size());
586 status != OK)
587 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000588
Steven Morelandada72bd2021-06-09 23:29:13 +0000589 return processTransactInternal(fd, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000590}
591
Steven Moreland438cce82021-04-02 18:04:08 +0000592static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
593 const binder_size_t* objects, size_t objectsCount) {
594 (void)p;
595 (void)data;
596 (void)dataSize;
597 (void)objects;
598 (void)objectsCount;
599}
600
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000601status_t RpcState::processTransactInternal(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000602 CommandData transactionData) {
603 // for 'recursive' calls to this, we have already read and processed the
604 // binder from the transaction data and taken reference counts into account,
605 // so it is cached here.
606 sp<IBinder> targetRef;
607processTransactInternalTailCall:
608
Steven Moreland5553ac42020-11-11 02:14:45 +0000609 if (transactionData.size() < sizeof(RpcWireTransaction)) {
610 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
611 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000612 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000613 return BAD_VALUE;
614 }
615 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
616
617 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
618 // maybe add an RpcAddress 'view' if the type remains 'heavy'
619 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
620
621 status_t replyStatus = OK;
622 sp<IBinder> target;
623 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000624 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000625 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000626 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000627 target = targetRef;
628 }
629
Steven Moreland7227c8a2021-06-02 00:24:32 +0000630 if (replyStatus != OK) {
631 // do nothing
632 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000633 // This can happen if the binder is remote in this process, and
634 // another thread has called the last decStrong on this binder.
635 // However, for local binders, it indicates a misbehaving client
636 // (any binder which is being transacted on should be holding a
637 // strong ref count), so in either case, terminating the
638 // session.
639 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
640 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000641 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000642 replyStatus = BAD_VALUE;
643 } else if (target->localBinder() == nullptr) {
644 ALOGE("Unknown binder address or non-local binder, not address %s. Terminating!",
645 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000646 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000647 replyStatus = BAD_VALUE;
648 } else if (transaction->flags & IBinder::FLAG_ONEWAY) {
Steven Morelandd45be622021-06-04 02:19:37 +0000649 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000650 auto it = mNodeForAddress.find(addr);
651 if (it->second.binder.promote() != target) {
652 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000653 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000654 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000655 } else if (transaction->asyncNumber != it->second.asyncNumber) {
656 // we need to process some other asynchronous transaction
657 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000658 it->second.asyncTodo.push(BinderNode::AsyncTodo{
659 .ref = target,
660 .data = std::move(transactionData),
661 .asyncNumber = transaction->asyncNumber,
662 });
Steven Morelandd45be622021-06-04 02:19:37 +0000663
664 size_t numPending = it->second.asyncTodo.size();
665 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s (%zu pending)",
666 transaction->asyncNumber, addr.toString().c_str(), numPending);
667
668 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
669 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
670 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
671
672 if (numPending >= kArbitraryOnewayCallWarnLevel) {
673 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
674 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
675 _l.unlock();
676 (void)session->shutdownAndWait(false);
677 return FAILED_TRANSACTION;
678 }
679
680 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
681 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
682 target.get(), numPending);
683 }
684 }
Steven Morelandf5174272021-05-25 00:39:28 +0000685 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000686 }
687 }
688 }
689
Steven Moreland5553ac42020-11-11 02:14:45 +0000690 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000691 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000692
693 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000694 Parcel data;
695 // transaction->data is owned by this function. Parcel borrows this data and
696 // only holds onto it for the duration of this function call. Parcel will be
697 // deleted before the 'transactionData' object.
698 data.ipcSetDataReference(transaction->data,
699 transactionData.size() - offsetof(RpcWireTransaction, data),
700 nullptr /*object*/, 0 /*objectCount*/,
701 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000702 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000703
Steven Moreland5553ac42020-11-11 02:14:45 +0000704 if (target) {
705 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
706 } else {
707 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000708
Steven Moreland103424e2021-06-02 18:16:19 +0000709 switch (transaction->code) {
710 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
711 replyStatus = reply.writeInt32(session->getMaxThreads());
712 break;
713 }
714 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
715 // for client connections, this should always report the value
716 // originally returned from the server
717 int32_t id = session->mId.value();
718 replyStatus = reply.writeInt32(id);
719 break;
720 }
721 default: {
722 sp<RpcServer> server = session->server().promote();
723 if (server) {
724 switch (transaction->code) {
725 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
726 replyStatus = reply.writeStrongBinder(server->getRootObject());
727 break;
728 }
729 default: {
730 replyStatus = UNKNOWN_TRANSACTION;
731 }
732 }
733 } else {
734 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000735 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000736 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000737 }
738 }
739 }
740
741 if (transaction->flags & IBinder::FLAG_ONEWAY) {
742 if (replyStatus != OK) {
743 ALOGW("Oneway call failed with error: %d", replyStatus);
744 }
745
746 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
747 addr.toString().c_str());
748
749 // Check to see if there is another asynchronous transaction to process.
750 // This behavior differs from binder behavior, since in the binder
751 // driver, asynchronous transactions will be processed after existing
752 // pending binder transactions on the queue. The downside of this is
753 // that asynchronous transactions can be drowned out by synchronous
754 // transactions. However, we have no easy way to queue these
755 // transactions after the synchronous transactions we may want to read
756 // from the wire. So, in socket binder here, we have the opposite
757 // downside: asynchronous transactions may drown out synchronous
758 // transactions.
759 {
760 std::unique_lock<std::mutex> _l(mNodeMutex);
761 auto it = mNodeForAddress.find(addr);
762 // last refcount dropped after this transaction happened
763 if (it == mNodeForAddress.end()) return OK;
764
Steven Morelandc9d7b532021-06-04 20:57:41 +0000765 if (!nodeProgressAsyncNumber(&it->second)) {
766 _l.unlock();
767 (void)session->shutdownAndWait(false);
768 return DEAD_OBJECT;
769 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000770
771 if (it->second.asyncTodo.size() == 0) return OK;
772 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
773 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
774 it->second.asyncNumber, addr.toString().c_str());
775
776 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000777 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000778 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000779 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
780
Steven Morelandada72bd2021-06-09 23:29:13 +0000781 // reset up arguments
782 transactionData = std::move(todo.data);
783 targetRef = std::move(todo.ref);
Steven Morelandf5174272021-05-25 00:39:28 +0000784
Steven Moreland5553ac42020-11-11 02:14:45 +0000785 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000786 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000787 }
788 }
789 return OK;
790 }
791
Steven Moreland77c30112021-06-02 20:45:46 +0000792 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
793 sizeof(RpcWireReply) <
794 reply.dataSize(),
795 "Too much data for reply %zu", reply.dataSize());
796
797 RpcWireHeader cmdReply{
798 .command = RPC_COMMAND_REPLY,
799 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
800 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000801 RpcWireReply rpcReply{
802 .status = replyStatus,
803 };
804
Steven Moreland77c30112021-06-02 20:45:46 +0000805 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000806 if (!replyData.valid()) {
807 return NO_MEMORY;
808 }
Steven Moreland77c30112021-06-02 20:45:46 +0000809 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
810 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
811 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
812 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000813
Steven Morelandc9d7b532021-06-04 20:57:41 +0000814 return rpcSend(fd, session, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000815}
816
Steven Morelandee3f4662021-05-22 01:07:33 +0000817status_t RpcState::processDecStrong(const base::unique_fd& fd, const sp<RpcSession>& session,
818 const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000819 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
820
Steven Morelanddbe71832021-05-12 23:31:00 +0000821 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000822 if (!commandData.valid()) {
823 return NO_MEMORY;
824 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000825 if (status_t status =
826 rpcRec(fd, session, "dec ref body", commandData.data(), commandData.size());
827 status != OK)
828 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000829
830 if (command.bodySize < sizeof(RpcWireAddress)) {
831 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
832 sizeof(RpcWireAddress), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000833 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000834 return BAD_VALUE;
835 }
836 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
837
838 // TODO(b/182939933): heap allocation just for lookup
839 auto addr = RpcAddress::fromRawEmbedded(address);
840 std::unique_lock<std::mutex> _l(mNodeMutex);
841 auto it = mNodeForAddress.find(addr);
842 if (it == mNodeForAddress.end()) {
843 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000844 return OK;
845 }
846
847 sp<IBinder> target = it->second.binder.promote();
848 if (target == nullptr) {
849 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
850 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000851 _l.unlock();
852 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000853 return BAD_VALUE;
854 }
855
856 if (it->second.timesSent == 0) {
857 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
858 return OK;
859 }
860
861 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
862 addr.toString().c_str());
863
Steven Moreland5553ac42020-11-11 02:14:45 +0000864 it->second.timesSent--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000865 sp<IBinder> tempHold = tryEraseNode(it);
866 _l.unlock();
867 tempHold = nullptr; // destructor may make binder calls on this session
868
869 return OK;
870}
871
872sp<IBinder> RpcState::tryEraseNode(std::map<RpcAddress, BinderNode>::iterator& it) {
873 sp<IBinder> ref;
874
Steven Moreland5553ac42020-11-11 02:14:45 +0000875 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000876 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000877
878 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +0000879 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
880 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +0000881 mNodeForAddress.erase(it);
882 }
883 }
884
Steven Moreland31bde7a2021-06-04 00:57:36 +0000885 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +0000886}
887
Steven Morelandc9d7b532021-06-04 20:57:41 +0000888bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000889 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
890 // a single binder
891 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
892 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +0000893 return false;
894 }
895 node->asyncNumber++;
896 return true;
897}
898
Steven Moreland5553ac42020-11-11 02:14:45 +0000899} // namespace android