blob: 03d974d186f22003ba56b3bf65f22ec4582bc1f5 [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
21#include <binder/BpBinder.h>
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000022#include <binder/Functional.h>
Steven Morelandd7302072021-05-15 01:32:04 +000023#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000024#include <binder/RpcServer.h>
25
Steven Moreland54fa6c72025-01-28 01:02:15 +000026#include "Constants.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000027#include "Debug.h"
28#include "RpcWireFormat.h"
Frederick Mayledc07cf82022-05-26 20:30:12 +000029#include "Utils.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000030
Steven Morelandb8176792021-06-22 20:29:21 +000031#include <random>
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +000032#include <sstream>
Steven Morelandb8176792021-06-22 20:29:21 +000033
Steven Moreland5553ac42020-11-11 02:14:45 +000034#include <inttypes.h>
35
Steven Moreland09034a92023-05-31 20:49:11 +000036#ifdef __ANDROID__
37#include <cutils/properties.h>
38#endif
39
Steven Moreland5553ac42020-11-11 02:14:45 +000040namespace android {
41
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000042using namespace android::binder::impl;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070043using android::binder::borrowed_fd;
44using android::binder::unique_fd;
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000045
Devin Moore08256432021-07-02 13:03:49 -070046#if RPC_FLAKE_PRONE
Steven Morelandb8176792021-06-22 20:29:21 +000047void rpcMaybeWaitToFlake() {
Devin Moore08256432021-07-02 13:03:49 -070048 [[clang::no_destroy]] static std::random_device r;
Steven Moreland7e2675c2022-09-28 23:34:52 +000049 [[clang::no_destroy]] static RpcMutex m;
Steven Morelandb8176792021-06-22 20:29:21 +000050 unsigned num;
51 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000052 RpcMutexLockGuard lock(m);
Steven Morelandb8176792021-06-22 20:29:21 +000053 num = r();
54 }
55 if (num % 10 == 0) usleep(num % 1000);
56}
57#endif
58
Frederick Mayle69a0c992022-05-26 20:38:39 +000059static bool enableAncillaryFds(RpcSession::FileDescriptorTransportMode mode) {
60 switch (mode) {
61 case RpcSession::FileDescriptorTransportMode::NONE:
62 return false;
63 case RpcSession::FileDescriptorTransportMode::UNIX:
Andrei Homescu1c18a802022-08-17 04:59:01 +000064 case RpcSession::FileDescriptorTransportMode::TRUSTY:
Frederick Mayle69a0c992022-05-26 20:38:39 +000065 return true;
66 }
Tomasz Wasilczyk7b5430b2023-06-28 14:04:51 -070067 LOG_ALWAYS_FATAL("Invalid FileDescriptorTransportMode: %d", static_cast<int>(mode));
Frederick Mayle69a0c992022-05-26 20:38:39 +000068}
69
Steven Moreland5553ac42020-11-11 02:14:45 +000070RpcState::RpcState() {}
71RpcState::~RpcState() {}
72
Steven Morelandbdb53ab2021-05-05 17:57:41 +000073status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5623d1a2021-09-10 15:45:34 -070074 uint64_t* outAddress) {
Steven Moreland5553ac42020-11-11 02:14:45 +000075 bool isRemote = binder->remoteBinder();
76 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
77
Steven Moreland99157622021-09-13 16:27:34 -070078 if (isRpc && binder->remoteBinder()->getPrivateAccessor().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000079 // We need to be able to send instructions over the socket for how to
80 // connect to a different server, and we also need to let the host
81 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000082 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000083 return INVALID_OPERATION;
84 }
85
86 if (isRemote && !isRpc) {
87 // Without additional work, this would have the effect of using this
88 // process to proxy calls from the socket over to the other process, and
89 // it would make those calls look like they come from us (not over the
90 // sockets). In order to make this work transparently like binder, we
91 // would instead need to send instructions over the socket for how to
92 // connect to the host process, and we also need to let the host process
93 // know this was happening.
94 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
95 return INVALID_OPERATION;
96 }
97
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000098 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000099 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000100
101 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
102 // in RpcState
103 for (auto& [addr, node] : mNodeForAddress) {
104 if (binder == node.binder) {
105 if (isRpc) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700106 // check integrity of data structure
Steven Moreland99157622021-09-13 16:27:34 -0700107 uint64_t actualAddr = binder->remoteBinder()->getPrivateAccessor().rpcAddress();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700108 LOG_ALWAYS_FATAL_IF(addr != actualAddr, "Address mismatch %" PRIu64 " vs %" PRIu64,
109 addr, actualAddr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000110 }
111 node.timesSent++;
112 node.sentRef = binder; // might already be set
113 *outAddress = addr;
114 return OK;
115 }
116 }
117 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
118
Steven Moreland91538242021-06-10 23:35:35 +0000119 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +0000120
Steven Moreland5623d1a2021-09-10 15:45:34 -0700121 // arbitrary limit for maximum number of nodes in a process (otherwise we
122 // might run out of addresses)
123 if (mNodeForAddress.size() > 100000) {
124 return NO_MEMORY;
125 }
126
127 while (true) {
128 RpcWireAddress address{
129 .options = RPC_WIRE_ADDRESS_OPTION_CREATED,
130 .address = mNextId,
131 };
132 if (forServer) {
133 address.options |= RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
134 }
135
136 // avoid ubsan abort
137 if (mNextId >= std::numeric_limits<uint32_t>::max()) {
138 mNextId = 0;
139 } else {
140 mNextId++;
141 }
142
143 auto&& [it, inserted] = mNodeForAddress.insert({RpcWireAddress::toRaw(address),
Steven Moreland91538242021-06-10 23:35:35 +0000144 BinderNode{
145 .binder = binder,
Steven Moreland91538242021-06-10 23:35:35 +0000146 .sentRef = binder,
Andrei Homescu5a036f32022-03-08 22:54:40 +0000147 .timesSent = 1,
Steven Moreland91538242021-06-10 23:35:35 +0000148 }});
149 if (inserted) {
150 *outAddress = it->first;
151 return OK;
152 }
Steven Moreland91538242021-06-10 23:35:35 +0000153 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000154}
155
Steven Moreland5623d1a2021-09-10 15:45:34 -0700156status_t RpcState::onBinderEntering(const sp<RpcSession>& session, uint64_t address,
Steven Moreland7227c8a2021-06-02 00:24:32 +0000157 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000158 // ensure that: if we want to use addresses for something else in the future (for
159 // instance, allowing transitive binder sends), that we don't accidentally
160 // send those addresses to old server. Accidentally ignoring this in that
161 // case and considering the binder to be recognized could cause this
162 // process to accidentally proxy transactions for that binder. Of course,
163 // if we communicate with a binder, it could always be proxying
164 // information. However, we want to make sure that isn't done on accident
165 // by a client.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700166 RpcWireAddress addr = RpcWireAddress::fromRaw(address);
167 constexpr uint32_t kKnownOptions =
168 RPC_WIRE_ADDRESS_OPTION_CREATED | RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
169 if (addr.options & ~kKnownOptions) {
170 ALOGE("Address is of an unknown type, rejecting: %" PRIu64, address);
Steven Moreland91538242021-06-10 23:35:35 +0000171 return BAD_VALUE;
172 }
173
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000174 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000175 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000176
177 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000178 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000179
180 // implicitly have strong RPC refcount, since we received this binder
181 it->second.timesRecd++;
Steven Morelandd8083312021-09-22 13:37:10 -0700182 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000183 }
184
Steven Moreland91538242021-06-10 23:35:35 +0000185 // we don't know about this binder, so the other side of the connection
186 // should have created it.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700187 if ((addr.options & RPC_WIRE_ADDRESS_OPTION_FOR_SERVER) == !!session->server()) {
188 ALOGE("Server received unrecognized address which we should own the creation of %" PRIu64,
189 address);
Steven Moreland91538242021-06-10 23:35:35 +0000190 return BAD_VALUE;
191 }
192
Steven Moreland5553ac42020-11-11 02:14:45 +0000193 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
194 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
195
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000196 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000197 // device global binders in the RPC world).
Steven Moreland99157622021-09-13 16:27:34 -0700198 it->second.binder = *out = BpBinder::PrivateAccessor::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000199 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000200 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000201}
202
Steven Morelandd8083312021-09-22 13:37:10 -0700203status_t RpcState::flushExcessBinderRefs(const sp<RpcSession>& session, uint64_t address,
204 const sp<IBinder>& binder) {
Steven Morelande96ed0e2021-09-27 17:43:53 -0700205 // We can flush all references when the binder is destroyed. No need to send
206 // extra reference counting packets now.
207 if (binder->remoteBinder()) return OK;
208
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000209 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandd8083312021-09-22 13:37:10 -0700210 if (mTerminated) return DEAD_OBJECT;
211
212 auto it = mNodeForAddress.find(address);
213
214 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Can't be deleted while we hold sp<>");
215 LOG_ALWAYS_FATAL_IF(it->second.binder != binder,
216 "Caller of flushExcessBinderRefs using inconsistent arguments");
217
Steven Morelande96ed0e2021-09-27 17:43:53 -0700218 LOG_ALWAYS_FATAL_IF(it->second.timesSent <= 0, "Local binder must have been sent %p",
219 binder.get());
Steven Morelandd8083312021-09-22 13:37:10 -0700220
Steven Morelande96ed0e2021-09-27 17:43:53 -0700221 // For a local binder, we only need to know that we sent it. Now that we
222 // have an sp<> for this call, we don't need anything more. If the other
223 // process is done with this binder, it needs to know we received the
224 // refcount associated with this call, so we can acknowledge that we
225 // received it. Once (or if) it has no other refcounts, it would reply with
226 // its own decStrong so that it could be removed from this session.
227 if (it->second.timesRecd != 0) {
Steven Morelandd8083312021-09-22 13:37:10 -0700228 _l.unlock();
229
Steven Morelande96ed0e2021-09-27 17:43:53 -0700230 return session->sendDecStrongToTarget(address, 0);
Steven Morelandd8083312021-09-22 13:37:10 -0700231 }
232
233 return OK;
234}
235
Devin Moore66d5b7a2022-07-07 21:42:10 +0000236status_t RpcState::sendObituaries(const sp<RpcSession>& session) {
237 RpcMutexUniqueLock _l(mNodeMutex);
238
239 // Gather strong pointers to all of the remote binders for this session so
240 // we hold the strong references. remoteBinder() returns a raw pointer.
241 // Send the obituaries and drop the strong pointers outside of the lock so
242 // the destructors and the onBinderDied calls are not done while locked.
243 std::vector<sp<IBinder>> remoteBinders;
244 for (const auto& [_, binderNode] : mNodeForAddress) {
245 if (auto binder = binderNode.binder.promote()) {
246 remoteBinders.push_back(std::move(binder));
247 }
248 }
249 _l.unlock();
250
251 for (const auto& binder : remoteBinders) {
252 if (binder->remoteBinder() &&
253 binder->remoteBinder()->getPrivateAccessor().rpcSession() == session) {
254 binder->remoteBinder()->sendObituary();
255 }
256 }
257 return OK;
258}
259
Steven Moreland5553ac42020-11-11 02:14:45 +0000260size_t RpcState::countBinders() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000261 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000262 return mNodeForAddress.size();
263}
264
265void RpcState::dump() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000266 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000267 dumpLocked();
268}
269
Steven Morelandc9d7b532021-06-04 20:57:41 +0000270void RpcState::clear() {
Steven Moreland67f85902023-03-15 01:13:49 +0000271 return clear(RpcMutexUniqueLock(mNodeMutex));
272}
Steven Morelandc9d7b532021-06-04 20:57:41 +0000273
Steven Moreland67f85902023-03-15 01:13:49 +0000274void RpcState::clear(RpcMutexUniqueLock nodeLock) {
Steven Morelandc9d7b532021-06-04 20:57:41 +0000275 if (mTerminated) {
276 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
277 "New state should be impossible after terminating!");
278 return;
279 }
Steven Moreland0092fe32022-07-15 00:15:34 +0000280 mTerminated = true;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000281
282 if (SHOULD_LOG_RPC_DETAIL) {
283 ALOGE("RpcState::clear()");
284 dumpLocked();
285 }
286
Steven Moreland0092fe32022-07-15 00:15:34 +0000287 // invariants
Steven Morelandc9d7b532021-06-04 20:57:41 +0000288 for (auto& [address, node] : mNodeForAddress) {
Steven Moreland0092fe32022-07-15 00:15:34 +0000289 bool guaranteedHaveBinder = node.timesSent > 0;
290 if (guaranteedHaveBinder) {
291 LOG_ALWAYS_FATAL_IF(node.sentRef == nullptr,
292 "Binder expected to be owned with address: %" PRIu64 " %s", address,
293 node.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000294 }
295 }
296
Steven Moreland0092fe32022-07-15 00:15:34 +0000297 // if the destructor of a binder object makes another RPC call, then calling
298 // decStrong could deadlock. So, we must hold onto these binders until
299 // mNodeMutex is no longer taken.
300 auto temp = std::move(mNodeForAddress);
301 mNodeForAddress.clear(); // RpcState isn't reusable, but for future/explicit
Steven Morelandc9d7b532021-06-04 20:57:41 +0000302
Steven Moreland67f85902023-03-15 01:13:49 +0000303 nodeLock.unlock();
Steven Moreland0092fe32022-07-15 00:15:34 +0000304 temp.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000305}
306
307void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000308 ALOGE("DUMP OF RpcState %p", this);
309 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
310 for (const auto& [address, node] : mNodeForAddress) {
Steven Moreland3fa32922022-07-14 18:45:51 +0000311 ALOGE("- address: %" PRIu64 " %s", address, node.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000312 }
313 ALOGE("END DUMP OF RpcState");
314}
315
Steven Moreland3fa32922022-07-14 18:45:51 +0000316std::string RpcState::BinderNode::toString() const {
317 sp<IBinder> strongBinder = this->binder.promote();
318
319 const char* desc;
320 if (strongBinder) {
321 if (strongBinder->remoteBinder()) {
322 if (strongBinder->remoteBinder()->isRpcBinder()) {
323 desc = "(rpc binder proxy)";
324 } else {
325 desc = "(binder proxy)";
326 }
327 } else {
328 desc = "(local binder)";
329 }
330 } else {
331 desc = "(not promotable)";
332 }
333
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +0000334 std::stringstream ss;
335 ss << "node{" << intptr_t(this->binder.unsafe_get()) << " times sent: " << this->timesSent
336 << " times recd: " << this->timesRecd << " type: " << desc << "}";
337 return ss.str();
Steven Moreland3fa32922022-07-14 18:45:51 +0000338}
Steven Moreland5553ac42020-11-11 02:14:45 +0000339
Steven Morelanddbe71832021-05-12 23:31:00 +0000340RpcState::CommandData::CommandData(size_t size) : mSize(size) {
Steven Moreland54fa6c72025-01-28 01:02:15 +0000341 if (size == 0) return;
342
Steven Morelanddbe71832021-05-12 23:31:00 +0000343 // The maximum size for regular binder is 1MB for all concurrent
344 // transactions. A very small proportion of transactions are even
345 // larger than a page, but we need to avoid allocating too much
346 // data on behalf of an arbitrary client, or we could risk being in
347 // a position where a single additional allocation could run out of
348 // memory.
349 //
350 // Note, this limit may not reflect the total amount of data allocated for a
351 // transaction (in some cases, additional fixed size amounts are added),
352 // though for rough consistency, we should avoid cases where this data type
353 // is used for multiple dynamic allocations for a single transaction.
Steven Moreland54fa6c72025-01-28 01:02:15 +0000354 if (size > binder::kRpcTransactionLimitBytes) {
355 ALOGE("Transaction requested too much data allocation: %zu bytes, failing.", size);
Steven Morelanddbe71832021-05-12 23:31:00 +0000356 return;
Steven Moreland54fa6c72025-01-28 01:02:15 +0000357 } else if (size > binder::kLogTransactionsOverBytes) {
358 ALOGW("Transaction too large: inefficient and in danger of breaking: %zu bytes.", size);
Steven Morelanddbe71832021-05-12 23:31:00 +0000359 }
360 mData.reset(new (std::nothrow) uint8_t[size]);
361}
362
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700363status_t RpcState::rpcSend(const sp<RpcSession::RpcConnection>& connection,
364 const sp<RpcSession>& session, const char* what, iovec* iovs, int niovs,
365 const std::optional<SmallFunction<status_t()>>& altPoll,
366 const std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800367 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000368 LOG_RPC_DETAIL("Sending %s (part %d of %d) on RpcTransport %p: %s",
369 what, i + 1, niovs, connection->rpcTransport.get(),
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000370 HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000371 }
372
Yifan Hong702115c2021-06-24 15:39:18 -0700373 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700374 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
Frederick Mayle69a0c992022-05-26 20:38:39 +0000375 iovs, niovs, altPoll,
376 ancillaryFds);
Steven Moreland798e0d12021-07-14 23:19:25 +0000377 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800378 LOG_RPC_DETAIL("Failed to write %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700379 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000380 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000381 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000382 }
383
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000384 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000385}
386
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700387status_t RpcState::rpcRec(const sp<RpcSession::RpcConnection>& connection,
388 const sp<RpcSession>& session, const char* what, iovec* iovs, int niovs,
389 std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) {
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000390 if (status_t status =
391 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
392 iovs, niovs, std::nullopt,
393 ancillaryFds);
Steven Morelandee3f4662021-05-22 01:07:33 +0000394 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800395 LOG_RPC_DETAIL("Failed to read %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700396 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandae58f432021-08-05 17:53:16 -0700397 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000398 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000399 }
400
Colin Cross9adfeaf2022-01-21 17:22:09 -0800401 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000402 LOG_RPC_DETAIL("Received %s (part %d of %d) on RpcTransport %p: %s",
403 what, i + 1, niovs, connection->rpcTransport.get(),
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000404 HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000405 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000406 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000407}
408
Steven Morelandca3f6382023-05-11 23:23:26 +0000409bool RpcState::validateProtocolVersion(uint32_t version) {
Steven Moreland09034a92023-05-31 20:49:11 +0000410 if (version == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
411#if defined(__ANDROID__)
412 char codename[PROPERTY_VALUE_MAX];
413 property_get("ro.build.version.codename", codename, "");
414 if (!strcmp(codename, "REL")) {
Steven Moreland0884c552023-10-17 18:23:31 +0000415 ALOGE("Cannot use experimental RPC binder protocol in a release configuration.");
Steven Moreland09034a92023-05-31 20:49:11 +0000416 return false;
417 }
418#else
Steven Moreland687728e2023-10-28 01:07:40 +0000419 ALOGE("Cannot use experimental RPC binder protocol outside of Android.");
420 return false;
Steven Moreland09034a92023-05-31 20:49:11 +0000421#endif
422 } else if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT) {
Steven Morelandca3f6382023-05-11 23:23:26 +0000423 ALOGE("Cannot use RPC binder protocol version %u which is unknown (current protocol "
424 "version "
425 "is %u).",
426 version, RPC_WIRE_PROTOCOL_VERSION);
427 return false;
428 }
Steven Moreland09034a92023-05-31 20:49:11 +0000429
Steven Morelandca3f6382023-05-11 23:23:26 +0000430 return true;
431}
432
Steven Morelandbf57bce2021-07-26 15:26:12 -0700433status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
434 const sp<RpcSession>& session, uint32_t* version) {
435 RpcNewSessionResponse response;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000436 iovec iov{&response, sizeof(response)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000437 if (status_t status = rpcRec(connection, session, "new session response", &iov, 1, nullptr);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700438 status != OK) {
439 return status;
440 }
441 *version = response.version;
442 return OK;
443}
444
Steven Moreland5ae62562021-06-10 03:21:42 +0000445status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
446 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000447 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000448 .msg = RPC_CONNECTION_INIT_OKAY,
449 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000450 iovec iov{&init, sizeof(init)};
Devin Moore695368f2022-06-03 22:29:14 +0000451 return rpcSend(connection, session, "connection init", &iov, 1, std::nullopt);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000452}
453
Steven Moreland5ae62562021-06-10 03:21:42 +0000454status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
455 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000456 RpcOutgoingConnectionInit init;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000457 iovec iov{&init, sizeof(init)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000458 if (status_t status = rpcRec(connection, session, "connection init", &iov, 1, nullptr);
459 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000460 return status;
461
462 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
463 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
464 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
465 init.msg);
466 return BAD_VALUE;
467 }
468 return OK;
469}
470
Steven Moreland5ae62562021-06-10 03:21:42 +0000471sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
472 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000473 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000474 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000475 Parcel reply;
476
Steven Moreland5623d1a2021-09-10 15:45:34 -0700477 status_t status =
478 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000479 if (status != OK) {
480 ALOGE("Error getting root object: %s", statusToString(status).c_str());
481 return nullptr;
482 }
483
484 return reply.readStrongBinder();
485}
486
Steven Moreland5ae62562021-06-10 03:21:42 +0000487status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
488 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000489 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000490 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000491 Parcel reply;
492
Steven Moreland5623d1a2021-09-10 15:45:34 -0700493 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
494 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000495 if (status != OK) {
496 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
497 return status;
498 }
499
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000500 int32_t maxThreads;
501 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000502 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000503 if (maxThreads <= 0) {
504 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000505 return BAD_VALUE;
506 }
507
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000508 *maxThreadsOut = maxThreads;
509 return OK;
510}
511
Steven Moreland5ae62562021-06-10 03:21:42 +0000512status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700513 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000514 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000515 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000516 Parcel reply;
517
Steven Moreland5623d1a2021-09-10 15:45:34 -0700518 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
519 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000520 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000521 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000522 return status;
523 }
524
Steven Moreland826367f2021-09-10 14:05:31 -0700525 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000526}
527
Steven Moreland5ae62562021-06-10 03:21:42 +0000528status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
529 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
530 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000531 std::string errorMsg;
532 if (status_t status = validateParcel(session, data, &errorMsg); status != OK) {
533 ALOGE("Refusing to send RPC on binder %p code %" PRIu32 ": Parcel %p failed validation: %s",
534 binder.get(), code, &data, errorMsg.c_str());
535 return status;
Steven Morelandf5174272021-05-25 00:39:28 +0000536 }
Steven Moreland5623d1a2021-09-10 15:45:34 -0700537 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000538 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
539
Steven Moreland5ae62562021-06-10 03:21:42 +0000540 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000541}
542
Steven Moreland5ae62562021-06-10 03:21:42 +0000543status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700544 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000545 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000546 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
547 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
548
Steven Moreland5553ac42020-11-11 02:14:45 +0000549 uint64_t asyncNumber = 0;
550
Steven Moreland5623d1a2021-09-10 15:45:34 -0700551 if (address != 0) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000552 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000553 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
554 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700555 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
556 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000557
558 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000559 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000560 if (!nodeProgressAsyncNumber(&it->second)) {
561 _l.unlock();
562 (void)session->shutdownAndWait(false);
563 return DEAD_OBJECT;
564 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000565 }
566 }
567
Frederick Mayle69a0c992022-05-26 20:38:39 +0000568 auto* rpcFields = data.maybeRpcFields();
569 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
570
571 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
572 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +0000573
Frederick Mayle778c0902022-05-27 01:14:57 +0000574 uint32_t bodySize;
575 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(sizeof(RpcWireTransaction), data.dataSize(),
Frederick Mayledc07cf82022-05-26 20:30:12 +0000576 &bodySize) ||
577 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
578 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +0000579 "Too much data %zu", data.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +0000580 RpcWireHeader command{
581 .command = RPC_COMMAND_TRANSACT,
Frederick Mayle778c0902022-05-27 01:14:57 +0000582 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +0000583 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700584
Steven Moreland5553ac42020-11-11 02:14:45 +0000585 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700586 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000587 .code = code,
588 .flags = flags,
589 .asyncNumber = asyncNumber,
Frederick Mayledc07cf82022-05-26 20:30:12 +0000590 // bodySize didn't overflow => this cast is safe
591 .parcelDataSize = static_cast<uint32_t>(data.dataSize()),
Steven Moreland5553ac42020-11-11 02:14:45 +0000592 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000593
Steven Moreland43921d52021-09-27 17:15:56 -0700594 // Oneway calls have no sync point, so if many are sent before, whether this
595 // is a twoway or oneway transaction, they may have filled up the socket.
Devin Moore695368f2022-06-03 22:29:14 +0000596 // So, make sure we drain them before polling
Steven Morelandda31af62023-02-25 01:55:58 +0000597 constexpr size_t kWaitMaxUs = 1000000;
598 constexpr size_t kWaitLogUs = 10000;
599 size_t waitUs = 0;
Steven Moreland43921d52021-09-27 17:15:56 -0700600
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000601 iovec iovs[]{
602 {&command, sizeof(RpcWireHeader)},
603 {&transaction, sizeof(RpcWireTransaction)},
604 {const_cast<uint8_t*>(data.data()), data.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +0000605 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000606 };
Tomasz Wasilczyk35804862023-10-30 14:19:19 +0000607 auto altPoll = [&] {
608 if (waitUs > kWaitLogUs) {
609 ALOGE("Cannot send command, trying to process pending refcounts. Waiting "
610 "%zuus. Too many oneway calls?",
611 waitUs);
612 }
Devin Moore695368f2022-06-03 22:29:14 +0000613
Tomasz Wasilczyk35804862023-10-30 14:19:19 +0000614 if (waitUs > 0) {
615 usleep(waitUs);
616 waitUs = std::min(kWaitMaxUs, waitUs * 2);
617 } else {
618 waitUs = 1;
619 }
Devin Moore695368f2022-06-03 22:29:14 +0000620
Tomasz Wasilczyk35804862023-10-30 14:19:19 +0000621 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
622 };
623 if (status_t status = rpcSend(connection, session, "transaction", iovs, countof(iovs),
624 std::ref(altPoll), rpcFields->mFds.get());
Steven Moreland43921d52021-09-27 17:15:56 -0700625 status != OK) {
Steven Morelandda31af62023-02-25 01:55:58 +0000626 // rpcSend calls shutdownAndWait, so all refcounts should be reset. If we ever tolerate
627 // errors here, then we may need to undo the binder-sent counts for the transaction as
628 // well as for the binder objects in the Parcel
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000629 return status;
Steven Moreland43921d52021-09-27 17:15:56 -0700630 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000631
632 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700633 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
634 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000635
636 // Do not wait on result.
Steven Moreland43921d52021-09-27 17:15:56 -0700637 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000638 }
639
640 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
641
Steven Moreland5ae62562021-06-10 03:21:42 +0000642 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000643}
644
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000645static void cleanup_reply_data(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
646 size_t objectsCount) {
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000647 delete[] const_cast<uint8_t*>(data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000648 (void)dataSize;
649 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000650 (void)objectsCount;
Steven Moreland5553ac42020-11-11 02:14:45 +0000651}
652
Steven Moreland5ae62562021-06-10 03:21:42 +0000653status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
654 const sp<RpcSession>& session, Parcel* reply) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700655 std::vector<std::variant<unique_fd, borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000656 RpcWireHeader command;
657 while (true) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000658 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000659 if (status_t status = rpcRec(connection, session, "command header (for reply)", &iov, 1,
660 enableAncillaryFds(session->getFileDescriptorTransportMode())
661 ? &ancillaryFds
662 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000663 status != OK)
664 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000665
666 if (command.command == RPC_COMMAND_REPLY) break;
667
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000668 if (status_t status = processCommand(connection, session, command, CommandType::ANY,
669 std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000670 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000671 return status;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000672
673 // Reset to avoid spurious use-after-move warning from clang-tidy.
674 ancillaryFds = decltype(ancillaryFds)();
Steven Moreland5553ac42020-11-11 02:14:45 +0000675 }
676
Frederick Mayledc07cf82022-05-26 20:30:12 +0000677 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
678
679 if (command.bodySize < rpcReplyWireSize) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000680 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
681 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000682 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000683 return BAD_VALUE;
684 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000685
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000686 RpcWireReply rpcReply;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000687 memset(&rpcReply, 0, sizeof(RpcWireReply)); // zero because of potential short read
688
689 CommandData data(command.bodySize - rpcReplyWireSize);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000690 if (!data.valid()) return NO_MEMORY;
691
692 iovec iovs[]{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000693 {&rpcReply, rpcReplyWireSize},
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000694 {data.data(), data.size()},
695 };
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -0700696 if (status_t status = rpcRec(connection, session, "reply body", iovs, countof(iovs), nullptr);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000697 status != OK)
698 return status;
Frederick Mayle69a0c992022-05-26 20:38:39 +0000699
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000700 if (rpcReply.status != OK) return rpcReply.status;
701
Frederick Mayledc07cf82022-05-26 20:30:12 +0000702 Span<const uint8_t> parcelSpan = {data.data(), data.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000703 Span<const uint32_t> objectTableSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000704 if (session->getProtocolVersion().value() >=
705 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000706 std::optional<Span<const uint8_t>> objectTableBytes =
707 parcelSpan.splitOff(rpcReply.parcelDataSize);
708 if (!objectTableBytes.has_value()) {
709 ALOGE("Parcel size larger than available bytes: %" PRId32 " vs %zu. Terminating!",
710 rpcReply.parcelDataSize, parcelSpan.byteSize());
711 (void)session->shutdownAndWait(false);
712 return BAD_VALUE;
713 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000714 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000715 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000716 if (!maybeSpan.has_value()) {
717 ALOGE("Bad object table size inferred from RpcWireReply. Saw bodySize=%" PRId32
718 " sizeofHeader=%zu parcelSize=%" PRId32 " objectTableBytesSize=%zu. Terminating!",
719 command.bodySize, rpcReplyWireSize, rpcReply.parcelDataSize,
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000720 objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000721 return BAD_VALUE;
722 }
723 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000724 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000725
Frederick Mayledc07cf82022-05-26 20:30:12 +0000726 data.release();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000727 return reply->rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
728 objectTableSpan.data, objectTableSpan.size,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000729 std::move(ancillaryFds), cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000730}
731
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000732status_t RpcState::sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection,
733 const sp<RpcSession>& session, uint64_t addr,
734 size_t target) {
735 RpcDecStrong body = {
736 .address = RpcWireAddress::fromRaw(addr),
737 };
738
Steven Moreland5553ac42020-11-11 02:14:45 +0000739 {
Steven Moreland67f85902023-03-15 01:13:49 +0000740 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000741 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
742 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700743 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
744 "Sending dec strong on unknown address %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000745
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000746 LOG_ALWAYS_FATAL_IF(it->second.timesRecd < target, "Can't dec count of %zu to %zu.",
747 it->second.timesRecd, target);
748
749 // typically this happens when multiple threads send dec refs at the
750 // same time - the transactions will get combined automatically
751 if (it->second.timesRecd == target) return OK;
752
753 body.amount = it->second.timesRecd - target;
754 it->second.timesRecd = target;
755
Steven Moreland67f85902023-03-15 01:13:49 +0000756 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(session, std::move(_l), it),
Steven Moreland31bde7a2021-06-04 00:57:36 +0000757 "Bad state. RpcState shouldn't own received binder");
Steven Moreland67f85902023-03-15 01:13:49 +0000758 // LOCK ALREADY RELEASED
Steven Moreland5553ac42020-11-11 02:14:45 +0000759 }
760
761 RpcWireHeader cmd = {
762 .command = RPC_COMMAND_DEC_STRONG,
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000763 .bodySize = sizeof(RpcDecStrong),
Steven Moreland5553ac42020-11-11 02:14:45 +0000764 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000765 iovec iovs[]{{&cmd, sizeof(cmd)}, {&body, sizeof(body)}};
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -0700766 return rpcSend(connection, session, "dec ref", iovs, countof(iovs), std::nullopt);
Steven Moreland5553ac42020-11-11 02:14:45 +0000767}
768
Steven Moreland5ae62562021-06-10 03:21:42 +0000769status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
770 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700771 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000772
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700773 std::vector<std::variant<unique_fd, borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000774 RpcWireHeader command;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000775 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000776 if (status_t status =
777 rpcRec(connection, session, "command header (for server)", &iov, 1,
778 enableAncillaryFds(session->getFileDescriptorTransportMode()) ? &ancillaryFds
779 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000780 status != OK)
781 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000782
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000783 return processCommand(connection, session, command, type, std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000784}
785
Steven Moreland5ae62562021-06-10 03:21:42 +0000786status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
787 const sp<RpcSession>& session, CommandType type) {
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000788 while (true) {
Andrei Homescu1975aaa2022-03-19 02:34:57 +0000789 status_t status = connection->rpcTransport->pollRead();
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000790 if (status == WOULD_BLOCK) break;
791 if (status != OK) return status;
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000792
793 status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000794 if (status != OK) return status;
795 }
796 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000797}
798
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000799status_t RpcState::processCommand(
800 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
801 const RpcWireHeader& command, CommandType type,
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700802 std::vector<std::variant<unique_fd, borrowed_fd>>&& ancillaryFds) {
Steven Moreland32150282021-11-12 22:54:53 +0000803#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000804 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
805 IPCThreadState::SpGuard spGuard{
806 .address = __builtin_frame_address(0),
Steven Morelande42ffd02022-07-06 21:46:23 +0000807 .context = "processing binder RPC command (where RpcServer::setPerSessionRootObject is "
808 "used to distinguish callers)",
Steven Morelandd7302072021-05-15 01:32:04 +0000809 };
810 const IPCThreadState::SpGuard* origGuard;
811 if (kernelBinderState != nullptr) {
812 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
813 }
Steven Moreland32150282021-11-12 22:54:53 +0000814
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +0000815 auto guardUnguard = make_scope_guard([&]() {
Steven Morelandd7302072021-05-15 01:32:04 +0000816 if (kernelBinderState != nullptr) {
817 kernelBinderState->restoreGetCallingSpGuard(origGuard);
818 }
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +0000819 });
Steven Moreland32150282021-11-12 22:54:53 +0000820#endif // BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000821
Steven Moreland5553ac42020-11-11 02:14:45 +0000822 switch (command.command) {
823 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000824 if (type != CommandType::ANY) return BAD_TYPE;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000825 return processTransact(connection, session, command, std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000826 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000827 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000828 }
829
830 // We should always know the version of the opposing side, and since the
831 // RPC-binder-level wire protocol is not self synchronizing, we have no way
832 // to understand where the current command ends and the next one begins. We
833 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000834 // to kill us, so ending the session for misbehaving client.
835 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000836 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000837 return DEAD_OBJECT;
838}
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000839status_t RpcState::processTransact(
840 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
841 const RpcWireHeader& command,
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700842 std::vector<std::variant<unique_fd, borrowed_fd>>&& ancillaryFds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000843 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
844
Steven Morelanddbe71832021-05-12 23:31:00 +0000845 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000846 if (!transactionData.valid()) {
847 return NO_MEMORY;
848 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000849 iovec iov{transactionData.data(), transactionData.size()};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000850 if (status_t status = rpcRec(connection, session, "transaction body", &iov, 1, nullptr);
851 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000852 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000853
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000854 return processTransactInternal(connection, session, std::move(transactionData),
855 std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000856}
857
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000858static void do_nothing_to_transact_data(const uint8_t* data, size_t dataSize,
Steven Moreland438cce82021-04-02 18:04:08 +0000859 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland438cce82021-04-02 18:04:08 +0000860 (void)data;
861 (void)dataSize;
862 (void)objects;
863 (void)objectsCount;
864}
865
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000866status_t RpcState::processTransactInternal(
867 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
868 CommandData transactionData,
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700869 std::vector<std::variant<unique_fd, borrowed_fd>>&& ancillaryFds) {
Steven Morelandada72bd2021-06-09 23:29:13 +0000870 // for 'recursive' calls to this, we have already read and processed the
871 // binder from the transaction data and taken reference counts into account,
872 // so it is cached here.
Steven Moreland3903bf02021-09-27 16:05:24 -0700873 sp<IBinder> target;
Steven Morelandada72bd2021-06-09 23:29:13 +0000874processTransactInternalTailCall:
875
Steven Moreland5553ac42020-11-11 02:14:45 +0000876 if (transactionData.size() < sizeof(RpcWireTransaction)) {
877 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
878 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000879 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000880 return BAD_VALUE;
881 }
882 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
883
Steven Moreland5623d1a2021-09-10 15:45:34 -0700884 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000885 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000886
887 status_t replyStatus = OK;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700888 if (addr != 0) {
Steven Moreland3903bf02021-09-27 16:05:24 -0700889 if (!target) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000890 replyStatus = onBinderEntering(session, addr, &target);
Steven Morelandf5174272021-05-25 00:39:28 +0000891 }
892
Steven Moreland7227c8a2021-06-02 00:24:32 +0000893 if (replyStatus != OK) {
894 // do nothing
895 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000896 // This can happen if the binder is remote in this process, and
897 // another thread has called the last decStrong on this binder.
898 // However, for local binders, it indicates a misbehaving client
899 // (any binder which is being transacted on should be holding a
900 // strong ref count), so in either case, terminating the
901 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700902 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
903 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000904 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000905 replyStatus = BAD_VALUE;
906 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700907 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
908 ". Terminating!",
909 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000910 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000911 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000912 } else if (oneway) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000913 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000914 auto it = mNodeForAddress.find(addr);
915 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700916 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000917 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000918 } else if (transaction->asyncNumber != it->second.asyncNumber) {
919 // we need to process some other asynchronous transaction
920 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000921 it->second.asyncTodo.push(BinderNode::AsyncTodo{
922 .ref = target,
923 .data = std::move(transactionData),
Frederick Mayleb0221d12022-10-03 23:10:53 +0000924 .ancillaryFds = std::move(ancillaryFds),
Steven Morelandf5174272021-05-25 00:39:28 +0000925 .asyncNumber = transaction->asyncNumber,
926 });
Steven Morelandd45be622021-06-04 02:19:37 +0000927
928 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700929 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
930 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000931
932 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
933 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
934 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
935
936 if (numPending >= kArbitraryOnewayCallWarnLevel) {
937 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
938 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
939 _l.unlock();
940 (void)session->shutdownAndWait(false);
941 return FAILED_TRANSACTION;
942 }
943
944 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
945 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
946 target.get(), numPending);
947 }
948 }
Steven Morelandf5174272021-05-25 00:39:28 +0000949 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000950 }
951 }
952 }
953
Steven Moreland5553ac42020-11-11 02:14:45 +0000954 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000955 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000956
957 if (replyStatus == OK) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000958 Span<const uint8_t> parcelSpan = {transaction->data,
959 transactionData.size() -
960 offsetof(RpcWireTransaction, data)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000961 Span<const uint32_t> objectTableSpan;
Steven Moreland28c87282023-04-14 21:03:01 +0000962 if (session->getProtocolVersion().value() >=
Frederick Mayledc07cf82022-05-26 20:30:12 +0000963 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000964 std::optional<Span<const uint8_t>> objectTableBytes =
965 parcelSpan.splitOff(transaction->parcelDataSize);
966 if (!objectTableBytes.has_value()) {
967 ALOGE("Parcel size (%" PRId32 ") greater than available bytes (%zu). Terminating!",
968 transaction->parcelDataSize, parcelSpan.byteSize());
969 (void)session->shutdownAndWait(false);
970 return BAD_VALUE;
971 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000972 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000973 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000974 if (!maybeSpan.has_value()) {
975 ALOGE("Bad object table size inferred from RpcWireTransaction. Saw bodySize=%zu "
976 "sizeofHeader=%zu parcelSize=%" PRId32
977 " objectTableBytesSize=%zu. Terminating!",
978 transactionData.size(), sizeof(RpcWireTransaction),
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000979 transaction->parcelDataSize, objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000980 return BAD_VALUE;
981 }
982 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000983 }
984
Steven Morelandeff77c12021-04-15 00:37:19 +0000985 Parcel data;
986 // transaction->data is owned by this function. Parcel borrows this data and
987 // only holds onto it for the duration of this function call. Parcel will be
988 // deleted before the 'transactionData' object.
Frederick Mayledc07cf82022-05-26 20:30:12 +0000989
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000990 replyStatus =
991 data.rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
992 objectTableSpan.data, objectTableSpan.size,
993 std::move(ancillaryFds), do_nothing_to_transact_data);
994 // Reset to avoid spurious use-after-move warning from clang-tidy.
995 ancillaryFds = std::remove_reference<decltype(ancillaryFds)>::type();
Steven Morelandeff77c12021-04-15 00:37:19 +0000996
Frederick Mayle69a0c992022-05-26 20:38:39 +0000997 if (replyStatus == OK) {
998 if (target) {
999 bool origAllowNested = connection->allowNested;
1000 connection->allowNested = !oneway;
Steven Morelandc7d40132021-06-10 03:42:11 +00001001
Frederick Mayle69a0c992022-05-26 20:38:39 +00001002 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +00001003
Frederick Mayle69a0c992022-05-26 20:38:39 +00001004 connection->allowNested = origAllowNested;
1005 } else {
1006 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +00001007
Frederick Mayle69a0c992022-05-26 20:38:39 +00001008 switch (transaction->code) {
1009 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
1010 replyStatus = reply.writeInt32(session->getMaxIncomingThreads());
1011 break;
1012 }
1013 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
1014 // for client connections, this should always report the value
1015 // originally returned from the server, so this is asserting
1016 // that it exists
1017 replyStatus = reply.writeByteVector(session->mId);
1018 break;
1019 }
1020 default: {
1021 sp<RpcServer> server = session->server();
1022 if (server) {
1023 switch (transaction->code) {
1024 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
1025 sp<IBinder> root = session->mSessionSpecificRootObject
1026 ?: server->getRootObject();
1027 replyStatus = reply.writeStrongBinder(root);
1028 break;
1029 }
1030 default: {
1031 replyStatus = UNKNOWN_TRANSACTION;
1032 }
Steven Moreland103424e2021-06-02 18:16:19 +00001033 }
Frederick Mayle69a0c992022-05-26 20:38:39 +00001034 } else {
1035 ALOGE("Special command sent, but no server object attached.");
Steven Moreland103424e2021-06-02 18:16:19 +00001036 }
Steven Morelandf137de92021-04-24 01:54:26 +00001037 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001038 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001039 }
1040 }
1041 }
1042
Steven Morelandc7d40132021-06-10 03:42:11 +00001043 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001044 if (replyStatus != OK) {
1045 ALOGW("Oneway call failed with error: %d", replyStatus);
1046 }
1047
Steven Moreland5623d1a2021-09-10 15:45:34 -07001048 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
1049 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001050
1051 // Check to see if there is another asynchronous transaction to process.
1052 // This behavior differs from binder behavior, since in the binder
1053 // driver, asynchronous transactions will be processed after existing
1054 // pending binder transactions on the queue. The downside of this is
1055 // that asynchronous transactions can be drowned out by synchronous
1056 // transactions. However, we have no easy way to queue these
1057 // transactions after the synchronous transactions we may want to read
1058 // from the wire. So, in socket binder here, we have the opposite
1059 // downside: asynchronous transactions may drown out synchronous
1060 // transactions.
1061 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001062 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001063 auto it = mNodeForAddress.find(addr);
1064 // last refcount dropped after this transaction happened
1065 if (it == mNodeForAddress.end()) return OK;
1066
Steven Morelandc9d7b532021-06-04 20:57:41 +00001067 if (!nodeProgressAsyncNumber(&it->second)) {
1068 _l.unlock();
1069 (void)session->shutdownAndWait(false);
1070 return DEAD_OBJECT;
1071 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001072
Andrei Homescuae5f0d12023-02-25 05:03:31 +00001073 if (it->second.asyncTodo.size() != 0 &&
1074 it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001075 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
1076 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001077
1078 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +00001079 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +00001080 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +00001081 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
1082
Steven Morelandada72bd2021-06-09 23:29:13 +00001083 // reset up arguments
1084 transactionData = std::move(todo.data);
Frederick Mayleb0221d12022-10-03 23:10:53 +00001085 ancillaryFds = std::move(todo.ancillaryFds);
Steven Moreland3903bf02021-09-27 16:05:24 -07001086 LOG_ALWAYS_FATAL_IF(target != todo.ref,
1087 "async list should be associated with a binder");
Steven Morelandf5174272021-05-25 00:39:28 +00001088
Steven Moreland5553ac42020-11-11 02:14:45 +00001089 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +00001090 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +00001091 }
1092 }
Steven Morelandd8083312021-09-22 13:37:10 -07001093
1094 // done processing all the async commands on this binder that we can, so
1095 // write decstrongs on the binder
1096 if (addr != 0 && replyStatus == OK) {
1097 return flushExcessBinderRefs(session, addr, target);
1098 }
1099
Steven Moreland5553ac42020-11-11 02:14:45 +00001100 return OK;
1101 }
1102
Steven Moreland6709cf42021-09-30 15:21:54 -07001103 // Binder refs are flushed for oneway calls only after all calls which are
1104 // built up are executed. Otherwise, they fill up the binder buffer.
1105 if (addr != 0 && replyStatus == OK) {
1106 replyStatus = flushExcessBinderRefs(session, addr, target);
1107 }
1108
Frederick Mayle69a0c992022-05-26 20:38:39 +00001109 std::string errorMsg;
1110 if (status_t status = validateParcel(session, reply, &errorMsg); status != OK) {
1111 ALOGE("Reply Parcel failed validation: %s", errorMsg.c_str());
1112 // Forward the error to the client of the transaction.
1113 reply.freeData();
1114 reply.markForRpc(session);
1115 replyStatus = status;
1116 }
1117
1118 auto* rpcFields = reply.maybeRpcFields();
1119 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
1120
Frederick Mayledc07cf82022-05-26 20:30:12 +00001121 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
1122
Frederick Mayle69a0c992022-05-26 20:38:39 +00001123 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
1124 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +00001125
Frederick Mayle778c0902022-05-27 01:14:57 +00001126 uint32_t bodySize;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001127 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(rpcReplyWireSize, reply.dataSize(), &bodySize) ||
1128 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
1129 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +00001130 "Too much data for reply %zu", reply.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +00001131 RpcWireHeader cmdReply{
1132 .command = RPC_COMMAND_REPLY,
Frederick Mayle778c0902022-05-27 01:14:57 +00001133 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +00001134 };
Steven Moreland5553ac42020-11-11 02:14:45 +00001135 RpcWireReply rpcReply{
1136 .status = replyStatus,
Frederick Mayledc07cf82022-05-26 20:30:12 +00001137 // NOTE: Not necessarily written to socket depending on session
1138 // version.
1139 // NOTE: bodySize didn't overflow => this cast is safe
1140 .parcelDataSize = static_cast<uint32_t>(reply.dataSize()),
1141 .reserved = {0, 0, 0},
Steven Moreland5553ac42020-11-11 02:14:45 +00001142 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001143 iovec iovs[]{
1144 {&cmdReply, sizeof(RpcWireHeader)},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001145 {&rpcReply, rpcReplyWireSize},
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001146 {const_cast<uint8_t*>(reply.data()), reply.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001147 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001148 };
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -07001149 return rpcSend(connection, session, "reply", iovs, countof(iovs), std::nullopt,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001150 rpcFields->mFds.get());
Steven Moreland5553ac42020-11-11 02:14:45 +00001151}
1152
Steven Moreland5ae62562021-06-10 03:21:42 +00001153status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
1154 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001155 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
1156
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001157 if (command.bodySize != sizeof(RpcDecStrong)) {
1158 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcDecStrong. Terminating!",
1159 sizeof(RpcDecStrong), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001160 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001161 return BAD_VALUE;
1162 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001163
Frederick Mayleb86cda42022-06-09 23:17:45 +00001164 RpcDecStrong body;
1165 iovec iov{&body, sizeof(RpcDecStrong)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001166 if (status_t status = rpcRec(connection, session, "dec ref body", &iov, 1, nullptr);
1167 status != OK)
Frederick Mayleb86cda42022-06-09 23:17:45 +00001168 return status;
1169
1170 uint64_t addr = RpcWireAddress::toRaw(body.address);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001171 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001172 auto it = mNodeForAddress.find(addr);
1173 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001174 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001175 return OK;
1176 }
1177
1178 sp<IBinder> target = it->second.binder.promote();
1179 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001180 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
1181 ". Terminating!",
1182 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001183 _l.unlock();
1184 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001185 return BAD_VALUE;
1186 }
1187
Frederick Mayleb86cda42022-06-09 23:17:45 +00001188 if (it->second.timesSent < body.amount) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001189 ALOGE("Record of sending binder %zu times, but requested decStrong for %" PRIu64 " of %u",
Frederick Mayleb86cda42022-06-09 23:17:45 +00001190 it->second.timesSent, addr, body.amount);
Steven Moreland5553ac42020-11-11 02:14:45 +00001191 return OK;
1192 }
1193
Steven Moreland5623d1a2021-09-10 15:45:34 -07001194 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
1195 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001196
Frederick Mayleb86cda42022-06-09 23:17:45 +00001197 LOG_RPC_DETAIL("Processing dec strong of %" PRIu64 " by %u from %zu", addr, body.amount,
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001198 it->second.timesSent);
1199
Frederick Mayleb86cda42022-06-09 23:17:45 +00001200 it->second.timesSent -= body.amount;
Steven Moreland67f85902023-03-15 01:13:49 +00001201 sp<IBinder> tempHold = tryEraseNode(session, std::move(_l), it);
1202 // LOCK ALREADY RELEASED
Steven Moreland31bde7a2021-06-04 00:57:36 +00001203 tempHold = nullptr; // destructor may make binder calls on this session
1204
1205 return OK;
1206}
1207
Frederick Mayle69a0c992022-05-26 20:38:39 +00001208status_t RpcState::validateParcel(const sp<RpcSession>& session, const Parcel& parcel,
1209 std::string* errorMsg) {
1210 auto* rpcFields = parcel.maybeRpcFields();
1211 if (rpcFields == nullptr) {
1212 *errorMsg = "Parcel not crafted for RPC call";
1213 return BAD_TYPE;
1214 }
1215
1216 if (rpcFields->mSession != session) {
1217 *errorMsg = "Parcel's session doesn't match";
1218 return BAD_TYPE;
1219 }
1220
1221 uint32_t protocolVersion = session->getProtocolVersion().value();
1222 if (protocolVersion < RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE &&
1223 !rpcFields->mObjectPositions.empty()) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +00001224 std::stringstream ss;
1225 ss << "Parcel has attached objects but the session's protocol version (" << protocolVersion
1226 << ") is too old, must be at least "
1227 << RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE;
1228 *errorMsg = ss.str();
Frederick Mayle69a0c992022-05-26 20:38:39 +00001229 return BAD_VALUE;
1230 }
1231
1232 if (rpcFields->mFds && !rpcFields->mFds->empty()) {
1233 switch (session->getFileDescriptorTransportMode()) {
1234 case RpcSession::FileDescriptorTransportMode::NONE:
1235 *errorMsg =
1236 "Parcel has file descriptors, but no file descriptor transport is enabled";
1237 return FDS_NOT_ALLOWED;
1238 case RpcSession::FileDescriptorTransportMode::UNIX: {
1239 constexpr size_t kMaxFdsPerMsg = 253;
1240 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +00001241 std::stringstream ss;
1242 ss << "Too many file descriptors in Parcel for unix domain socket: "
1243 << rpcFields->mFds->size() << " (max is " << kMaxFdsPerMsg << ")";
1244 *errorMsg = ss.str();
Frederick Mayle69a0c992022-05-26 20:38:39 +00001245 return BAD_VALUE;
1246 }
Andrei Homescu1c18a802022-08-17 04:59:01 +00001247 break;
1248 }
1249 case RpcSession::FileDescriptorTransportMode::TRUSTY: {
1250 // Keep this in sync with trusty_ipc.h!!!
1251 // We could import that file here on Trusty, but it's not
1252 // available on Android
1253 constexpr size_t kMaxFdsPerMsg = 8;
1254 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +00001255 std::stringstream ss;
1256 ss << "Too many file descriptors in Parcel for Trusty IPC connection: "
1257 << rpcFields->mFds->size() << " (max is " << kMaxFdsPerMsg << ")";
1258 *errorMsg = ss.str();
Andrei Homescu1c18a802022-08-17 04:59:01 +00001259 return BAD_VALUE;
1260 }
1261 break;
Frederick Mayle69a0c992022-05-26 20:38:39 +00001262 }
1263 }
1264 }
1265
1266 return OK;
1267}
1268
Steven Moreland67f85902023-03-15 01:13:49 +00001269sp<IBinder> RpcState::tryEraseNode(const sp<RpcSession>& session, RpcMutexUniqueLock nodeLock,
1270 std::map<uint64_t, BinderNode>::iterator& it) {
1271 bool shouldShutdown = false;
1272
Steven Moreland31bde7a2021-06-04 00:57:36 +00001273 sp<IBinder> ref;
1274
Steven Moreland5553ac42020-11-11 02:14:45 +00001275 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001276 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +00001277
1278 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +00001279 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
1280 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +00001281 mNodeForAddress.erase(it);
Steven Moreland67f85902023-03-15 01:13:49 +00001282
1283 if (mNodeForAddress.size() == 0) {
1284 shouldShutdown = true;
1285 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001286 }
1287 }
1288
Steven Moreland67f85902023-03-15 01:13:49 +00001289 // If we shutdown, prevent RpcState from being re-used. This prevents another
1290 // thread from getting the root object again.
1291 if (shouldShutdown) {
1292 clear(std::move(nodeLock));
1293 } else {
1294 nodeLock.unlock(); // explicit
1295 }
1296 // LOCK IS RELEASED
1297
1298 if (shouldShutdown) {
1299 ALOGI("RpcState has no binders left, so triggering shutdown...");
1300 (void)session->shutdownAndWait(false);
1301 }
1302
Steven Moreland31bde7a2021-06-04 00:57:36 +00001303 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +00001304}
1305
Steven Morelandc9d7b532021-06-04 20:57:41 +00001306bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +00001307 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
1308 // a single binder
1309 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
1310 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +00001311 return false;
1312 }
1313 node->asyncNumber++;
1314 return true;
1315}
1316
Steven Moreland5553ac42020-11-11 02:14:45 +00001317} // namespace android