blob: 28730ffc2b15651c298895702a5f7ffcb0feb778 [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 Moreland62129012021-07-29 12:14:44 -070021#include <android-base/hex.h>
Andrei Homescua39e4ed2021-12-10 08:41:54 +000022#include <android-base/macros.h>
Steven Morelandd7302072021-05-15 01:32:04 +000023#include <android-base/scopeguard.h>
Frederick Mayle69a0c992022-05-26 20:38:39 +000024#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000025#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000026#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000027#include <binder/RpcServer.h>
28
29#include "Debug.h"
30#include "RpcWireFormat.h"
Frederick Mayledc07cf82022-05-26 20:30:12 +000031#include "Utils.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000032
Steven Morelandb8176792021-06-22 20:29:21 +000033#include <random>
34
Steven Moreland5553ac42020-11-11 02:14:45 +000035#include <inttypes.h>
36
37namespace android {
38
Frederick Mayle69a0c992022-05-26 20:38:39 +000039using base::StringPrintf;
Steven Morelandd7302072021-05-15 01:32:04 +000040
Devin Moore08256432021-07-02 13:03:49 -070041#if RPC_FLAKE_PRONE
Steven Morelandb8176792021-06-22 20:29:21 +000042void rpcMaybeWaitToFlake() {
Devin Moore08256432021-07-02 13:03:49 -070043 [[clang::no_destroy]] static std::random_device r;
44 [[clang::no_destroy]] static std::mutex m;
Steven Morelandb8176792021-06-22 20:29:21 +000045 unsigned num;
46 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000047 RpcMutexLockGuard lock(m);
Steven Morelandb8176792021-06-22 20:29:21 +000048 num = r();
49 }
50 if (num % 10 == 0) usleep(num % 1000);
51}
52#endif
53
Frederick Mayle69a0c992022-05-26 20:38:39 +000054static bool enableAncillaryFds(RpcSession::FileDescriptorTransportMode mode) {
55 switch (mode) {
56 case RpcSession::FileDescriptorTransportMode::NONE:
57 return false;
58 case RpcSession::FileDescriptorTransportMode::UNIX:
59 return true;
60 }
61}
62
Steven Moreland5553ac42020-11-11 02:14:45 +000063RpcState::RpcState() {}
64RpcState::~RpcState() {}
65
Steven Morelandbdb53ab2021-05-05 17:57:41 +000066status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5623d1a2021-09-10 15:45:34 -070067 uint64_t* outAddress) {
Steven Moreland5553ac42020-11-11 02:14:45 +000068 bool isRemote = binder->remoteBinder();
69 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
70
Steven Moreland99157622021-09-13 16:27:34 -070071 if (isRpc && binder->remoteBinder()->getPrivateAccessor().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000072 // We need to be able to send instructions over the socket for how to
73 // connect to a different server, and we also need to let the host
74 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000075 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000076 return INVALID_OPERATION;
77 }
78
79 if (isRemote && !isRpc) {
80 // Without additional work, this would have the effect of using this
81 // process to proxy calls from the socket over to the other process, and
82 // it would make those calls look like they come from us (not over the
83 // sockets). In order to make this work transparently like binder, we
84 // would instead need to send instructions over the socket for how to
85 // connect to the host process, and we also need to let the host process
86 // know this was happening.
87 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
88 return INVALID_OPERATION;
89 }
90
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000091 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000092 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +000093
94 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
95 // in RpcState
96 for (auto& [addr, node] : mNodeForAddress) {
97 if (binder == node.binder) {
98 if (isRpc) {
Steven Moreland5623d1a2021-09-10 15:45:34 -070099 // check integrity of data structure
Steven Moreland99157622021-09-13 16:27:34 -0700100 uint64_t actualAddr = binder->remoteBinder()->getPrivateAccessor().rpcAddress();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700101 LOG_ALWAYS_FATAL_IF(addr != actualAddr, "Address mismatch %" PRIu64 " vs %" PRIu64,
102 addr, actualAddr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000103 }
104 node.timesSent++;
105 node.sentRef = binder; // might already be set
106 *outAddress = addr;
107 return OK;
108 }
109 }
110 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
111
Steven Moreland91538242021-06-10 23:35:35 +0000112 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +0000113
Steven Moreland5623d1a2021-09-10 15:45:34 -0700114 // arbitrary limit for maximum number of nodes in a process (otherwise we
115 // might run out of addresses)
116 if (mNodeForAddress.size() > 100000) {
117 return NO_MEMORY;
118 }
119
120 while (true) {
121 RpcWireAddress address{
122 .options = RPC_WIRE_ADDRESS_OPTION_CREATED,
123 .address = mNextId,
124 };
125 if (forServer) {
126 address.options |= RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
127 }
128
129 // avoid ubsan abort
130 if (mNextId >= std::numeric_limits<uint32_t>::max()) {
131 mNextId = 0;
132 } else {
133 mNextId++;
134 }
135
136 auto&& [it, inserted] = mNodeForAddress.insert({RpcWireAddress::toRaw(address),
Steven Moreland91538242021-06-10 23:35:35 +0000137 BinderNode{
138 .binder = binder,
Steven Moreland91538242021-06-10 23:35:35 +0000139 .sentRef = binder,
Andrei Homescu5a036f32022-03-08 22:54:40 +0000140 .timesSent = 1,
Steven Moreland91538242021-06-10 23:35:35 +0000141 }});
142 if (inserted) {
143 *outAddress = it->first;
144 return OK;
145 }
Steven Moreland91538242021-06-10 23:35:35 +0000146 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000147}
148
Steven Moreland5623d1a2021-09-10 15:45:34 -0700149status_t RpcState::onBinderEntering(const sp<RpcSession>& session, uint64_t address,
Steven Moreland7227c8a2021-06-02 00:24:32 +0000150 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000151 // ensure that: if we want to use addresses for something else in the future (for
152 // instance, allowing transitive binder sends), that we don't accidentally
153 // send those addresses to old server. Accidentally ignoring this in that
154 // case and considering the binder to be recognized could cause this
155 // process to accidentally proxy transactions for that binder. Of course,
156 // if we communicate with a binder, it could always be proxying
157 // information. However, we want to make sure that isn't done on accident
158 // by a client.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700159 RpcWireAddress addr = RpcWireAddress::fromRaw(address);
160 constexpr uint32_t kKnownOptions =
161 RPC_WIRE_ADDRESS_OPTION_CREATED | RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
162 if (addr.options & ~kKnownOptions) {
163 ALOGE("Address is of an unknown type, rejecting: %" PRIu64, address);
Steven Moreland91538242021-06-10 23:35:35 +0000164 return BAD_VALUE;
165 }
166
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000167 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000168 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000169
170 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000171 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000172
173 // implicitly have strong RPC refcount, since we received this binder
174 it->second.timesRecd++;
Steven Morelandd8083312021-09-22 13:37:10 -0700175 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000176 }
177
Steven Moreland91538242021-06-10 23:35:35 +0000178 // we don't know about this binder, so the other side of the connection
179 // should have created it.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700180 if ((addr.options & RPC_WIRE_ADDRESS_OPTION_FOR_SERVER) == !!session->server()) {
181 ALOGE("Server received unrecognized address which we should own the creation of %" PRIu64,
182 address);
Steven Moreland91538242021-06-10 23:35:35 +0000183 return BAD_VALUE;
184 }
185
Steven Moreland5553ac42020-11-11 02:14:45 +0000186 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
187 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
188
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000189 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000190 // device global binders in the RPC world).
Steven Moreland99157622021-09-13 16:27:34 -0700191 it->second.binder = *out = BpBinder::PrivateAccessor::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000192 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000193 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000194}
195
Steven Morelandd8083312021-09-22 13:37:10 -0700196status_t RpcState::flushExcessBinderRefs(const sp<RpcSession>& session, uint64_t address,
197 const sp<IBinder>& binder) {
Steven Morelande96ed0e2021-09-27 17:43:53 -0700198 // We can flush all references when the binder is destroyed. No need to send
199 // extra reference counting packets now.
200 if (binder->remoteBinder()) return OK;
201
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000202 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandd8083312021-09-22 13:37:10 -0700203 if (mTerminated) return DEAD_OBJECT;
204
205 auto it = mNodeForAddress.find(address);
206
207 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Can't be deleted while we hold sp<>");
208 LOG_ALWAYS_FATAL_IF(it->second.binder != binder,
209 "Caller of flushExcessBinderRefs using inconsistent arguments");
210
Steven Morelande96ed0e2021-09-27 17:43:53 -0700211 LOG_ALWAYS_FATAL_IF(it->second.timesSent <= 0, "Local binder must have been sent %p",
212 binder.get());
Steven Morelandd8083312021-09-22 13:37:10 -0700213
Steven Morelande96ed0e2021-09-27 17:43:53 -0700214 // For a local binder, we only need to know that we sent it. Now that we
215 // have an sp<> for this call, we don't need anything more. If the other
216 // process is done with this binder, it needs to know we received the
217 // refcount associated with this call, so we can acknowledge that we
218 // received it. Once (or if) it has no other refcounts, it would reply with
219 // its own decStrong so that it could be removed from this session.
220 if (it->second.timesRecd != 0) {
Steven Morelandd8083312021-09-22 13:37:10 -0700221 _l.unlock();
222
Steven Morelande96ed0e2021-09-27 17:43:53 -0700223 return session->sendDecStrongToTarget(address, 0);
Steven Morelandd8083312021-09-22 13:37:10 -0700224 }
225
226 return OK;
227}
228
Steven Moreland5553ac42020-11-11 02:14:45 +0000229size_t RpcState::countBinders() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000230 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000231 return mNodeForAddress.size();
232}
233
234void RpcState::dump() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000235 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000236 dumpLocked();
237}
238
Steven Morelandc9d7b532021-06-04 20:57:41 +0000239void RpcState::clear() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000240 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000241
242 if (mTerminated) {
243 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
244 "New state should be impossible after terminating!");
245 return;
246 }
247
248 if (SHOULD_LOG_RPC_DETAIL) {
249 ALOGE("RpcState::clear()");
250 dumpLocked();
251 }
252
253 // if the destructor of a binder object makes another RPC call, then calling
254 // decStrong could deadlock. So, we must hold onto these binders until
255 // mNodeMutex is no longer taken.
256 std::vector<sp<IBinder>> tempHoldBinder;
257
258 mTerminated = true;
259 for (auto& [address, node] : mNodeForAddress) {
260 sp<IBinder> binder = node.binder.promote();
Steven Moreland3fa32922022-07-14 18:45:51 +0000261 LOG_ALWAYS_FATAL_IF(binder == nullptr,
262 "Binder expected to be owned with address: %" PRIu64 " %s", address,
263 node.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000264
265 if (node.sentRef != nullptr) {
266 tempHoldBinder.push_back(node.sentRef);
267 }
268 }
269
270 mNodeForAddress.clear();
271
272 _l.unlock();
273 tempHoldBinder.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000274}
275
276void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000277 ALOGE("DUMP OF RpcState %p", this);
278 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
279 for (const auto& [address, node] : mNodeForAddress) {
Steven Moreland3fa32922022-07-14 18:45:51 +0000280 ALOGE("- address: %" PRIu64 " %s", address, node.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000281 }
282 ALOGE("END DUMP OF RpcState");
283}
284
Steven Moreland3fa32922022-07-14 18:45:51 +0000285std::string RpcState::BinderNode::toString() const {
286 sp<IBinder> strongBinder = this->binder.promote();
287
288 const char* desc;
289 if (strongBinder) {
290 if (strongBinder->remoteBinder()) {
291 if (strongBinder->remoteBinder()->isRpcBinder()) {
292 desc = "(rpc binder proxy)";
293 } else {
294 desc = "(binder proxy)";
295 }
296 } else {
297 desc = "(local binder)";
298 }
299 } else {
300 desc = "(not promotable)";
301 }
302
303 return StringPrintf("node{%p times sent: %zu times recd: %zu type: %s}",
304 this->binder.unsafe_get(), this->timesSent, this->timesRecd, desc);
305}
Steven Moreland5553ac42020-11-11 02:14:45 +0000306
Steven Morelanddbe71832021-05-12 23:31:00 +0000307RpcState::CommandData::CommandData(size_t size) : mSize(size) {
308 // The maximum size for regular binder is 1MB for all concurrent
309 // transactions. A very small proportion of transactions are even
310 // larger than a page, but we need to avoid allocating too much
311 // data on behalf of an arbitrary client, or we could risk being in
312 // a position where a single additional allocation could run out of
313 // memory.
314 //
315 // Note, this limit may not reflect the total amount of data allocated for a
316 // transaction (in some cases, additional fixed size amounts are added),
317 // though for rough consistency, we should avoid cases where this data type
318 // is used for multiple dynamic allocations for a single transaction.
319 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
320 if (size == 0) return;
321 if (size > kMaxTransactionAllocation) {
322 ALOGW("Transaction requested too much data allocation %zu", size);
323 return;
324 }
325 mData.reset(new (std::nothrow) uint8_t[size]);
326}
327
Frederick Mayle69a0c992022-05-26 20:38:39 +0000328status_t RpcState::rpcSend(
329 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
330 const char* what, iovec* iovs, int niovs,
331 const std::optional<android::base::function_ref<status_t()>>& altPoll,
332 const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800333 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000334 LOG_RPC_DETAIL("Sending %s (part %d of %d) on RpcTransport %p: %s",
335 what, i + 1, niovs, connection->rpcTransport.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000336 android::base::HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000337 }
338
Yifan Hong702115c2021-06-24 15:39:18 -0700339 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700340 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
Frederick Mayle69a0c992022-05-26 20:38:39 +0000341 iovs, niovs, altPoll,
342 ancillaryFds);
Steven Moreland798e0d12021-07-14 23:19:25 +0000343 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800344 LOG_RPC_DETAIL("Failed to write %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700345 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000346 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000347 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000348 }
349
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000350 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000351}
352
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000353status_t RpcState::rpcRec(
354 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
355 const char* what, iovec* iovs, int niovs,
356 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
357 if (status_t status =
358 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
359 iovs, niovs, std::nullopt,
360 ancillaryFds);
Steven Morelandee3f4662021-05-22 01:07:33 +0000361 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800362 LOG_RPC_DETAIL("Failed to read %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700363 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandae58f432021-08-05 17:53:16 -0700364 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000365 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000366 }
367
Colin Cross9adfeaf2022-01-21 17:22:09 -0800368 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000369 LOG_RPC_DETAIL("Received %s (part %d of %d) on RpcTransport %p: %s",
370 what, i + 1, niovs, connection->rpcTransport.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000371 android::base::HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
372 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000373 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000374}
375
Steven Morelandbf57bce2021-07-26 15:26:12 -0700376status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
377 const sp<RpcSession>& session, uint32_t* version) {
378 RpcNewSessionResponse response;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000379 iovec iov{&response, sizeof(response)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000380 if (status_t status = rpcRec(connection, session, "new session response", &iov, 1, nullptr);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700381 status != OK) {
382 return status;
383 }
384 *version = response.version;
385 return OK;
386}
387
Steven Moreland5ae62562021-06-10 03:21:42 +0000388status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
389 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000390 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000391 .msg = RPC_CONNECTION_INIT_OKAY,
392 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000393 iovec iov{&init, sizeof(init)};
Devin Moore695368f2022-06-03 22:29:14 +0000394 return rpcSend(connection, session, "connection init", &iov, 1, std::nullopt);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000395}
396
Steven Moreland5ae62562021-06-10 03:21:42 +0000397status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
398 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000399 RpcOutgoingConnectionInit init;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000400 iovec iov{&init, sizeof(init)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000401 if (status_t status = rpcRec(connection, session, "connection init", &iov, 1, nullptr);
402 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000403 return status;
404
405 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
406 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
407 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
408 init.msg);
409 return BAD_VALUE;
410 }
411 return OK;
412}
413
Steven Moreland5ae62562021-06-10 03:21:42 +0000414sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
415 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000416 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000417 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000418 Parcel reply;
419
Steven Moreland5623d1a2021-09-10 15:45:34 -0700420 status_t status =
421 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000422 if (status != OK) {
423 ALOGE("Error getting root object: %s", statusToString(status).c_str());
424 return nullptr;
425 }
426
427 return reply.readStrongBinder();
428}
429
Steven Moreland5ae62562021-06-10 03:21:42 +0000430status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
431 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000432 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000433 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000434 Parcel reply;
435
Steven Moreland5623d1a2021-09-10 15:45:34 -0700436 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
437 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000438 if (status != OK) {
439 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
440 return status;
441 }
442
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000443 int32_t maxThreads;
444 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000445 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000446 if (maxThreads <= 0) {
447 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000448 return BAD_VALUE;
449 }
450
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000451 *maxThreadsOut = maxThreads;
452 return OK;
453}
454
Steven Moreland5ae62562021-06-10 03:21:42 +0000455status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700456 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000457 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000458 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000459 Parcel reply;
460
Steven Moreland5623d1a2021-09-10 15:45:34 -0700461 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
462 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000463 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000464 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000465 return status;
466 }
467
Steven Moreland826367f2021-09-10 14:05:31 -0700468 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000469}
470
Steven Moreland5ae62562021-06-10 03:21:42 +0000471status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
472 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
473 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000474 std::string errorMsg;
475 if (status_t status = validateParcel(session, data, &errorMsg); status != OK) {
476 ALOGE("Refusing to send RPC on binder %p code %" PRIu32 ": Parcel %p failed validation: %s",
477 binder.get(), code, &data, errorMsg.c_str());
478 return status;
Steven Morelandf5174272021-05-25 00:39:28 +0000479 }
Steven Moreland5623d1a2021-09-10 15:45:34 -0700480 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000481 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
482
Steven Moreland5ae62562021-06-10 03:21:42 +0000483 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000484}
485
Steven Moreland5ae62562021-06-10 03:21:42 +0000486status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700487 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000488 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000489 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
490 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
491
Steven Moreland5553ac42020-11-11 02:14:45 +0000492 uint64_t asyncNumber = 0;
493
Steven Moreland5623d1a2021-09-10 15:45:34 -0700494 if (address != 0) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000495 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000496 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
497 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700498 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
499 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000500
501 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000502 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000503 if (!nodeProgressAsyncNumber(&it->second)) {
504 _l.unlock();
505 (void)session->shutdownAndWait(false);
506 return DEAD_OBJECT;
507 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000508 }
509 }
510
Frederick Mayle69a0c992022-05-26 20:38:39 +0000511 auto* rpcFields = data.maybeRpcFields();
512 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
513
514 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
515 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +0000516
Frederick Mayle778c0902022-05-27 01:14:57 +0000517 uint32_t bodySize;
518 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(sizeof(RpcWireTransaction), data.dataSize(),
Frederick Mayledc07cf82022-05-26 20:30:12 +0000519 &bodySize) ||
520 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
521 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +0000522 "Too much data %zu", data.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +0000523 RpcWireHeader command{
524 .command = RPC_COMMAND_TRANSACT,
Frederick Mayle778c0902022-05-27 01:14:57 +0000525 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +0000526 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700527
Steven Moreland5553ac42020-11-11 02:14:45 +0000528 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700529 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000530 .code = code,
531 .flags = flags,
532 .asyncNumber = asyncNumber,
Frederick Mayledc07cf82022-05-26 20:30:12 +0000533 // bodySize didn't overflow => this cast is safe
534 .parcelDataSize = static_cast<uint32_t>(data.dataSize()),
Steven Moreland5553ac42020-11-11 02:14:45 +0000535 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000536
Steven Moreland43921d52021-09-27 17:15:56 -0700537 constexpr size_t kWaitMaxUs = 1000000;
538 constexpr size_t kWaitLogUs = 10000;
539 size_t waitUs = 0;
540
541 // Oneway calls have no sync point, so if many are sent before, whether this
542 // is a twoway or oneway transaction, they may have filled up the socket.
Devin Moore695368f2022-06-03 22:29:14 +0000543 // So, make sure we drain them before polling
Steven Moreland43921d52021-09-27 17:15:56 -0700544
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000545 iovec iovs[]{
546 {&command, sizeof(RpcWireHeader)},
547 {&transaction, sizeof(RpcWireTransaction)},
548 {const_cast<uint8_t*>(data.data()), data.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +0000549 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000550 };
Frederick Mayle69a0c992022-05-26 20:38:39 +0000551 if (status_t status = rpcSend(
552 connection, session, "transaction", iovs, arraysize(iovs),
553 [&] {
554 if (waitUs > kWaitLogUs) {
555 ALOGE("Cannot send command, trying to process pending refcounts. Waiting "
556 "%zuus. Too many oneway calls?",
557 waitUs);
558 }
Devin Moore695368f2022-06-03 22:29:14 +0000559
Frederick Mayle69a0c992022-05-26 20:38:39 +0000560 if (waitUs > 0) {
561 usleep(waitUs);
562 waitUs = std::min(kWaitMaxUs, waitUs * 2);
563 } else {
564 waitUs = 1;
565 }
Devin Moore695368f2022-06-03 22:29:14 +0000566
Frederick Mayle69a0c992022-05-26 20:38:39 +0000567 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
568 },
569 rpcFields->mFds.get());
Steven Moreland43921d52021-09-27 17:15:56 -0700570 status != OK) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000571 // TODO(b/167966510): need to undo onBinderLeaving - we know the
572 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000573 return status;
Steven Moreland43921d52021-09-27 17:15:56 -0700574 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000575
576 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700577 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
578 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000579
580 // Do not wait on result.
Steven Moreland43921d52021-09-27 17:15:56 -0700581 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000582 }
583
584 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
585
Steven Moreland5ae62562021-06-10 03:21:42 +0000586 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000587}
588
Steven Moreland438cce82021-04-02 18:04:08 +0000589static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
590 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000591 (void)p;
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000592 delete[] const_cast<uint8_t*>(data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000593 (void)dataSize;
594 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Yifan Hong239a2ca2021-06-24 16:05:16 -0700595 LOG_ALWAYS_FATAL_IF(objectsCount != 0, "%zu objects remaining", objectsCount);
Steven Moreland5553ac42020-11-11 02:14:45 +0000596}
597
Steven Moreland5ae62562021-06-10 03:21:42 +0000598status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
599 const sp<RpcSession>& session, Parcel* reply) {
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000600 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000601 RpcWireHeader command;
602 while (true) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000603 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000604 if (status_t status = rpcRec(connection, session, "command header (for reply)", &iov, 1,
605 enableAncillaryFds(session->getFileDescriptorTransportMode())
606 ? &ancillaryFds
607 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000608 status != OK)
609 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000610
611 if (command.command == RPC_COMMAND_REPLY) break;
612
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000613 if (status_t status = processCommand(connection, session, command, CommandType::ANY,
614 std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000615 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000616 return status;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000617
618 // Reset to avoid spurious use-after-move warning from clang-tidy.
619 ancillaryFds = decltype(ancillaryFds)();
Steven Moreland5553ac42020-11-11 02:14:45 +0000620 }
621
Frederick Mayledc07cf82022-05-26 20:30:12 +0000622 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
623
624 if (command.bodySize < rpcReplyWireSize) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000625 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
626 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000627 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000628 return BAD_VALUE;
629 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000630
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000631 RpcWireReply rpcReply;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000632 memset(&rpcReply, 0, sizeof(RpcWireReply)); // zero because of potential short read
633
634 CommandData data(command.bodySize - rpcReplyWireSize);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000635 if (!data.valid()) return NO_MEMORY;
636
637 iovec iovs[]{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000638 {&rpcReply, rpcReplyWireSize},
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000639 {data.data(), data.size()},
640 };
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000641 if (status_t status = rpcRec(connection, session, "reply body", iovs, arraysize(iovs), nullptr);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000642 status != OK)
643 return status;
Frederick Mayle69a0c992022-05-26 20:38:39 +0000644
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000645 if (rpcReply.status != OK) return rpcReply.status;
646
Frederick Mayledc07cf82022-05-26 20:30:12 +0000647 Span<const uint8_t> parcelSpan = {data.data(), data.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000648 Span<const uint32_t> objectTableSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000649 if (session->getProtocolVersion().value() >=
650 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
651 Span<const uint8_t> objectTableBytes = parcelSpan.splitOff(rpcReply.parcelDataSize);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000652 std::optional<Span<const uint32_t>> maybeSpan =
653 objectTableBytes.reinterpret<const uint32_t>();
654 if (!maybeSpan.has_value()) {
655 ALOGE("Bad object table size inferred from RpcWireReply. Saw bodySize=%" PRId32
656 " sizeofHeader=%zu parcelSize=%" PRId32 " objectTableBytesSize=%zu. Terminating!",
657 command.bodySize, rpcReplyWireSize, rpcReply.parcelDataSize,
658 objectTableBytes.size);
659 return BAD_VALUE;
660 }
661 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000662 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000663
Frederick Mayledc07cf82022-05-26 20:30:12 +0000664 data.release();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000665 return reply->rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
666 objectTableSpan.data, objectTableSpan.size,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000667 std::move(ancillaryFds), cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000668}
669
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000670status_t RpcState::sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection,
671 const sp<RpcSession>& session, uint64_t addr,
672 size_t target) {
673 RpcDecStrong body = {
674 .address = RpcWireAddress::fromRaw(addr),
675 };
676
Steven Moreland5553ac42020-11-11 02:14:45 +0000677 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000678 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000679 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
680 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700681 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
682 "Sending dec strong on unknown address %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000683
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000684 LOG_ALWAYS_FATAL_IF(it->second.timesRecd < target, "Can't dec count of %zu to %zu.",
685 it->second.timesRecd, target);
686
687 // typically this happens when multiple threads send dec refs at the
688 // same time - the transactions will get combined automatically
689 if (it->second.timesRecd == target) return OK;
690
691 body.amount = it->second.timesRecd - target;
692 it->second.timesRecd = target;
693
Steven Moreland31bde7a2021-06-04 00:57:36 +0000694 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
695 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000696 }
697
698 RpcWireHeader cmd = {
699 .command = RPC_COMMAND_DEC_STRONG,
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000700 .bodySize = sizeof(RpcDecStrong),
Steven Moreland5553ac42020-11-11 02:14:45 +0000701 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000702 iovec iovs[]{{&cmd, sizeof(cmd)}, {&body, sizeof(body)}};
Devin Moore695368f2022-06-03 22:29:14 +0000703 return rpcSend(connection, session, "dec ref", iovs, arraysize(iovs), std::nullopt);
Steven Moreland5553ac42020-11-11 02:14:45 +0000704}
705
Steven Moreland5ae62562021-06-10 03:21:42 +0000706status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
707 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700708 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000709
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000710 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000711 RpcWireHeader command;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000712 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000713 if (status_t status =
714 rpcRec(connection, session, "command header (for server)", &iov, 1,
715 enableAncillaryFds(session->getFileDescriptorTransportMode()) ? &ancillaryFds
716 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000717 status != OK)
718 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000719
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000720 return processCommand(connection, session, command, type, std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000721}
722
Steven Moreland5ae62562021-06-10 03:21:42 +0000723status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
724 const sp<RpcSession>& session, CommandType type) {
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000725 while (true) {
Andrei Homescu1975aaa2022-03-19 02:34:57 +0000726 status_t status = connection->rpcTransport->pollRead();
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000727 if (status == WOULD_BLOCK) break;
728 if (status != OK) return status;
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000729
730 status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000731 if (status != OK) return status;
732 }
733 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000734}
735
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000736status_t RpcState::processCommand(
737 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
738 const RpcWireHeader& command, CommandType type,
739 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland32150282021-11-12 22:54:53 +0000740#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000741 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
742 IPCThreadState::SpGuard spGuard{
743 .address = __builtin_frame_address(0),
Steven Morelande42ffd02022-07-06 21:46:23 +0000744 .context = "processing binder RPC command (where RpcServer::setPerSessionRootObject is "
745 "used to distinguish callers)",
Steven Morelandd7302072021-05-15 01:32:04 +0000746 };
747 const IPCThreadState::SpGuard* origGuard;
748 if (kernelBinderState != nullptr) {
749 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
750 }
Steven Moreland32150282021-11-12 22:54:53 +0000751
752 base::ScopeGuard guardUnguard = [&]() {
Steven Morelandd7302072021-05-15 01:32:04 +0000753 if (kernelBinderState != nullptr) {
754 kernelBinderState->restoreGetCallingSpGuard(origGuard);
755 }
756 };
Steven Moreland32150282021-11-12 22:54:53 +0000757#endif // BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000758
Steven Moreland5553ac42020-11-11 02:14:45 +0000759 switch (command.command) {
760 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000761 if (type != CommandType::ANY) return BAD_TYPE;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000762 return processTransact(connection, session, command, std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000763 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000764 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000765 }
766
767 // We should always know the version of the opposing side, and since the
768 // RPC-binder-level wire protocol is not self synchronizing, we have no way
769 // to understand where the current command ends and the next one begins. We
770 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000771 // to kill us, so ending the session for misbehaving client.
772 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000773 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000774 return DEAD_OBJECT;
775}
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000776status_t RpcState::processTransact(
777 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
778 const RpcWireHeader& command,
779 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000780 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
781
Steven Morelanddbe71832021-05-12 23:31:00 +0000782 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000783 if (!transactionData.valid()) {
784 return NO_MEMORY;
785 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000786 iovec iov{transactionData.data(), transactionData.size()};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000787 if (status_t status = rpcRec(connection, session, "transaction body", &iov, 1, nullptr);
788 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000789 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000790
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000791 return processTransactInternal(connection, session, std::move(transactionData),
792 std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000793}
794
Steven Moreland438cce82021-04-02 18:04:08 +0000795static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
796 const binder_size_t* objects, size_t objectsCount) {
797 (void)p;
798 (void)data;
799 (void)dataSize;
800 (void)objects;
801 (void)objectsCount;
802}
803
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000804status_t RpcState::processTransactInternal(
805 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
806 CommandData transactionData,
807 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Morelandada72bd2021-06-09 23:29:13 +0000808 // for 'recursive' calls to this, we have already read and processed the
809 // binder from the transaction data and taken reference counts into account,
810 // so it is cached here.
Steven Moreland3903bf02021-09-27 16:05:24 -0700811 sp<IBinder> target;
Steven Morelandada72bd2021-06-09 23:29:13 +0000812processTransactInternalTailCall:
813
Steven Moreland5553ac42020-11-11 02:14:45 +0000814 if (transactionData.size() < sizeof(RpcWireTransaction)) {
815 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
816 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000817 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000818 return BAD_VALUE;
819 }
820 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
821
Steven Moreland5623d1a2021-09-10 15:45:34 -0700822 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000823 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000824
825 status_t replyStatus = OK;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700826 if (addr != 0) {
Steven Moreland3903bf02021-09-27 16:05:24 -0700827 if (!target) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000828 replyStatus = onBinderEntering(session, addr, &target);
Steven Morelandf5174272021-05-25 00:39:28 +0000829 }
830
Steven Moreland7227c8a2021-06-02 00:24:32 +0000831 if (replyStatus != OK) {
832 // do nothing
833 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000834 // This can happen if the binder is remote in this process, and
835 // another thread has called the last decStrong on this binder.
836 // However, for local binders, it indicates a misbehaving client
837 // (any binder which is being transacted on should be holding a
838 // strong ref count), so in either case, terminating the
839 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700840 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
841 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000842 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000843 replyStatus = BAD_VALUE;
844 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700845 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
846 ". Terminating!",
847 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000848 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000849 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000850 } else if (oneway) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000851 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000852 auto it = mNodeForAddress.find(addr);
853 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700854 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000855 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000856 } else if (transaction->asyncNumber != it->second.asyncNumber) {
857 // we need to process some other asynchronous transaction
858 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000859 it->second.asyncTodo.push(BinderNode::AsyncTodo{
860 .ref = target,
861 .data = std::move(transactionData),
862 .asyncNumber = transaction->asyncNumber,
863 });
Steven Morelandd45be622021-06-04 02:19:37 +0000864
865 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700866 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
867 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000868
869 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
870 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
871 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
872
873 if (numPending >= kArbitraryOnewayCallWarnLevel) {
874 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
875 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
876 _l.unlock();
877 (void)session->shutdownAndWait(false);
878 return FAILED_TRANSACTION;
879 }
880
881 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
882 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
883 target.get(), numPending);
884 }
885 }
Steven Morelandf5174272021-05-25 00:39:28 +0000886 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000887 }
888 }
889 }
890
Steven Moreland5553ac42020-11-11 02:14:45 +0000891 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000892 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000893
894 if (replyStatus == OK) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000895 Span<const uint8_t> parcelSpan = {transaction->data,
896 transactionData.size() -
897 offsetof(RpcWireTransaction, data)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000898 Span<const uint32_t> objectTableSpan;
899 if (session->getProtocolVersion().value() >
Frederick Mayledc07cf82022-05-26 20:30:12 +0000900 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
901 Span<const uint8_t> objectTableBytes = parcelSpan.splitOff(transaction->parcelDataSize);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000902 std::optional<Span<const uint32_t>> maybeSpan =
903 objectTableBytes.reinterpret<const uint32_t>();
904 if (!maybeSpan.has_value()) {
905 ALOGE("Bad object table size inferred from RpcWireTransaction. Saw bodySize=%zu "
906 "sizeofHeader=%zu parcelSize=%" PRId32
907 " objectTableBytesSize=%zu. Terminating!",
908 transactionData.size(), sizeof(RpcWireTransaction),
909 transaction->parcelDataSize, objectTableBytes.size);
910 return BAD_VALUE;
911 }
912 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000913 }
914
Steven Morelandeff77c12021-04-15 00:37:19 +0000915 Parcel data;
916 // transaction->data is owned by this function. Parcel borrows this data and
917 // only holds onto it for the duration of this function call. Parcel will be
918 // deleted before the 'transactionData' object.
Frederick Mayledc07cf82022-05-26 20:30:12 +0000919
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000920 replyStatus =
921 data.rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
922 objectTableSpan.data, objectTableSpan.size,
923 std::move(ancillaryFds), do_nothing_to_transact_data);
924 // Reset to avoid spurious use-after-move warning from clang-tidy.
925 ancillaryFds = std::remove_reference<decltype(ancillaryFds)>::type();
Steven Morelandeff77c12021-04-15 00:37:19 +0000926
Frederick Mayle69a0c992022-05-26 20:38:39 +0000927 if (replyStatus == OK) {
928 if (target) {
929 bool origAllowNested = connection->allowNested;
930 connection->allowNested = !oneway;
Steven Morelandc7d40132021-06-10 03:42:11 +0000931
Frederick Mayle69a0c992022-05-26 20:38:39 +0000932 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000933
Frederick Mayle69a0c992022-05-26 20:38:39 +0000934 connection->allowNested = origAllowNested;
935 } else {
936 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000937
Frederick Mayle69a0c992022-05-26 20:38:39 +0000938 switch (transaction->code) {
939 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
940 replyStatus = reply.writeInt32(session->getMaxIncomingThreads());
941 break;
942 }
943 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
944 // for client connections, this should always report the value
945 // originally returned from the server, so this is asserting
946 // that it exists
947 replyStatus = reply.writeByteVector(session->mId);
948 break;
949 }
950 default: {
951 sp<RpcServer> server = session->server();
952 if (server) {
953 switch (transaction->code) {
954 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
955 sp<IBinder> root = session->mSessionSpecificRootObject
956 ?: server->getRootObject();
957 replyStatus = reply.writeStrongBinder(root);
958 break;
959 }
960 default: {
961 replyStatus = UNKNOWN_TRANSACTION;
962 }
Steven Moreland103424e2021-06-02 18:16:19 +0000963 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000964 } else {
965 ALOGE("Special command sent, but no server object attached.");
Steven Moreland103424e2021-06-02 18:16:19 +0000966 }
Steven Morelandf137de92021-04-24 01:54:26 +0000967 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000968 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000969 }
970 }
971 }
972
Steven Morelandc7d40132021-06-10 03:42:11 +0000973 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000974 if (replyStatus != OK) {
975 ALOGW("Oneway call failed with error: %d", replyStatus);
976 }
977
Steven Moreland5623d1a2021-09-10 15:45:34 -0700978 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
979 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000980
981 // Check to see if there is another asynchronous transaction to process.
982 // This behavior differs from binder behavior, since in the binder
983 // driver, asynchronous transactions will be processed after existing
984 // pending binder transactions on the queue. The downside of this is
985 // that asynchronous transactions can be drowned out by synchronous
986 // transactions. However, we have no easy way to queue these
987 // transactions after the synchronous transactions we may want to read
988 // from the wire. So, in socket binder here, we have the opposite
989 // downside: asynchronous transactions may drown out synchronous
990 // transactions.
991 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000992 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000993 auto it = mNodeForAddress.find(addr);
994 // last refcount dropped after this transaction happened
995 if (it == mNodeForAddress.end()) return OK;
996
Steven Morelandc9d7b532021-06-04 20:57:41 +0000997 if (!nodeProgressAsyncNumber(&it->second)) {
998 _l.unlock();
999 (void)session->shutdownAndWait(false);
1000 return DEAD_OBJECT;
1001 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001002
1003 if (it->second.asyncTodo.size() == 0) return OK;
1004 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001005 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
1006 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001007
1008 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +00001009 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +00001010 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +00001011 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
1012
Steven Morelandada72bd2021-06-09 23:29:13 +00001013 // reset up arguments
1014 transactionData = std::move(todo.data);
Steven Moreland3903bf02021-09-27 16:05:24 -07001015 LOG_ALWAYS_FATAL_IF(target != todo.ref,
1016 "async list should be associated with a binder");
Steven Morelandf5174272021-05-25 00:39:28 +00001017
Steven Moreland5553ac42020-11-11 02:14:45 +00001018 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +00001019 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +00001020 }
1021 }
Steven Morelandd8083312021-09-22 13:37:10 -07001022
1023 // done processing all the async commands on this binder that we can, so
1024 // write decstrongs on the binder
1025 if (addr != 0 && replyStatus == OK) {
1026 return flushExcessBinderRefs(session, addr, target);
1027 }
1028
Steven Moreland5553ac42020-11-11 02:14:45 +00001029 return OK;
1030 }
1031
Steven Moreland6709cf42021-09-30 15:21:54 -07001032 // Binder refs are flushed for oneway calls only after all calls which are
1033 // built up are executed. Otherwise, they fill up the binder buffer.
1034 if (addr != 0 && replyStatus == OK) {
1035 replyStatus = flushExcessBinderRefs(session, addr, target);
1036 }
1037
Frederick Mayle69a0c992022-05-26 20:38:39 +00001038 std::string errorMsg;
1039 if (status_t status = validateParcel(session, reply, &errorMsg); status != OK) {
1040 ALOGE("Reply Parcel failed validation: %s", errorMsg.c_str());
1041 // Forward the error to the client of the transaction.
1042 reply.freeData();
1043 reply.markForRpc(session);
1044 replyStatus = status;
1045 }
1046
1047 auto* rpcFields = reply.maybeRpcFields();
1048 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
1049
Frederick Mayledc07cf82022-05-26 20:30:12 +00001050 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
1051
Frederick Mayle69a0c992022-05-26 20:38:39 +00001052 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
1053 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +00001054
Frederick Mayle778c0902022-05-27 01:14:57 +00001055 uint32_t bodySize;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001056 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(rpcReplyWireSize, reply.dataSize(), &bodySize) ||
1057 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
1058 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +00001059 "Too much data for reply %zu", reply.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +00001060 RpcWireHeader cmdReply{
1061 .command = RPC_COMMAND_REPLY,
Frederick Mayle778c0902022-05-27 01:14:57 +00001062 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +00001063 };
Steven Moreland5553ac42020-11-11 02:14:45 +00001064 RpcWireReply rpcReply{
1065 .status = replyStatus,
Frederick Mayledc07cf82022-05-26 20:30:12 +00001066 // NOTE: Not necessarily written to socket depending on session
1067 // version.
1068 // NOTE: bodySize didn't overflow => this cast is safe
1069 .parcelDataSize = static_cast<uint32_t>(reply.dataSize()),
1070 .reserved = {0, 0, 0},
Steven Moreland5553ac42020-11-11 02:14:45 +00001071 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001072 iovec iovs[]{
1073 {&cmdReply, sizeof(RpcWireHeader)},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001074 {&rpcReply, rpcReplyWireSize},
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001075 {const_cast<uint8_t*>(reply.data()), reply.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001076 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001077 };
Frederick Mayle69a0c992022-05-26 20:38:39 +00001078 return rpcSend(connection, session, "reply", iovs, arraysize(iovs), std::nullopt,
1079 rpcFields->mFds.get());
Steven Moreland5553ac42020-11-11 02:14:45 +00001080}
1081
Steven Moreland5ae62562021-06-10 03:21:42 +00001082status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
1083 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001084 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
1085
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001086 if (command.bodySize != sizeof(RpcDecStrong)) {
1087 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcDecStrong. Terminating!",
1088 sizeof(RpcDecStrong), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001089 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001090 return BAD_VALUE;
1091 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001092
Frederick Mayleb86cda42022-06-09 23:17:45 +00001093 RpcDecStrong body;
1094 iovec iov{&body, sizeof(RpcDecStrong)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001095 if (status_t status = rpcRec(connection, session, "dec ref body", &iov, 1, nullptr);
1096 status != OK)
Frederick Mayleb86cda42022-06-09 23:17:45 +00001097 return status;
1098
1099 uint64_t addr = RpcWireAddress::toRaw(body.address);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001100 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001101 auto it = mNodeForAddress.find(addr);
1102 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001103 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001104 return OK;
1105 }
1106
1107 sp<IBinder> target = it->second.binder.promote();
1108 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001109 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
1110 ". Terminating!",
1111 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001112 _l.unlock();
1113 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001114 return BAD_VALUE;
1115 }
1116
Frederick Mayleb86cda42022-06-09 23:17:45 +00001117 if (it->second.timesSent < body.amount) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001118 ALOGE("Record of sending binder %zu times, but requested decStrong for %" PRIu64 " of %u",
Frederick Mayleb86cda42022-06-09 23:17:45 +00001119 it->second.timesSent, addr, body.amount);
Steven Moreland5553ac42020-11-11 02:14:45 +00001120 return OK;
1121 }
1122
Steven Moreland5623d1a2021-09-10 15:45:34 -07001123 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
1124 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001125
Frederick Mayleb86cda42022-06-09 23:17:45 +00001126 LOG_RPC_DETAIL("Processing dec strong of %" PRIu64 " by %u from %zu", addr, body.amount,
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001127 it->second.timesSent);
1128
Frederick Mayleb86cda42022-06-09 23:17:45 +00001129 it->second.timesSent -= body.amount;
Steven Moreland31bde7a2021-06-04 00:57:36 +00001130 sp<IBinder> tempHold = tryEraseNode(it);
1131 _l.unlock();
1132 tempHold = nullptr; // destructor may make binder calls on this session
1133
1134 return OK;
1135}
1136
Frederick Mayle69a0c992022-05-26 20:38:39 +00001137status_t RpcState::validateParcel(const sp<RpcSession>& session, const Parcel& parcel,
1138 std::string* errorMsg) {
1139 auto* rpcFields = parcel.maybeRpcFields();
1140 if (rpcFields == nullptr) {
1141 *errorMsg = "Parcel not crafted for RPC call";
1142 return BAD_TYPE;
1143 }
1144
1145 if (rpcFields->mSession != session) {
1146 *errorMsg = "Parcel's session doesn't match";
1147 return BAD_TYPE;
1148 }
1149
1150 uint32_t protocolVersion = session->getProtocolVersion().value();
1151 if (protocolVersion < RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE &&
1152 !rpcFields->mObjectPositions.empty()) {
1153 *errorMsg = StringPrintf("Parcel has attached objects but the session's protocol version "
1154 "(%" PRIu32 ") is too old, must be at least %" PRIu32,
1155 protocolVersion,
1156 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE);
1157 return BAD_VALUE;
1158 }
1159
1160 if (rpcFields->mFds && !rpcFields->mFds->empty()) {
1161 switch (session->getFileDescriptorTransportMode()) {
1162 case RpcSession::FileDescriptorTransportMode::NONE:
1163 *errorMsg =
1164 "Parcel has file descriptors, but no file descriptor transport is enabled";
1165 return FDS_NOT_ALLOWED;
1166 case RpcSession::FileDescriptorTransportMode::UNIX: {
1167 constexpr size_t kMaxFdsPerMsg = 253;
1168 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
1169 *errorMsg = StringPrintf("Too many file descriptors in Parcel for unix "
1170 "domain socket: %zu (max is %zu)",
1171 rpcFields->mFds->size(), kMaxFdsPerMsg);
1172 return BAD_VALUE;
1173 }
1174 }
1175 }
1176 }
1177
1178 return OK;
1179}
1180
Steven Moreland5623d1a2021-09-10 15:45:34 -07001181sp<IBinder> RpcState::tryEraseNode(std::map<uint64_t, BinderNode>::iterator& it) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001182 sp<IBinder> ref;
1183
Steven Moreland5553ac42020-11-11 02:14:45 +00001184 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001185 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +00001186
1187 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +00001188 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
1189 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +00001190 mNodeForAddress.erase(it);
1191 }
1192 }
1193
Steven Moreland31bde7a2021-06-04 00:57:36 +00001194 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +00001195}
1196
Steven Morelandc9d7b532021-06-04 20:57:41 +00001197bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +00001198 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
1199 // a single binder
1200 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
1201 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +00001202 return false;
1203 }
1204 node->asyncNumber++;
1205 return true;
1206}
1207
Steven Moreland5553ac42020-11-11 02:14:45 +00001208} // namespace android