blob: 69ada56ed02262f9a67c07c5edc68ff84e1d574d [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "RpcState"
18
19#include "RpcState.h"
20
Steven Morelandd7302072021-05-15 01:32:04 +000021#include <android-base/scopeguard.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000022#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000023#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000024#include <binder/RpcServer.h>
25
26#include "Debug.h"
27#include "RpcWireFormat.h"
28
Steven Morelandb8176792021-06-22 20:29:21 +000029#include <random>
30
Steven Moreland5553ac42020-11-11 02:14:45 +000031#include <inttypes.h>
32
33namespace android {
34
Steven Morelandd7302072021-05-15 01:32:04 +000035using base::ScopeGuard;
36
Steven Morelandb8176792021-06-22 20:29:21 +000037#ifdef RPC_FLAKE_PRONE
38void rpcMaybeWaitToFlake() {
39 static std::random_device r;
40 static std::mutex m;
41
42 unsigned num;
43 {
44 std::lock_guard<std::mutex> lock(m);
45 num = r();
46 }
47 if (num % 10 == 0) usleep(num % 1000);
48}
49#endif
50
Steven Moreland5553ac42020-11-11 02:14:45 +000051RpcState::RpcState() {}
52RpcState::~RpcState() {}
53
Steven Morelandbdb53ab2021-05-05 17:57:41 +000054status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5553ac42020-11-11 02:14:45 +000055 RpcAddress* outAddress) {
56 bool isRemote = binder->remoteBinder();
57 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
58
Steven Morelandbdb53ab2021-05-05 17:57:41 +000059 if (isRpc && binder->remoteBinder()->getPrivateAccessorForId().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000060 // We need to be able to send instructions over the socket for how to
61 // connect to a different server, and we also need to let the host
62 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000063 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000064 return INVALID_OPERATION;
65 }
66
67 if (isRemote && !isRpc) {
68 // Without additional work, this would have the effect of using this
69 // process to proxy calls from the socket over to the other process, and
70 // it would make those calls look like they come from us (not over the
71 // sockets). In order to make this work transparently like binder, we
72 // would instead need to send instructions over the socket for how to
73 // connect to the host process, and we also need to let the host process
74 // know this was happening.
75 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
76 return INVALID_OPERATION;
77 }
78
79 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000080 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +000081
82 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
83 // in RpcState
84 for (auto& [addr, node] : mNodeForAddress) {
85 if (binder == node.binder) {
86 if (isRpc) {
87 const RpcAddress& actualAddr =
88 binder->remoteBinder()->getPrivateAccessorForId().rpcAddress();
89 // TODO(b/182939933): this is only checking integrity of data structure
90 // a different data structure doesn't need this
91 LOG_ALWAYS_FATAL_IF(addr < actualAddr, "Address mismatch");
92 LOG_ALWAYS_FATAL_IF(actualAddr < addr, "Address mismatch");
93 }
94 node.timesSent++;
95 node.sentRef = binder; // might already be set
96 *outAddress = addr;
97 return OK;
98 }
99 }
100 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
101
102 auto&& [it, inserted] = mNodeForAddress.insert({RpcAddress::unique(),
103 BinderNode{
104 .binder = binder,
105 .timesSent = 1,
106 .sentRef = binder,
107 }});
108 // TODO(b/182939933): better organization could avoid needing this log
109 LOG_ALWAYS_FATAL_IF(!inserted);
110
111 *outAddress = it->first;
112 return OK;
113}
114
Steven Moreland7227c8a2021-06-02 00:24:32 +0000115status_t RpcState::onBinderEntering(const sp<RpcSession>& session, const RpcAddress& address,
116 sp<IBinder>* out) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000117 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000118 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000119
120 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000121 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000122
123 // implicitly have strong RPC refcount, since we received this binder
124 it->second.timesRecd++;
125
126 _l.unlock();
127
128 // We have timesRecd RPC refcounts, but we only need to hold on to one
129 // when we keep the object. All additional dec strongs are sent
130 // immediately, we wait to send the last one in BpBinder::onLastDecStrong.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000131 (void)session->sendDecStrong(address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000132
Steven Moreland7227c8a2021-06-02 00:24:32 +0000133 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000134 }
135
136 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
137 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
138
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000139 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000140 // device global binders in the RPC world).
Steven Moreland7227c8a2021-06-02 00:24:32 +0000141 it->second.binder = *out = BpBinder::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000142 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000143 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000144}
145
146size_t RpcState::countBinders() {
147 std::lock_guard<std::mutex> _l(mNodeMutex);
148 return mNodeForAddress.size();
149}
150
151void RpcState::dump() {
152 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000153 dumpLocked();
154}
155
Steven Morelandc9d7b532021-06-04 20:57:41 +0000156void RpcState::clear() {
Steven Moreland583a14a2021-06-04 02:04:58 +0000157 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000158
159 if (mTerminated) {
160 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
161 "New state should be impossible after terminating!");
162 return;
163 }
164
165 if (SHOULD_LOG_RPC_DETAIL) {
166 ALOGE("RpcState::clear()");
167 dumpLocked();
168 }
169
170 // if the destructor of a binder object makes another RPC call, then calling
171 // decStrong could deadlock. So, we must hold onto these binders until
172 // mNodeMutex is no longer taken.
173 std::vector<sp<IBinder>> tempHoldBinder;
174
175 mTerminated = true;
176 for (auto& [address, node] : mNodeForAddress) {
177 sp<IBinder> binder = node.binder.promote();
178 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
179
180 if (node.sentRef != nullptr) {
181 tempHoldBinder.push_back(node.sentRef);
182 }
183 }
184
185 mNodeForAddress.clear();
186
187 _l.unlock();
188 tempHoldBinder.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000189}
190
191void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000192 ALOGE("DUMP OF RpcState %p", this);
193 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
194 for (const auto& [address, node] : mNodeForAddress) {
195 sp<IBinder> binder = node.binder.promote();
196
197 const char* desc;
198 if (binder) {
199 if (binder->remoteBinder()) {
200 if (binder->remoteBinder()->isRpcBinder()) {
201 desc = "(rpc binder proxy)";
202 } else {
203 desc = "(binder proxy)";
204 }
205 } else {
206 desc = "(local binder)";
207 }
208 } else {
209 desc = "(null)";
210 }
211
212 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a:%s type:%s",
213 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address.toString().c_str(),
214 desc);
215 }
216 ALOGE("END DUMP OF RpcState");
217}
218
Steven Moreland5553ac42020-11-11 02:14:45 +0000219
Steven Morelanddbe71832021-05-12 23:31:00 +0000220RpcState::CommandData::CommandData(size_t size) : mSize(size) {
221 // The maximum size for regular binder is 1MB for all concurrent
222 // transactions. A very small proportion of transactions are even
223 // larger than a page, but we need to avoid allocating too much
224 // data on behalf of an arbitrary client, or we could risk being in
225 // a position where a single additional allocation could run out of
226 // memory.
227 //
228 // Note, this limit may not reflect the total amount of data allocated for a
229 // transaction (in some cases, additional fixed size amounts are added),
230 // though for rough consistency, we should avoid cases where this data type
231 // is used for multiple dynamic allocations for a single transaction.
232 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
233 if (size == 0) return;
234 if (size > kMaxTransactionAllocation) {
235 ALOGW("Transaction requested too much data allocation %zu", size);
236 return;
237 }
238 mData.reset(new (std::nothrow) uint8_t[size]);
239}
240
Steven Morelandc9d7b532021-06-04 20:57:41 +0000241status_t RpcState::rpcSend(const base::unique_fd& fd, const sp<RpcSession>& session,
242 const char* what, const void* data, size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000243 LOG_RPC_DETAIL("Sending %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
244
Steven Morelandb8176792021-06-22 20:29:21 +0000245 MAYBE_WAIT_IN_FLAKE_MODE;
246
Steven Moreland5553ac42020-11-11 02:14:45 +0000247 if (size > std::numeric_limits<ssize_t>::max()) {
248 ALOGE("Cannot send %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000249 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000250 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000251 }
252
Steven Morelandc6ddf362021-04-02 01:13:36 +0000253 ssize_t sent = TEMP_FAILURE_RETRY(send(fd.get(), data, size, MSG_NOSIGNAL));
Steven Moreland5553ac42020-11-11 02:14:45 +0000254
255 if (sent < 0 || sent != static_cast<ssize_t>(size)) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000256 int savedErrno = errno;
Steven Morelandc12c9d92021-05-26 18:44:11 +0000257 LOG_RPC_DETAIL("Failed to send %s (sent %zd of %zu bytes) on fd %d, error: %s", what, sent,
258 size, fd.get(), strerror(savedErrno));
Steven Moreland5553ac42020-11-11 02:14:45 +0000259
Steven Morelandc9d7b532021-06-04 20:57:41 +0000260 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000261 return -savedErrno;
Steven Moreland5553ac42020-11-11 02:14:45 +0000262 }
263
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000264 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000265}
266
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000267status_t RpcState::rpcRec(const base::unique_fd& fd, const sp<RpcSession>& session,
268 const char* what, void* data, size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000269 if (size > std::numeric_limits<ssize_t>::max()) {
270 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000271 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000272 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000273 }
274
Steven Morelandee3f4662021-05-22 01:07:33 +0000275 if (status_t status = session->mShutdownTrigger->interruptableReadFully(fd.get(), data, size);
276 status != OK) {
Steven Morelandc12c9d92021-05-26 18:44:11 +0000277 LOG_RPC_DETAIL("Failed to read %s (%zu bytes) on fd %d, error: %s", what, size, fd.get(),
278 statusToString(status).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000279 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000280 }
281
Steven Morelandee3f4662021-05-22 01:07:33 +0000282 LOG_RPC_DETAIL("Received %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000283 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000284}
285
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000286status_t RpcState::sendConnectionInit(const base::unique_fd& fd, const sp<RpcSession>& session) {
287 RpcClientConnectionInit init{
288 .msg = RPC_CONNECTION_INIT_OKAY,
289 };
290 return rpcSend(fd, session, "connection init", &init, sizeof(init));
291}
292
293status_t RpcState::readConnectionInit(const base::unique_fd& fd, const sp<RpcSession>& session) {
294 RpcClientConnectionInit init;
295 if (status_t status = rpcRec(fd, session, "connection init", &init, sizeof(init)); status != OK)
296 return status;
297
298 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
299 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
300 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
301 init.msg);
302 return BAD_VALUE;
303 }
304 return OK;
305}
306
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000307sp<IBinder> RpcState::getRootObject(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000308 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000309 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000310 Parcel reply;
311
Steven Morelandf5174272021-05-25 00:39:28 +0000312 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT, data,
313 session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000314 if (status != OK) {
315 ALOGE("Error getting root object: %s", statusToString(status).c_str());
316 return nullptr;
317 }
318
319 return reply.readStrongBinder();
320}
321
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000322status_t RpcState::getMaxThreads(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000323 size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000324 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000325 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000326 Parcel reply;
327
Steven Morelandf5174272021-05-25 00:39:28 +0000328 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS,
329 data, session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000330 if (status != OK) {
331 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
332 return status;
333 }
334
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000335 int32_t maxThreads;
336 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000337 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000338 if (maxThreads <= 0) {
339 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000340 return BAD_VALUE;
341 }
342
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000343 *maxThreadsOut = maxThreads;
344 return OK;
345}
346
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000347status_t RpcState::getSessionId(const base::unique_fd& fd, const sp<RpcSession>& session,
348 int32_t* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000349 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000350 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000351 Parcel reply;
352
Steven Morelandf5174272021-05-25 00:39:28 +0000353 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_SESSION_ID,
354 data, session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000355 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000356 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000357 return status;
358 }
359
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000360 int32_t sessionId;
361 status = reply.readInt32(&sessionId);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000362 if (status != OK) return status;
363
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000364 *sessionIdOut = sessionId;
Steven Morelandf137de92021-04-24 01:54:26 +0000365 return OK;
366}
367
Steven Morelandf5174272021-05-25 00:39:28 +0000368status_t RpcState::transact(const base::unique_fd& fd, const sp<IBinder>& binder, uint32_t code,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000369 const Parcel& data, const sp<RpcSession>& session, Parcel* reply,
Steven Moreland5553ac42020-11-11 02:14:45 +0000370 uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000371 if (!data.isForRpc()) {
372 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
373 return BAD_TYPE;
374 }
375
376 if (data.objectsCount() != 0) {
377 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
378 return BAD_TYPE;
379 }
380
381 RpcAddress address = RpcAddress::zero();
382 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
383
384 return transactAddress(fd, address, code, data, session, reply, flags);
385}
386
387status_t RpcState::transactAddress(const base::unique_fd& fd, const RpcAddress& address,
388 uint32_t code, const Parcel& data, const sp<RpcSession>& session,
389 Parcel* reply, uint32_t flags) {
390 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
391 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
392
Steven Moreland5553ac42020-11-11 02:14:45 +0000393 uint64_t asyncNumber = 0;
394
395 if (!address.isZero()) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000396 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000397 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
398 auto it = mNodeForAddress.find(address);
399 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
400 address.toString().c_str());
401
402 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000403 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000404 if (!nodeProgressAsyncNumber(&it->second)) {
405 _l.unlock();
406 (void)session->shutdownAndWait(false);
407 return DEAD_OBJECT;
408 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000409 }
410 }
411
Steven Moreland77c30112021-06-02 20:45:46 +0000412 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
413 sizeof(RpcWireTransaction) <
414 data.dataSize(),
415 "Too much data %zu", data.dataSize());
416
417 RpcWireHeader command{
418 .command = RPC_COMMAND_TRANSACT,
419 .bodySize = static_cast<uint32_t>(sizeof(RpcWireTransaction) + data.dataSize()),
420 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000421 RpcWireTransaction transaction{
422 .address = address.viewRawEmbedded(),
423 .code = code,
424 .flags = flags,
425 .asyncNumber = asyncNumber,
426 };
Steven Moreland77c30112021-06-02 20:45:46 +0000427 CommandData transactionData(sizeof(RpcWireHeader) + sizeof(RpcWireTransaction) +
428 data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000429 if (!transactionData.valid()) {
430 return NO_MEMORY;
431 }
432
Steven Moreland77c30112021-06-02 20:45:46 +0000433 memcpy(transactionData.data() + 0, &command, sizeof(RpcWireHeader));
434 memcpy(transactionData.data() + sizeof(RpcWireHeader), &transaction,
435 sizeof(RpcWireTransaction));
436 memcpy(transactionData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireTransaction), data.data(),
437 data.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000438
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000439 if (status_t status =
Steven Morelandc9d7b532021-06-04 20:57:41 +0000440 rpcSend(fd, session, "transaction", transactionData.data(), transactionData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000441 status != OK)
Steven Morelanda5036f02021-06-08 02:26:57 +0000442 // TODO(b/167966510): need to undo onBinderLeaving - we know the
443 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000444 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000445
446 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland659416d2021-05-11 00:47:50 +0000447 LOG_RPC_DETAIL("Oneway command, so no longer waiting on %d", fd.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000448
449 // Do not wait on result.
450 // However, too many oneway calls may cause refcounts to build up and fill up the socket,
451 // so process those.
452 return drainCommands(fd, session, CommandType::CONTROL_ONLY);
Steven Moreland5553ac42020-11-11 02:14:45 +0000453 }
454
455 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
456
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000457 return waitForReply(fd, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000458}
459
Steven Moreland438cce82021-04-02 18:04:08 +0000460static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
461 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000462 (void)p;
463 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
464 (void)dataSize;
465 LOG_ALWAYS_FATAL_IF(objects != nullptr);
466 LOG_ALWAYS_FATAL_IF(objectsCount, 0);
467}
468
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000469status_t RpcState::waitForReply(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000470 Parcel* reply) {
471 RpcWireHeader command;
472 while (true) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000473 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
474 status != OK)
475 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000476
477 if (command.command == RPC_COMMAND_REPLY) break;
478
Steven Moreland52eee942021-06-03 00:59:28 +0000479 if (status_t status = processServerCommand(fd, session, command, CommandType::ANY);
480 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000481 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000482 }
483
Steven Morelanddbe71832021-05-12 23:31:00 +0000484 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000485 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000486
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000487 if (status_t status = rpcRec(fd, session, "reply body", data.data(), command.bodySize);
488 status != OK)
489 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000490
491 if (command.bodySize < sizeof(RpcWireReply)) {
492 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
493 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000494 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000495 return BAD_VALUE;
496 }
Steven Morelande8393342021-05-05 23:27:53 +0000497 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000498 if (rpcReply->status != OK) return rpcReply->status;
499
Steven Morelande8393342021-05-05 23:27:53 +0000500 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000501 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000502 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000503
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000504 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000505
506 return OK;
507}
508
Steven Morelandc9d7b532021-06-04 20:57:41 +0000509status_t RpcState::sendDecStrong(const base::unique_fd& fd, const sp<RpcSession>& session,
510 const RpcAddress& addr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000511 {
512 std::lock_guard<std::mutex> _l(mNodeMutex);
513 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
514 auto it = mNodeForAddress.find(addr);
515 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
516 addr.toString().c_str());
517 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
518 addr.toString().c_str());
519
520 it->second.timesRecd--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000521 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
522 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000523 }
524
525 RpcWireHeader cmd = {
526 .command = RPC_COMMAND_DEC_STRONG,
527 .bodySize = sizeof(RpcWireAddress),
528 };
Steven Morelandc9d7b532021-06-04 20:57:41 +0000529 if (status_t status = rpcSend(fd, session, "dec ref header", &cmd, sizeof(cmd)); status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000530 return status;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000531 if (status_t status = rpcSend(fd, session, "dec ref body", &addr.viewRawEmbedded(),
532 sizeof(RpcWireAddress));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000533 status != OK)
534 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000535 return OK;
536}
537
Steven Moreland52eee942021-06-03 00:59:28 +0000538status_t RpcState::getAndExecuteCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
539 CommandType type) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000540 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", fd.get());
541
542 RpcWireHeader command;
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000543 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
544 status != OK)
545 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000546
Steven Moreland52eee942021-06-03 00:59:28 +0000547 return processServerCommand(fd, session, command, type);
548}
549
550status_t RpcState::drainCommands(const base::unique_fd& fd, const sp<RpcSession>& session,
551 CommandType type) {
552 uint8_t buf;
553 while (0 < TEMP_FAILURE_RETRY(recv(fd.get(), &buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT))) {
554 status_t status = getAndExecuteCommand(fd, session, type);
555 if (status != OK) return status;
556 }
557 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000558}
559
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000560status_t RpcState::processServerCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland52eee942021-06-03 00:59:28 +0000561 const RpcWireHeader& command, CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000562 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
563 IPCThreadState::SpGuard spGuard{
564 .address = __builtin_frame_address(0),
565 .context = "processing binder RPC command",
566 };
567 const IPCThreadState::SpGuard* origGuard;
568 if (kernelBinderState != nullptr) {
569 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
570 }
571 ScopeGuard guardUnguard = [&]() {
572 if (kernelBinderState != nullptr) {
573 kernelBinderState->restoreGetCallingSpGuard(origGuard);
574 }
575 };
576
Steven Moreland5553ac42020-11-11 02:14:45 +0000577 switch (command.command) {
578 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000579 if (type != CommandType::ANY) return BAD_TYPE;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000580 return processTransact(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000581 case RPC_COMMAND_DEC_STRONG:
Steven Morelandee3f4662021-05-22 01:07:33 +0000582 return processDecStrong(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000583 }
584
585 // We should always know the version of the opposing side, and since the
586 // RPC-binder-level wire protocol is not self synchronizing, we have no way
587 // to understand where the current command ends and the next one begins. We
588 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000589 // to kill us, so ending the session for misbehaving client.
590 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000591 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000592 return DEAD_OBJECT;
593}
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000594status_t RpcState::processTransact(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000595 const RpcWireHeader& command) {
596 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
597
Steven Morelanddbe71832021-05-12 23:31:00 +0000598 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000599 if (!transactionData.valid()) {
600 return NO_MEMORY;
601 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000602 if (status_t status = rpcRec(fd, session, "transaction body", transactionData.data(),
603 transactionData.size());
604 status != OK)
605 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000606
Steven Morelandada72bd2021-06-09 23:29:13 +0000607 return processTransactInternal(fd, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000608}
609
Steven Moreland438cce82021-04-02 18:04:08 +0000610static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
611 const binder_size_t* objects, size_t objectsCount) {
612 (void)p;
613 (void)data;
614 (void)dataSize;
615 (void)objects;
616 (void)objectsCount;
617}
618
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000619status_t RpcState::processTransactInternal(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000620 CommandData transactionData) {
621 // for 'recursive' calls to this, we have already read and processed the
622 // binder from the transaction data and taken reference counts into account,
623 // so it is cached here.
624 sp<IBinder> targetRef;
625processTransactInternalTailCall:
626
Steven Moreland5553ac42020-11-11 02:14:45 +0000627 if (transactionData.size() < sizeof(RpcWireTransaction)) {
628 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
629 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000630 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000631 return BAD_VALUE;
632 }
633 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
634
635 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
636 // maybe add an RpcAddress 'view' if the type remains 'heavy'
637 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
638
639 status_t replyStatus = OK;
640 sp<IBinder> target;
641 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000642 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000643 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000644 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000645 target = targetRef;
646 }
647
Steven Moreland7227c8a2021-06-02 00:24:32 +0000648 if (replyStatus != OK) {
649 // do nothing
650 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000651 // This can happen if the binder is remote in this process, and
652 // another thread has called the last decStrong on this binder.
653 // However, for local binders, it indicates a misbehaving client
654 // (any binder which is being transacted on should be holding a
655 // strong ref count), so in either case, terminating the
656 // session.
657 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
658 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000659 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000660 replyStatus = BAD_VALUE;
661 } else if (target->localBinder() == nullptr) {
662 ALOGE("Unknown binder address or non-local binder, not address %s. Terminating!",
663 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000664 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000665 replyStatus = BAD_VALUE;
666 } else if (transaction->flags & IBinder::FLAG_ONEWAY) {
Steven Morelandd45be622021-06-04 02:19:37 +0000667 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000668 auto it = mNodeForAddress.find(addr);
669 if (it->second.binder.promote() != target) {
670 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000671 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000672 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000673 } else if (transaction->asyncNumber != it->second.asyncNumber) {
674 // we need to process some other asynchronous transaction
675 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000676 it->second.asyncTodo.push(BinderNode::AsyncTodo{
677 .ref = target,
678 .data = std::move(transactionData),
679 .asyncNumber = transaction->asyncNumber,
680 });
Steven Morelandd45be622021-06-04 02:19:37 +0000681
682 size_t numPending = it->second.asyncTodo.size();
683 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s (%zu pending)",
684 transaction->asyncNumber, addr.toString().c_str(), numPending);
685
686 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
687 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
688 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
689
690 if (numPending >= kArbitraryOnewayCallWarnLevel) {
691 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
692 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
693 _l.unlock();
694 (void)session->shutdownAndWait(false);
695 return FAILED_TRANSACTION;
696 }
697
698 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
699 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
700 target.get(), numPending);
701 }
702 }
Steven Morelandf5174272021-05-25 00:39:28 +0000703 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000704 }
705 }
706 }
707
Steven Moreland5553ac42020-11-11 02:14:45 +0000708 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000709 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000710
711 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000712 Parcel data;
713 // transaction->data is owned by this function. Parcel borrows this data and
714 // only holds onto it for the duration of this function call. Parcel will be
715 // deleted before the 'transactionData' object.
716 data.ipcSetDataReference(transaction->data,
717 transactionData.size() - offsetof(RpcWireTransaction, data),
718 nullptr /*object*/, 0 /*objectCount*/,
719 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000720 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000721
Steven Moreland5553ac42020-11-11 02:14:45 +0000722 if (target) {
723 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
724 } else {
725 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000726
Steven Moreland103424e2021-06-02 18:16:19 +0000727 switch (transaction->code) {
728 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
729 replyStatus = reply.writeInt32(session->getMaxThreads());
730 break;
731 }
732 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
733 // for client connections, this should always report the value
734 // originally returned from the server
735 int32_t id = session->mId.value();
736 replyStatus = reply.writeInt32(id);
737 break;
738 }
739 default: {
740 sp<RpcServer> server = session->server().promote();
741 if (server) {
742 switch (transaction->code) {
743 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
744 replyStatus = reply.writeStrongBinder(server->getRootObject());
745 break;
746 }
747 default: {
748 replyStatus = UNKNOWN_TRANSACTION;
749 }
750 }
751 } else {
752 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000753 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000754 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000755 }
756 }
757 }
758
759 if (transaction->flags & IBinder::FLAG_ONEWAY) {
760 if (replyStatus != OK) {
761 ALOGW("Oneway call failed with error: %d", replyStatus);
762 }
763
764 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
765 addr.toString().c_str());
766
767 // Check to see if there is another asynchronous transaction to process.
768 // This behavior differs from binder behavior, since in the binder
769 // driver, asynchronous transactions will be processed after existing
770 // pending binder transactions on the queue. The downside of this is
771 // that asynchronous transactions can be drowned out by synchronous
772 // transactions. However, we have no easy way to queue these
773 // transactions after the synchronous transactions we may want to read
774 // from the wire. So, in socket binder here, we have the opposite
775 // downside: asynchronous transactions may drown out synchronous
776 // transactions.
777 {
778 std::unique_lock<std::mutex> _l(mNodeMutex);
779 auto it = mNodeForAddress.find(addr);
780 // last refcount dropped after this transaction happened
781 if (it == mNodeForAddress.end()) return OK;
782
Steven Morelandc9d7b532021-06-04 20:57:41 +0000783 if (!nodeProgressAsyncNumber(&it->second)) {
784 _l.unlock();
785 (void)session->shutdownAndWait(false);
786 return DEAD_OBJECT;
787 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000788
789 if (it->second.asyncTodo.size() == 0) return OK;
790 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
791 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
792 it->second.asyncNumber, addr.toString().c_str());
793
794 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000795 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000796 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000797 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
798
Steven Morelandada72bd2021-06-09 23:29:13 +0000799 // reset up arguments
800 transactionData = std::move(todo.data);
801 targetRef = std::move(todo.ref);
Steven Morelandf5174272021-05-25 00:39:28 +0000802
Steven Moreland5553ac42020-11-11 02:14:45 +0000803 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000804 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000805 }
806 }
807 return OK;
808 }
809
Steven Moreland77c30112021-06-02 20:45:46 +0000810 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
811 sizeof(RpcWireReply) <
812 reply.dataSize(),
813 "Too much data for reply %zu", reply.dataSize());
814
815 RpcWireHeader cmdReply{
816 .command = RPC_COMMAND_REPLY,
817 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
818 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000819 RpcWireReply rpcReply{
820 .status = replyStatus,
821 };
822
Steven Moreland77c30112021-06-02 20:45:46 +0000823 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000824 if (!replyData.valid()) {
825 return NO_MEMORY;
826 }
Steven Moreland77c30112021-06-02 20:45:46 +0000827 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
828 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
829 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
830 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000831
Steven Morelandc9d7b532021-06-04 20:57:41 +0000832 return rpcSend(fd, session, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000833}
834
Steven Morelandee3f4662021-05-22 01:07:33 +0000835status_t RpcState::processDecStrong(const base::unique_fd& fd, const sp<RpcSession>& session,
836 const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000837 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
838
Steven Morelanddbe71832021-05-12 23:31:00 +0000839 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000840 if (!commandData.valid()) {
841 return NO_MEMORY;
842 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000843 if (status_t status =
844 rpcRec(fd, session, "dec ref body", commandData.data(), commandData.size());
845 status != OK)
846 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000847
848 if (command.bodySize < sizeof(RpcWireAddress)) {
849 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
850 sizeof(RpcWireAddress), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000851 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000852 return BAD_VALUE;
853 }
854 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
855
856 // TODO(b/182939933): heap allocation just for lookup
857 auto addr = RpcAddress::fromRawEmbedded(address);
858 std::unique_lock<std::mutex> _l(mNodeMutex);
859 auto it = mNodeForAddress.find(addr);
860 if (it == mNodeForAddress.end()) {
861 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000862 return OK;
863 }
864
865 sp<IBinder> target = it->second.binder.promote();
866 if (target == nullptr) {
867 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
868 addr.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000869 _l.unlock();
870 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000871 return BAD_VALUE;
872 }
873
874 if (it->second.timesSent == 0) {
875 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
876 return OK;
877 }
878
879 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
880 addr.toString().c_str());
881
Steven Moreland5553ac42020-11-11 02:14:45 +0000882 it->second.timesSent--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000883 sp<IBinder> tempHold = tryEraseNode(it);
884 _l.unlock();
885 tempHold = nullptr; // destructor may make binder calls on this session
886
887 return OK;
888}
889
890sp<IBinder> RpcState::tryEraseNode(std::map<RpcAddress, BinderNode>::iterator& it) {
891 sp<IBinder> ref;
892
Steven Moreland5553ac42020-11-11 02:14:45 +0000893 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000894 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000895
896 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +0000897 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
898 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +0000899 mNodeForAddress.erase(it);
900 }
901 }
902
Steven Moreland31bde7a2021-06-04 00:57:36 +0000903 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +0000904}
905
Steven Morelandc9d7b532021-06-04 20:57:41 +0000906bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000907 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
908 // a single binder
909 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
910 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +0000911 return false;
912 }
913 node->asyncNumber++;
914 return true;
915}
916
Steven Moreland5553ac42020-11-11 02:14:45 +0000917} // namespace android