blob: c411f4fed37795d56edd565a46fbbdcc10aa66a5 [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;
Steven Moreland7e2675c2022-09-28 23:34:52 +000044 [[clang::no_destroy]] static RpcMutex 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
Devin Moore66d5b7a2022-07-07 21:42:10 +0000229status_t RpcState::sendObituaries(const sp<RpcSession>& session) {
230 RpcMutexUniqueLock _l(mNodeMutex);
231
232 // Gather strong pointers to all of the remote binders for this session so
233 // we hold the strong references. remoteBinder() returns a raw pointer.
234 // Send the obituaries and drop the strong pointers outside of the lock so
235 // the destructors and the onBinderDied calls are not done while locked.
236 std::vector<sp<IBinder>> remoteBinders;
237 for (const auto& [_, binderNode] : mNodeForAddress) {
238 if (auto binder = binderNode.binder.promote()) {
239 remoteBinders.push_back(std::move(binder));
240 }
241 }
242 _l.unlock();
243
244 for (const auto& binder : remoteBinders) {
245 if (binder->remoteBinder() &&
246 binder->remoteBinder()->getPrivateAccessor().rpcSession() == session) {
247 binder->remoteBinder()->sendObituary();
248 }
249 }
250 return OK;
251}
252
Steven Moreland5553ac42020-11-11 02:14:45 +0000253size_t RpcState::countBinders() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000254 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000255 return mNodeForAddress.size();
256}
257
258void RpcState::dump() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000259 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000260 dumpLocked();
261}
262
Steven Morelandc9d7b532021-06-04 20:57:41 +0000263void RpcState::clear() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000264 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000265
266 if (mTerminated) {
267 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
268 "New state should be impossible after terminating!");
269 return;
270 }
Steven Moreland0092fe32022-07-15 00:15:34 +0000271 mTerminated = true;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000272
273 if (SHOULD_LOG_RPC_DETAIL) {
274 ALOGE("RpcState::clear()");
275 dumpLocked();
276 }
277
Steven Moreland0092fe32022-07-15 00:15:34 +0000278 // invariants
Steven Morelandc9d7b532021-06-04 20:57:41 +0000279 for (auto& [address, node] : mNodeForAddress) {
Steven Moreland0092fe32022-07-15 00:15:34 +0000280 bool guaranteedHaveBinder = node.timesSent > 0;
281 if (guaranteedHaveBinder) {
282 LOG_ALWAYS_FATAL_IF(node.sentRef == nullptr,
283 "Binder expected to be owned with address: %" PRIu64 " %s", address,
284 node.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000285 }
286 }
287
Steven Moreland0092fe32022-07-15 00:15:34 +0000288 // if the destructor of a binder object makes another RPC call, then calling
289 // decStrong could deadlock. So, we must hold onto these binders until
290 // mNodeMutex is no longer taken.
291 auto temp = std::move(mNodeForAddress);
292 mNodeForAddress.clear(); // RpcState isn't reusable, but for future/explicit
Steven Morelandc9d7b532021-06-04 20:57:41 +0000293
294 _l.unlock();
Steven Moreland0092fe32022-07-15 00:15:34 +0000295 temp.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000296}
297
298void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000299 ALOGE("DUMP OF RpcState %p", this);
300 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
301 for (const auto& [address, node] : mNodeForAddress) {
Steven Moreland3fa32922022-07-14 18:45:51 +0000302 ALOGE("- address: %" PRIu64 " %s", address, node.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000303 }
304 ALOGE("END DUMP OF RpcState");
305}
306
Steven Moreland3fa32922022-07-14 18:45:51 +0000307std::string RpcState::BinderNode::toString() const {
308 sp<IBinder> strongBinder = this->binder.promote();
309
310 const char* desc;
311 if (strongBinder) {
312 if (strongBinder->remoteBinder()) {
313 if (strongBinder->remoteBinder()->isRpcBinder()) {
314 desc = "(rpc binder proxy)";
315 } else {
316 desc = "(binder proxy)";
317 }
318 } else {
319 desc = "(local binder)";
320 }
321 } else {
322 desc = "(not promotable)";
323 }
324
325 return StringPrintf("node{%p times sent: %zu times recd: %zu type: %s}",
326 this->binder.unsafe_get(), this->timesSent, this->timesRecd, desc);
327}
Steven Moreland5553ac42020-11-11 02:14:45 +0000328
Steven Morelanddbe71832021-05-12 23:31:00 +0000329RpcState::CommandData::CommandData(size_t size) : mSize(size) {
330 // The maximum size for regular binder is 1MB for all concurrent
331 // transactions. A very small proportion of transactions are even
332 // larger than a page, but we need to avoid allocating too much
333 // data on behalf of an arbitrary client, or we could risk being in
334 // a position where a single additional allocation could run out of
335 // memory.
336 //
337 // Note, this limit may not reflect the total amount of data allocated for a
338 // transaction (in some cases, additional fixed size amounts are added),
339 // though for rough consistency, we should avoid cases where this data type
340 // is used for multiple dynamic allocations for a single transaction.
341 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
342 if (size == 0) return;
343 if (size > kMaxTransactionAllocation) {
344 ALOGW("Transaction requested too much data allocation %zu", size);
345 return;
346 }
347 mData.reset(new (std::nothrow) uint8_t[size]);
348}
349
Frederick Mayle69a0c992022-05-26 20:38:39 +0000350status_t RpcState::rpcSend(
351 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
352 const char* what, iovec* iovs, int niovs,
353 const std::optional<android::base::function_ref<status_t()>>& altPoll,
354 const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800355 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000356 LOG_RPC_DETAIL("Sending %s (part %d of %d) on RpcTransport %p: %s",
357 what, i + 1, niovs, connection->rpcTransport.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000358 android::base::HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000359 }
360
Yifan Hong702115c2021-06-24 15:39:18 -0700361 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700362 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
Frederick Mayle69a0c992022-05-26 20:38:39 +0000363 iovs, niovs, altPoll,
364 ancillaryFds);
Steven Moreland798e0d12021-07-14 23:19:25 +0000365 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800366 LOG_RPC_DETAIL("Failed to write %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700367 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000368 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000369 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000370 }
371
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000372 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000373}
374
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000375status_t RpcState::rpcRec(
376 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
377 const char* what, iovec* iovs, int niovs,
378 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
379 if (status_t status =
380 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
381 iovs, niovs, std::nullopt,
382 ancillaryFds);
Steven Morelandee3f4662021-05-22 01:07:33 +0000383 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800384 LOG_RPC_DETAIL("Failed to read %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700385 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandae58f432021-08-05 17:53:16 -0700386 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000387 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000388 }
389
Colin Cross9adfeaf2022-01-21 17:22:09 -0800390 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000391 LOG_RPC_DETAIL("Received %s (part %d of %d) on RpcTransport %p: %s",
392 what, i + 1, niovs, connection->rpcTransport.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000393 android::base::HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
394 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000395 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000396}
397
Steven Morelandbf57bce2021-07-26 15:26:12 -0700398status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
399 const sp<RpcSession>& session, uint32_t* version) {
400 RpcNewSessionResponse response;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000401 iovec iov{&response, sizeof(response)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000402 if (status_t status = rpcRec(connection, session, "new session response", &iov, 1, nullptr);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700403 status != OK) {
404 return status;
405 }
406 *version = response.version;
407 return OK;
408}
409
Steven Moreland5ae62562021-06-10 03:21:42 +0000410status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
411 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000412 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000413 .msg = RPC_CONNECTION_INIT_OKAY,
414 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000415 iovec iov{&init, sizeof(init)};
Devin Moore695368f2022-06-03 22:29:14 +0000416 return rpcSend(connection, session, "connection init", &iov, 1, std::nullopt);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000417}
418
Steven Moreland5ae62562021-06-10 03:21:42 +0000419status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
420 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000421 RpcOutgoingConnectionInit init;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000422 iovec iov{&init, sizeof(init)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000423 if (status_t status = rpcRec(connection, session, "connection init", &iov, 1, nullptr);
424 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000425 return status;
426
427 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
428 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
429 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
430 init.msg);
431 return BAD_VALUE;
432 }
433 return OK;
434}
435
Steven Moreland5ae62562021-06-10 03:21:42 +0000436sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
437 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000438 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000439 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000440 Parcel reply;
441
Steven Moreland5623d1a2021-09-10 15:45:34 -0700442 status_t status =
443 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000444 if (status != OK) {
445 ALOGE("Error getting root object: %s", statusToString(status).c_str());
446 return nullptr;
447 }
448
449 return reply.readStrongBinder();
450}
451
Steven Moreland5ae62562021-06-10 03:21:42 +0000452status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
453 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000454 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000455 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000456 Parcel reply;
457
Steven Moreland5623d1a2021-09-10 15:45:34 -0700458 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
459 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000460 if (status != OK) {
461 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
462 return status;
463 }
464
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000465 int32_t maxThreads;
466 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000467 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000468 if (maxThreads <= 0) {
469 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000470 return BAD_VALUE;
471 }
472
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000473 *maxThreadsOut = maxThreads;
474 return OK;
475}
476
Steven Moreland5ae62562021-06-10 03:21:42 +0000477status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700478 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000479 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000480 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000481 Parcel reply;
482
Steven Moreland5623d1a2021-09-10 15:45:34 -0700483 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
484 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000485 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000486 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000487 return status;
488 }
489
Steven Moreland826367f2021-09-10 14:05:31 -0700490 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000491}
492
Steven Moreland5ae62562021-06-10 03:21:42 +0000493status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
494 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
495 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000496 std::string errorMsg;
497 if (status_t status = validateParcel(session, data, &errorMsg); status != OK) {
498 ALOGE("Refusing to send RPC on binder %p code %" PRIu32 ": Parcel %p failed validation: %s",
499 binder.get(), code, &data, errorMsg.c_str());
500 return status;
Steven Morelandf5174272021-05-25 00:39:28 +0000501 }
Steven Moreland5623d1a2021-09-10 15:45:34 -0700502 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000503 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
504
Steven Moreland5ae62562021-06-10 03:21:42 +0000505 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000506}
507
Steven Moreland5ae62562021-06-10 03:21:42 +0000508status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700509 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000510 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000511 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
512 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
513
Steven Moreland5553ac42020-11-11 02:14:45 +0000514 uint64_t asyncNumber = 0;
515
Steven Moreland5623d1a2021-09-10 15:45:34 -0700516 if (address != 0) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000517 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000518 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
519 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700520 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
521 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000522
523 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000524 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000525 if (!nodeProgressAsyncNumber(&it->second)) {
526 _l.unlock();
527 (void)session->shutdownAndWait(false);
528 return DEAD_OBJECT;
529 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000530 }
531 }
532
Frederick Mayle69a0c992022-05-26 20:38:39 +0000533 auto* rpcFields = data.maybeRpcFields();
534 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
535
536 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
537 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +0000538
Frederick Mayle778c0902022-05-27 01:14:57 +0000539 uint32_t bodySize;
540 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(sizeof(RpcWireTransaction), data.dataSize(),
Frederick Mayledc07cf82022-05-26 20:30:12 +0000541 &bodySize) ||
542 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
543 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +0000544 "Too much data %zu", data.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +0000545 RpcWireHeader command{
546 .command = RPC_COMMAND_TRANSACT,
Frederick Mayle778c0902022-05-27 01:14:57 +0000547 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +0000548 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700549
Steven Moreland5553ac42020-11-11 02:14:45 +0000550 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700551 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000552 .code = code,
553 .flags = flags,
554 .asyncNumber = asyncNumber,
Frederick Mayledc07cf82022-05-26 20:30:12 +0000555 // bodySize didn't overflow => this cast is safe
556 .parcelDataSize = static_cast<uint32_t>(data.dataSize()),
Steven Moreland5553ac42020-11-11 02:14:45 +0000557 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000558
Steven Moreland43921d52021-09-27 17:15:56 -0700559 constexpr size_t kWaitMaxUs = 1000000;
560 constexpr size_t kWaitLogUs = 10000;
561 size_t waitUs = 0;
562
563 // Oneway calls have no sync point, so if many are sent before, whether this
564 // is a twoway or oneway transaction, they may have filled up the socket.
Devin Moore695368f2022-06-03 22:29:14 +0000565 // So, make sure we drain them before polling
Steven Moreland43921d52021-09-27 17:15:56 -0700566
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000567 iovec iovs[]{
568 {&command, sizeof(RpcWireHeader)},
569 {&transaction, sizeof(RpcWireTransaction)},
570 {const_cast<uint8_t*>(data.data()), data.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +0000571 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000572 };
Frederick Mayle69a0c992022-05-26 20:38:39 +0000573 if (status_t status = rpcSend(
574 connection, session, "transaction", iovs, arraysize(iovs),
575 [&] {
576 if (waitUs > kWaitLogUs) {
577 ALOGE("Cannot send command, trying to process pending refcounts. Waiting "
578 "%zuus. Too many oneway calls?",
579 waitUs);
580 }
Devin Moore695368f2022-06-03 22:29:14 +0000581
Frederick Mayle69a0c992022-05-26 20:38:39 +0000582 if (waitUs > 0) {
583 usleep(waitUs);
584 waitUs = std::min(kWaitMaxUs, waitUs * 2);
585 } else {
586 waitUs = 1;
587 }
Devin Moore695368f2022-06-03 22:29:14 +0000588
Frederick Mayle69a0c992022-05-26 20:38:39 +0000589 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
590 },
591 rpcFields->mFds.get());
Steven Moreland43921d52021-09-27 17:15:56 -0700592 status != OK) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000593 // TODO(b/167966510): need to undo onBinderLeaving - we know the
594 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000595 return status;
Steven Moreland43921d52021-09-27 17:15:56 -0700596 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000597
598 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700599 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
600 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000601
602 // Do not wait on result.
Steven Moreland43921d52021-09-27 17:15:56 -0700603 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000604 }
605
606 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
607
Steven Moreland5ae62562021-06-10 03:21:42 +0000608 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000609}
610
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000611static void cleanup_reply_data(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
612 size_t objectsCount) {
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000613 delete[] const_cast<uint8_t*>(data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000614 (void)dataSize;
615 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000616 (void)objectsCount;
Steven Moreland5553ac42020-11-11 02:14:45 +0000617}
618
Steven Moreland5ae62562021-06-10 03:21:42 +0000619status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
620 const sp<RpcSession>& session, Parcel* reply) {
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000621 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000622 RpcWireHeader command;
623 while (true) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000624 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000625 if (status_t status = rpcRec(connection, session, "command header (for reply)", &iov, 1,
626 enableAncillaryFds(session->getFileDescriptorTransportMode())
627 ? &ancillaryFds
628 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000629 status != OK)
630 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000631
632 if (command.command == RPC_COMMAND_REPLY) break;
633
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000634 if (status_t status = processCommand(connection, session, command, CommandType::ANY,
635 std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000636 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000637 return status;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000638
639 // Reset to avoid spurious use-after-move warning from clang-tidy.
640 ancillaryFds = decltype(ancillaryFds)();
Steven Moreland5553ac42020-11-11 02:14:45 +0000641 }
642
Frederick Mayledc07cf82022-05-26 20:30:12 +0000643 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
644
645 if (command.bodySize < rpcReplyWireSize) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000646 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
647 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000648 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000649 return BAD_VALUE;
650 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000651
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000652 RpcWireReply rpcReply;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000653 memset(&rpcReply, 0, sizeof(RpcWireReply)); // zero because of potential short read
654
655 CommandData data(command.bodySize - rpcReplyWireSize);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000656 if (!data.valid()) return NO_MEMORY;
657
658 iovec iovs[]{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000659 {&rpcReply, rpcReplyWireSize},
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000660 {data.data(), data.size()},
661 };
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000662 if (status_t status = rpcRec(connection, session, "reply body", iovs, arraysize(iovs), nullptr);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000663 status != OK)
664 return status;
Frederick Mayle69a0c992022-05-26 20:38:39 +0000665
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000666 if (rpcReply.status != OK) return rpcReply.status;
667
Frederick Mayledc07cf82022-05-26 20:30:12 +0000668 Span<const uint8_t> parcelSpan = {data.data(), data.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000669 Span<const uint32_t> objectTableSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000670 if (session->getProtocolVersion().value() >=
671 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000672 std::optional<Span<const uint8_t>> objectTableBytes =
673 parcelSpan.splitOff(rpcReply.parcelDataSize);
674 if (!objectTableBytes.has_value()) {
675 ALOGE("Parcel size larger than available bytes: %" PRId32 " vs %zu. Terminating!",
676 rpcReply.parcelDataSize, parcelSpan.byteSize());
677 (void)session->shutdownAndWait(false);
678 return BAD_VALUE;
679 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000680 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000681 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000682 if (!maybeSpan.has_value()) {
683 ALOGE("Bad object table size inferred from RpcWireReply. Saw bodySize=%" PRId32
684 " sizeofHeader=%zu parcelSize=%" PRId32 " objectTableBytesSize=%zu. Terminating!",
685 command.bodySize, rpcReplyWireSize, rpcReply.parcelDataSize,
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000686 objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000687 return BAD_VALUE;
688 }
689 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000690 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000691
Frederick Mayledc07cf82022-05-26 20:30:12 +0000692 data.release();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000693 return reply->rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
694 objectTableSpan.data, objectTableSpan.size,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000695 std::move(ancillaryFds), cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000696}
697
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000698status_t RpcState::sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection,
699 const sp<RpcSession>& session, uint64_t addr,
700 size_t target) {
701 RpcDecStrong body = {
702 .address = RpcWireAddress::fromRaw(addr),
703 };
704
Steven Moreland5553ac42020-11-11 02:14:45 +0000705 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000706 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000707 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
708 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700709 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
710 "Sending dec strong on unknown address %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000711
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000712 LOG_ALWAYS_FATAL_IF(it->second.timesRecd < target, "Can't dec count of %zu to %zu.",
713 it->second.timesRecd, target);
714
715 // typically this happens when multiple threads send dec refs at the
716 // same time - the transactions will get combined automatically
717 if (it->second.timesRecd == target) return OK;
718
719 body.amount = it->second.timesRecd - target;
720 it->second.timesRecd = target;
721
Steven Moreland31bde7a2021-06-04 00:57:36 +0000722 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
723 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000724 }
725
726 RpcWireHeader cmd = {
727 .command = RPC_COMMAND_DEC_STRONG,
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000728 .bodySize = sizeof(RpcDecStrong),
Steven Moreland5553ac42020-11-11 02:14:45 +0000729 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000730 iovec iovs[]{{&cmd, sizeof(cmd)}, {&body, sizeof(body)}};
Devin Moore695368f2022-06-03 22:29:14 +0000731 return rpcSend(connection, session, "dec ref", iovs, arraysize(iovs), std::nullopt);
Steven Moreland5553ac42020-11-11 02:14:45 +0000732}
733
Steven Moreland5ae62562021-06-10 03:21:42 +0000734status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
735 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700736 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000737
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000738 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000739 RpcWireHeader command;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000740 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000741 if (status_t status =
742 rpcRec(connection, session, "command header (for server)", &iov, 1,
743 enableAncillaryFds(session->getFileDescriptorTransportMode()) ? &ancillaryFds
744 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000745 status != OK)
746 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000747
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000748 return processCommand(connection, session, command, type, std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000749}
750
Steven Moreland5ae62562021-06-10 03:21:42 +0000751status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
752 const sp<RpcSession>& session, CommandType type) {
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000753 while (true) {
Andrei Homescu1975aaa2022-03-19 02:34:57 +0000754 status_t status = connection->rpcTransport->pollRead();
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000755 if (status == WOULD_BLOCK) break;
756 if (status != OK) return status;
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000757
758 status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000759 if (status != OK) return status;
760 }
761 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000762}
763
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000764status_t RpcState::processCommand(
765 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
766 const RpcWireHeader& command, CommandType type,
767 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland32150282021-11-12 22:54:53 +0000768#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000769 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
770 IPCThreadState::SpGuard spGuard{
771 .address = __builtin_frame_address(0),
Steven Morelande42ffd02022-07-06 21:46:23 +0000772 .context = "processing binder RPC command (where RpcServer::setPerSessionRootObject is "
773 "used to distinguish callers)",
Steven Morelandd7302072021-05-15 01:32:04 +0000774 };
775 const IPCThreadState::SpGuard* origGuard;
776 if (kernelBinderState != nullptr) {
777 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
778 }
Steven Moreland32150282021-11-12 22:54:53 +0000779
780 base::ScopeGuard guardUnguard = [&]() {
Steven Morelandd7302072021-05-15 01:32:04 +0000781 if (kernelBinderState != nullptr) {
782 kernelBinderState->restoreGetCallingSpGuard(origGuard);
783 }
784 };
Steven Moreland32150282021-11-12 22:54:53 +0000785#endif // BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000786
Steven Moreland5553ac42020-11-11 02:14:45 +0000787 switch (command.command) {
788 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000789 if (type != CommandType::ANY) return BAD_TYPE;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000790 return processTransact(connection, session, command, std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000791 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000792 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000793 }
794
795 // We should always know the version of the opposing side, and since the
796 // RPC-binder-level wire protocol is not self synchronizing, we have no way
797 // to understand where the current command ends and the next one begins. We
798 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000799 // to kill us, so ending the session for misbehaving client.
800 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000801 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000802 return DEAD_OBJECT;
803}
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000804status_t RpcState::processTransact(
805 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
806 const RpcWireHeader& command,
807 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000808 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
809
Steven Morelanddbe71832021-05-12 23:31:00 +0000810 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000811 if (!transactionData.valid()) {
812 return NO_MEMORY;
813 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000814 iovec iov{transactionData.data(), transactionData.size()};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000815 if (status_t status = rpcRec(connection, session, "transaction body", &iov, 1, nullptr);
816 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000817 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000818
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000819 return processTransactInternal(connection, session, std::move(transactionData),
820 std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000821}
822
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000823static void do_nothing_to_transact_data(const uint8_t* data, size_t dataSize,
Steven Moreland438cce82021-04-02 18:04:08 +0000824 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland438cce82021-04-02 18:04:08 +0000825 (void)data;
826 (void)dataSize;
827 (void)objects;
828 (void)objectsCount;
829}
830
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000831status_t RpcState::processTransactInternal(
832 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
833 CommandData transactionData,
834 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Morelandada72bd2021-06-09 23:29:13 +0000835 // for 'recursive' calls to this, we have already read and processed the
836 // binder from the transaction data and taken reference counts into account,
837 // so it is cached here.
Steven Moreland3903bf02021-09-27 16:05:24 -0700838 sp<IBinder> target;
Steven Morelandada72bd2021-06-09 23:29:13 +0000839processTransactInternalTailCall:
840
Steven Moreland5553ac42020-11-11 02:14:45 +0000841 if (transactionData.size() < sizeof(RpcWireTransaction)) {
842 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
843 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000844 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000845 return BAD_VALUE;
846 }
847 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
848
Steven Moreland5623d1a2021-09-10 15:45:34 -0700849 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000850 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000851
852 status_t replyStatus = OK;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700853 if (addr != 0) {
Steven Moreland3903bf02021-09-27 16:05:24 -0700854 if (!target) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000855 replyStatus = onBinderEntering(session, addr, &target);
Steven Morelandf5174272021-05-25 00:39:28 +0000856 }
857
Steven Moreland7227c8a2021-06-02 00:24:32 +0000858 if (replyStatus != OK) {
859 // do nothing
860 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000861 // This can happen if the binder is remote in this process, and
862 // another thread has called the last decStrong on this binder.
863 // However, for local binders, it indicates a misbehaving client
864 // (any binder which is being transacted on should be holding a
865 // strong ref count), so in either case, terminating the
866 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700867 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
868 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000869 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000870 replyStatus = BAD_VALUE;
871 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700872 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
873 ". Terminating!",
874 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000875 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000876 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000877 } else if (oneway) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000878 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000879 auto it = mNodeForAddress.find(addr);
880 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700881 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000882 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000883 } else if (transaction->asyncNumber != it->second.asyncNumber) {
884 // we need to process some other asynchronous transaction
885 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000886 it->second.asyncTodo.push(BinderNode::AsyncTodo{
887 .ref = target,
888 .data = std::move(transactionData),
889 .asyncNumber = transaction->asyncNumber,
890 });
Steven Morelandd45be622021-06-04 02:19:37 +0000891
892 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700893 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
894 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000895
896 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
897 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
898 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
899
900 if (numPending >= kArbitraryOnewayCallWarnLevel) {
901 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
902 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
903 _l.unlock();
904 (void)session->shutdownAndWait(false);
905 return FAILED_TRANSACTION;
906 }
907
908 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
909 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
910 target.get(), numPending);
911 }
912 }
Steven Morelandf5174272021-05-25 00:39:28 +0000913 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000914 }
915 }
916 }
917
Steven Moreland5553ac42020-11-11 02:14:45 +0000918 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000919 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000920
921 if (replyStatus == OK) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000922 Span<const uint8_t> parcelSpan = {transaction->data,
923 transactionData.size() -
924 offsetof(RpcWireTransaction, data)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000925 Span<const uint32_t> objectTableSpan;
926 if (session->getProtocolVersion().value() >
Frederick Mayledc07cf82022-05-26 20:30:12 +0000927 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000928 std::optional<Span<const uint8_t>> objectTableBytes =
929 parcelSpan.splitOff(transaction->parcelDataSize);
930 if (!objectTableBytes.has_value()) {
931 ALOGE("Parcel size (%" PRId32 ") greater than available bytes (%zu). Terminating!",
932 transaction->parcelDataSize, parcelSpan.byteSize());
933 (void)session->shutdownAndWait(false);
934 return BAD_VALUE;
935 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000936 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000937 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000938 if (!maybeSpan.has_value()) {
939 ALOGE("Bad object table size inferred from RpcWireTransaction. Saw bodySize=%zu "
940 "sizeofHeader=%zu parcelSize=%" PRId32
941 " objectTableBytesSize=%zu. Terminating!",
942 transactionData.size(), sizeof(RpcWireTransaction),
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000943 transaction->parcelDataSize, objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000944 return BAD_VALUE;
945 }
946 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000947 }
948
Steven Morelandeff77c12021-04-15 00:37:19 +0000949 Parcel data;
950 // transaction->data is owned by this function. Parcel borrows this data and
951 // only holds onto it for the duration of this function call. Parcel will be
952 // deleted before the 'transactionData' object.
Frederick Mayledc07cf82022-05-26 20:30:12 +0000953
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000954 replyStatus =
955 data.rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
956 objectTableSpan.data, objectTableSpan.size,
957 std::move(ancillaryFds), do_nothing_to_transact_data);
958 // Reset to avoid spurious use-after-move warning from clang-tidy.
959 ancillaryFds = std::remove_reference<decltype(ancillaryFds)>::type();
Steven Morelandeff77c12021-04-15 00:37:19 +0000960
Frederick Mayle69a0c992022-05-26 20:38:39 +0000961 if (replyStatus == OK) {
962 if (target) {
963 bool origAllowNested = connection->allowNested;
964 connection->allowNested = !oneway;
Steven Morelandc7d40132021-06-10 03:42:11 +0000965
Frederick Mayle69a0c992022-05-26 20:38:39 +0000966 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000967
Frederick Mayle69a0c992022-05-26 20:38:39 +0000968 connection->allowNested = origAllowNested;
969 } else {
970 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000971
Frederick Mayle69a0c992022-05-26 20:38:39 +0000972 switch (transaction->code) {
973 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
974 replyStatus = reply.writeInt32(session->getMaxIncomingThreads());
975 break;
976 }
977 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
978 // for client connections, this should always report the value
979 // originally returned from the server, so this is asserting
980 // that it exists
981 replyStatus = reply.writeByteVector(session->mId);
982 break;
983 }
984 default: {
985 sp<RpcServer> server = session->server();
986 if (server) {
987 switch (transaction->code) {
988 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
989 sp<IBinder> root = session->mSessionSpecificRootObject
990 ?: server->getRootObject();
991 replyStatus = reply.writeStrongBinder(root);
992 break;
993 }
994 default: {
995 replyStatus = UNKNOWN_TRANSACTION;
996 }
Steven Moreland103424e2021-06-02 18:16:19 +0000997 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000998 } else {
999 ALOGE("Special command sent, but no server object attached.");
Steven Moreland103424e2021-06-02 18:16:19 +00001000 }
Steven Morelandf137de92021-04-24 01:54:26 +00001001 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001002 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001003 }
1004 }
1005 }
1006
Steven Morelandc7d40132021-06-10 03:42:11 +00001007 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001008 if (replyStatus != OK) {
1009 ALOGW("Oneway call failed with error: %d", replyStatus);
1010 }
1011
Steven Moreland5623d1a2021-09-10 15:45:34 -07001012 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
1013 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001014
1015 // Check to see if there is another asynchronous transaction to process.
1016 // This behavior differs from binder behavior, since in the binder
1017 // driver, asynchronous transactions will be processed after existing
1018 // pending binder transactions on the queue. The downside of this is
1019 // that asynchronous transactions can be drowned out by synchronous
1020 // transactions. However, we have no easy way to queue these
1021 // transactions after the synchronous transactions we may want to read
1022 // from the wire. So, in socket binder here, we have the opposite
1023 // downside: asynchronous transactions may drown out synchronous
1024 // transactions.
1025 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001026 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001027 auto it = mNodeForAddress.find(addr);
1028 // last refcount dropped after this transaction happened
1029 if (it == mNodeForAddress.end()) return OK;
1030
Steven Morelandc9d7b532021-06-04 20:57:41 +00001031 if (!nodeProgressAsyncNumber(&it->second)) {
1032 _l.unlock();
1033 (void)session->shutdownAndWait(false);
1034 return DEAD_OBJECT;
1035 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001036
1037 if (it->second.asyncTodo.size() == 0) return OK;
1038 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001039 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
1040 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001041
1042 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +00001043 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +00001044 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +00001045 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
1046
Steven Morelandada72bd2021-06-09 23:29:13 +00001047 // reset up arguments
1048 transactionData = std::move(todo.data);
Steven Moreland3903bf02021-09-27 16:05:24 -07001049 LOG_ALWAYS_FATAL_IF(target != todo.ref,
1050 "async list should be associated with a binder");
Steven Morelandf5174272021-05-25 00:39:28 +00001051
Steven Moreland5553ac42020-11-11 02:14:45 +00001052 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +00001053 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +00001054 }
1055 }
Steven Morelandd8083312021-09-22 13:37:10 -07001056
1057 // done processing all the async commands on this binder that we can, so
1058 // write decstrongs on the binder
1059 if (addr != 0 && replyStatus == OK) {
1060 return flushExcessBinderRefs(session, addr, target);
1061 }
1062
Steven Moreland5553ac42020-11-11 02:14:45 +00001063 return OK;
1064 }
1065
Steven Moreland6709cf42021-09-30 15:21:54 -07001066 // Binder refs are flushed for oneway calls only after all calls which are
1067 // built up are executed. Otherwise, they fill up the binder buffer.
1068 if (addr != 0 && replyStatus == OK) {
1069 replyStatus = flushExcessBinderRefs(session, addr, target);
1070 }
1071
Frederick Mayle69a0c992022-05-26 20:38:39 +00001072 std::string errorMsg;
1073 if (status_t status = validateParcel(session, reply, &errorMsg); status != OK) {
1074 ALOGE("Reply Parcel failed validation: %s", errorMsg.c_str());
1075 // Forward the error to the client of the transaction.
1076 reply.freeData();
1077 reply.markForRpc(session);
1078 replyStatus = status;
1079 }
1080
1081 auto* rpcFields = reply.maybeRpcFields();
1082 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
1083
Frederick Mayledc07cf82022-05-26 20:30:12 +00001084 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
1085
Frederick Mayle69a0c992022-05-26 20:38:39 +00001086 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
1087 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +00001088
Frederick Mayle778c0902022-05-27 01:14:57 +00001089 uint32_t bodySize;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001090 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(rpcReplyWireSize, reply.dataSize(), &bodySize) ||
1091 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
1092 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +00001093 "Too much data for reply %zu", reply.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +00001094 RpcWireHeader cmdReply{
1095 .command = RPC_COMMAND_REPLY,
Frederick Mayle778c0902022-05-27 01:14:57 +00001096 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +00001097 };
Steven Moreland5553ac42020-11-11 02:14:45 +00001098 RpcWireReply rpcReply{
1099 .status = replyStatus,
Frederick Mayledc07cf82022-05-26 20:30:12 +00001100 // NOTE: Not necessarily written to socket depending on session
1101 // version.
1102 // NOTE: bodySize didn't overflow => this cast is safe
1103 .parcelDataSize = static_cast<uint32_t>(reply.dataSize()),
1104 .reserved = {0, 0, 0},
Steven Moreland5553ac42020-11-11 02:14:45 +00001105 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001106 iovec iovs[]{
1107 {&cmdReply, sizeof(RpcWireHeader)},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001108 {&rpcReply, rpcReplyWireSize},
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001109 {const_cast<uint8_t*>(reply.data()), reply.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001110 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001111 };
Frederick Mayle69a0c992022-05-26 20:38:39 +00001112 return rpcSend(connection, session, "reply", iovs, arraysize(iovs), std::nullopt,
1113 rpcFields->mFds.get());
Steven Moreland5553ac42020-11-11 02:14:45 +00001114}
1115
Steven Moreland5ae62562021-06-10 03:21:42 +00001116status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
1117 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001118 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
1119
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001120 if (command.bodySize != sizeof(RpcDecStrong)) {
1121 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcDecStrong. Terminating!",
1122 sizeof(RpcDecStrong), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001123 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001124 return BAD_VALUE;
1125 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001126
Frederick Mayleb86cda42022-06-09 23:17:45 +00001127 RpcDecStrong body;
1128 iovec iov{&body, sizeof(RpcDecStrong)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001129 if (status_t status = rpcRec(connection, session, "dec ref body", &iov, 1, nullptr);
1130 status != OK)
Frederick Mayleb86cda42022-06-09 23:17:45 +00001131 return status;
1132
1133 uint64_t addr = RpcWireAddress::toRaw(body.address);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001134 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001135 auto it = mNodeForAddress.find(addr);
1136 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001137 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001138 return OK;
1139 }
1140
1141 sp<IBinder> target = it->second.binder.promote();
1142 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001143 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
1144 ". Terminating!",
1145 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001146 _l.unlock();
1147 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001148 return BAD_VALUE;
1149 }
1150
Frederick Mayleb86cda42022-06-09 23:17:45 +00001151 if (it->second.timesSent < body.amount) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001152 ALOGE("Record of sending binder %zu times, but requested decStrong for %" PRIu64 " of %u",
Frederick Mayleb86cda42022-06-09 23:17:45 +00001153 it->second.timesSent, addr, body.amount);
Steven Moreland5553ac42020-11-11 02:14:45 +00001154 return OK;
1155 }
1156
Steven Moreland5623d1a2021-09-10 15:45:34 -07001157 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
1158 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001159
Frederick Mayleb86cda42022-06-09 23:17:45 +00001160 LOG_RPC_DETAIL("Processing dec strong of %" PRIu64 " by %u from %zu", addr, body.amount,
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001161 it->second.timesSent);
1162
Frederick Mayleb86cda42022-06-09 23:17:45 +00001163 it->second.timesSent -= body.amount;
Steven Moreland31bde7a2021-06-04 00:57:36 +00001164 sp<IBinder> tempHold = tryEraseNode(it);
1165 _l.unlock();
1166 tempHold = nullptr; // destructor may make binder calls on this session
1167
1168 return OK;
1169}
1170
Frederick Mayle69a0c992022-05-26 20:38:39 +00001171status_t RpcState::validateParcel(const sp<RpcSession>& session, const Parcel& parcel,
1172 std::string* errorMsg) {
1173 auto* rpcFields = parcel.maybeRpcFields();
1174 if (rpcFields == nullptr) {
1175 *errorMsg = "Parcel not crafted for RPC call";
1176 return BAD_TYPE;
1177 }
1178
1179 if (rpcFields->mSession != session) {
1180 *errorMsg = "Parcel's session doesn't match";
1181 return BAD_TYPE;
1182 }
1183
1184 uint32_t protocolVersion = session->getProtocolVersion().value();
1185 if (protocolVersion < RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE &&
1186 !rpcFields->mObjectPositions.empty()) {
1187 *errorMsg = StringPrintf("Parcel has attached objects but the session's protocol version "
1188 "(%" PRIu32 ") is too old, must be at least %" PRIu32,
1189 protocolVersion,
1190 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE);
1191 return BAD_VALUE;
1192 }
1193
1194 if (rpcFields->mFds && !rpcFields->mFds->empty()) {
1195 switch (session->getFileDescriptorTransportMode()) {
1196 case RpcSession::FileDescriptorTransportMode::NONE:
1197 *errorMsg =
1198 "Parcel has file descriptors, but no file descriptor transport is enabled";
1199 return FDS_NOT_ALLOWED;
1200 case RpcSession::FileDescriptorTransportMode::UNIX: {
1201 constexpr size_t kMaxFdsPerMsg = 253;
1202 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
1203 *errorMsg = StringPrintf("Too many file descriptors in Parcel for unix "
1204 "domain socket: %zu (max is %zu)",
1205 rpcFields->mFds->size(), kMaxFdsPerMsg);
1206 return BAD_VALUE;
1207 }
1208 }
1209 }
1210 }
1211
1212 return OK;
1213}
1214
Steven Moreland5623d1a2021-09-10 15:45:34 -07001215sp<IBinder> RpcState::tryEraseNode(std::map<uint64_t, BinderNode>::iterator& it) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001216 sp<IBinder> ref;
1217
Steven Moreland5553ac42020-11-11 02:14:45 +00001218 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001219 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +00001220
1221 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +00001222 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
1223 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +00001224 mNodeForAddress.erase(it);
1225 }
1226 }
1227
Steven Moreland31bde7a2021-06-04 00:57:36 +00001228 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +00001229}
1230
Steven Morelandc9d7b532021-06-04 20:57:41 +00001231bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +00001232 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
1233 // a single binder
1234 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
1235 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +00001236 return false;
1237 }
1238 node->asyncNumber++;
1239 return true;
1240}
1241
Steven Moreland5553ac42020-11-11 02:14:45 +00001242} // namespace android