blob: 964a5c4ff94aa26b0e93cc749d02759600ff5d15 [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "RpcState"
18
19#include "RpcState.h"
20
Steven Morelandd7302072021-05-15 01:32:04 +000021#include <android-base/scopeguard.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000022#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000023#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000024#include <binder/RpcServer.h>
25
26#include "Debug.h"
27#include "RpcWireFormat.h"
Frederick Mayledc07cf82022-05-26 20:30:12 +000028#include "Utils.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000029
Steven Morelandb8176792021-06-22 20:29:21 +000030#include <random>
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +000031#include <sstream>
Steven Morelandb8176792021-06-22 20:29:21 +000032
Steven Moreland5553ac42020-11-11 02:14:45 +000033#include <inttypes.h>
34
Steven Moreland09034a92023-05-31 20:49:11 +000035#ifdef __ANDROID__
36#include <cutils/properties.h>
37#endif
38
Steven Moreland5553ac42020-11-11 02:14:45 +000039namespace android {
40
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:
Andrei Homescu1c18a802022-08-17 04:59:01 +000059 case RpcSession::FileDescriptorTransportMode::TRUSTY:
Frederick Mayle69a0c992022-05-26 20:38:39 +000060 return true;
61 }
Tomasz Wasilczyk7b5430b2023-06-28 14:04:51 -070062 LOG_ALWAYS_FATAL("Invalid FileDescriptorTransportMode: %d", static_cast<int>(mode));
Frederick Mayle69a0c992022-05-26 20:38:39 +000063}
64
Steven Moreland5553ac42020-11-11 02:14:45 +000065RpcState::RpcState() {}
66RpcState::~RpcState() {}
67
Steven Morelandbdb53ab2021-05-05 17:57:41 +000068status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5623d1a2021-09-10 15:45:34 -070069 uint64_t* outAddress) {
Steven Moreland5553ac42020-11-11 02:14:45 +000070 bool isRemote = binder->remoteBinder();
71 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
72
Steven Moreland99157622021-09-13 16:27:34 -070073 if (isRpc && binder->remoteBinder()->getPrivateAccessor().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000074 // We need to be able to send instructions over the socket for how to
75 // connect to a different server, and we also need to let the host
76 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000077 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000078 return INVALID_OPERATION;
79 }
80
81 if (isRemote && !isRpc) {
82 // Without additional work, this would have the effect of using this
83 // process to proxy calls from the socket over to the other process, and
84 // it would make those calls look like they come from us (not over the
85 // sockets). In order to make this work transparently like binder, we
86 // would instead need to send instructions over the socket for how to
87 // connect to the host process, and we also need to let the host process
88 // know this was happening.
89 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
90 return INVALID_OPERATION;
91 }
92
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000093 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000094 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +000095
96 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
97 // in RpcState
98 for (auto& [addr, node] : mNodeForAddress) {
99 if (binder == node.binder) {
100 if (isRpc) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700101 // check integrity of data structure
Steven Moreland99157622021-09-13 16:27:34 -0700102 uint64_t actualAddr = binder->remoteBinder()->getPrivateAccessor().rpcAddress();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700103 LOG_ALWAYS_FATAL_IF(addr != actualAddr, "Address mismatch %" PRIu64 " vs %" PRIu64,
104 addr, actualAddr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000105 }
106 node.timesSent++;
107 node.sentRef = binder; // might already be set
108 *outAddress = addr;
109 return OK;
110 }
111 }
112 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
113
Steven Moreland91538242021-06-10 23:35:35 +0000114 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +0000115
Steven Moreland5623d1a2021-09-10 15:45:34 -0700116 // arbitrary limit for maximum number of nodes in a process (otherwise we
117 // might run out of addresses)
118 if (mNodeForAddress.size() > 100000) {
119 return NO_MEMORY;
120 }
121
122 while (true) {
123 RpcWireAddress address{
124 .options = RPC_WIRE_ADDRESS_OPTION_CREATED,
125 .address = mNextId,
126 };
127 if (forServer) {
128 address.options |= RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
129 }
130
131 // avoid ubsan abort
132 if (mNextId >= std::numeric_limits<uint32_t>::max()) {
133 mNextId = 0;
134 } else {
135 mNextId++;
136 }
137
138 auto&& [it, inserted] = mNodeForAddress.insert({RpcWireAddress::toRaw(address),
Steven Moreland91538242021-06-10 23:35:35 +0000139 BinderNode{
140 .binder = binder,
Steven Moreland91538242021-06-10 23:35:35 +0000141 .sentRef = binder,
Andrei Homescu5a036f32022-03-08 22:54:40 +0000142 .timesSent = 1,
Steven Moreland91538242021-06-10 23:35:35 +0000143 }});
144 if (inserted) {
145 *outAddress = it->first;
146 return OK;
147 }
Steven Moreland91538242021-06-10 23:35:35 +0000148 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000149}
150
Steven Moreland5623d1a2021-09-10 15:45:34 -0700151status_t RpcState::onBinderEntering(const sp<RpcSession>& session, uint64_t address,
Steven Moreland7227c8a2021-06-02 00:24:32 +0000152 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000153 // ensure that: if we want to use addresses for something else in the future (for
154 // instance, allowing transitive binder sends), that we don't accidentally
155 // send those addresses to old server. Accidentally ignoring this in that
156 // case and considering the binder to be recognized could cause this
157 // process to accidentally proxy transactions for that binder. Of course,
158 // if we communicate with a binder, it could always be proxying
159 // information. However, we want to make sure that isn't done on accident
160 // by a client.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700161 RpcWireAddress addr = RpcWireAddress::fromRaw(address);
162 constexpr uint32_t kKnownOptions =
163 RPC_WIRE_ADDRESS_OPTION_CREATED | RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
164 if (addr.options & ~kKnownOptions) {
165 ALOGE("Address is of an unknown type, rejecting: %" PRIu64, address);
Steven Moreland91538242021-06-10 23:35:35 +0000166 return BAD_VALUE;
167 }
168
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000169 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000170 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000171
172 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000173 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000174
175 // implicitly have strong RPC refcount, since we received this binder
176 it->second.timesRecd++;
Steven Morelandd8083312021-09-22 13:37:10 -0700177 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000178 }
179
Steven Moreland91538242021-06-10 23:35:35 +0000180 // we don't know about this binder, so the other side of the connection
181 // should have created it.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700182 if ((addr.options & RPC_WIRE_ADDRESS_OPTION_FOR_SERVER) == !!session->server()) {
183 ALOGE("Server received unrecognized address which we should own the creation of %" PRIu64,
184 address);
Steven Moreland91538242021-06-10 23:35:35 +0000185 return BAD_VALUE;
186 }
187
Steven Moreland5553ac42020-11-11 02:14:45 +0000188 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
189 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
190
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000191 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000192 // device global binders in the RPC world).
Steven Moreland99157622021-09-13 16:27:34 -0700193 it->second.binder = *out = BpBinder::PrivateAccessor::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000194 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000195 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000196}
197
Steven Morelandd8083312021-09-22 13:37:10 -0700198status_t RpcState::flushExcessBinderRefs(const sp<RpcSession>& session, uint64_t address,
199 const sp<IBinder>& binder) {
Steven Morelande96ed0e2021-09-27 17:43:53 -0700200 // We can flush all references when the binder is destroyed. No need to send
201 // extra reference counting packets now.
202 if (binder->remoteBinder()) return OK;
203
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000204 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandd8083312021-09-22 13:37:10 -0700205 if (mTerminated) return DEAD_OBJECT;
206
207 auto it = mNodeForAddress.find(address);
208
209 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Can't be deleted while we hold sp<>");
210 LOG_ALWAYS_FATAL_IF(it->second.binder != binder,
211 "Caller of flushExcessBinderRefs using inconsistent arguments");
212
Steven Morelande96ed0e2021-09-27 17:43:53 -0700213 LOG_ALWAYS_FATAL_IF(it->second.timesSent <= 0, "Local binder must have been sent %p",
214 binder.get());
Steven Morelandd8083312021-09-22 13:37:10 -0700215
Steven Morelande96ed0e2021-09-27 17:43:53 -0700216 // For a local binder, we only need to know that we sent it. Now that we
217 // have an sp<> for this call, we don't need anything more. If the other
218 // process is done with this binder, it needs to know we received the
219 // refcount associated with this call, so we can acknowledge that we
220 // received it. Once (or if) it has no other refcounts, it would reply with
221 // its own decStrong so that it could be removed from this session.
222 if (it->second.timesRecd != 0) {
Steven Morelandd8083312021-09-22 13:37:10 -0700223 _l.unlock();
224
Steven Morelande96ed0e2021-09-27 17:43:53 -0700225 return session->sendDecStrongToTarget(address, 0);
Steven Morelandd8083312021-09-22 13:37:10 -0700226 }
227
228 return OK;
229}
230
Devin Moore66d5b7a2022-07-07 21:42:10 +0000231status_t RpcState::sendObituaries(const sp<RpcSession>& session) {
232 RpcMutexUniqueLock _l(mNodeMutex);
233
234 // Gather strong pointers to all of the remote binders for this session so
235 // we hold the strong references. remoteBinder() returns a raw pointer.
236 // Send the obituaries and drop the strong pointers outside of the lock so
237 // the destructors and the onBinderDied calls are not done while locked.
238 std::vector<sp<IBinder>> remoteBinders;
239 for (const auto& [_, binderNode] : mNodeForAddress) {
240 if (auto binder = binderNode.binder.promote()) {
241 remoteBinders.push_back(std::move(binder));
242 }
243 }
244 _l.unlock();
245
246 for (const auto& binder : remoteBinders) {
247 if (binder->remoteBinder() &&
248 binder->remoteBinder()->getPrivateAccessor().rpcSession() == session) {
249 binder->remoteBinder()->sendObituary();
250 }
251 }
252 return OK;
253}
254
Steven Moreland5553ac42020-11-11 02:14:45 +0000255size_t RpcState::countBinders() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000256 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000257 return mNodeForAddress.size();
258}
259
260void RpcState::dump() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000261 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000262 dumpLocked();
263}
264
Steven Morelandc9d7b532021-06-04 20:57:41 +0000265void RpcState::clear() {
Steven Moreland67f85902023-03-15 01:13:49 +0000266 return clear(RpcMutexUniqueLock(mNodeMutex));
267}
Steven Morelandc9d7b532021-06-04 20:57:41 +0000268
Steven Moreland67f85902023-03-15 01:13:49 +0000269void RpcState::clear(RpcMutexUniqueLock nodeLock) {
Steven Morelandc9d7b532021-06-04 20:57:41 +0000270 if (mTerminated) {
271 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
272 "New state should be impossible after terminating!");
273 return;
274 }
Steven Moreland0092fe32022-07-15 00:15:34 +0000275 mTerminated = true;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000276
277 if (SHOULD_LOG_RPC_DETAIL) {
278 ALOGE("RpcState::clear()");
279 dumpLocked();
280 }
281
Steven Moreland0092fe32022-07-15 00:15:34 +0000282 // invariants
Steven Morelandc9d7b532021-06-04 20:57:41 +0000283 for (auto& [address, node] : mNodeForAddress) {
Steven Moreland0092fe32022-07-15 00:15:34 +0000284 bool guaranteedHaveBinder = node.timesSent > 0;
285 if (guaranteedHaveBinder) {
286 LOG_ALWAYS_FATAL_IF(node.sentRef == nullptr,
287 "Binder expected to be owned with address: %" PRIu64 " %s", address,
288 node.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000289 }
290 }
291
Steven Moreland0092fe32022-07-15 00:15:34 +0000292 // if the destructor of a binder object makes another RPC call, then calling
293 // decStrong could deadlock. So, we must hold onto these binders until
294 // mNodeMutex is no longer taken.
295 auto temp = std::move(mNodeForAddress);
296 mNodeForAddress.clear(); // RpcState isn't reusable, but for future/explicit
Steven Morelandc9d7b532021-06-04 20:57:41 +0000297
Steven Moreland67f85902023-03-15 01:13:49 +0000298 nodeLock.unlock();
Steven Moreland0092fe32022-07-15 00:15:34 +0000299 temp.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000300}
301
302void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000303 ALOGE("DUMP OF RpcState %p", this);
304 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
305 for (const auto& [address, node] : mNodeForAddress) {
Steven Moreland3fa32922022-07-14 18:45:51 +0000306 ALOGE("- address: %" PRIu64 " %s", address, node.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000307 }
308 ALOGE("END DUMP OF RpcState");
309}
310
Steven Moreland3fa32922022-07-14 18:45:51 +0000311std::string RpcState::BinderNode::toString() const {
312 sp<IBinder> strongBinder = this->binder.promote();
313
314 const char* desc;
315 if (strongBinder) {
316 if (strongBinder->remoteBinder()) {
317 if (strongBinder->remoteBinder()->isRpcBinder()) {
318 desc = "(rpc binder proxy)";
319 } else {
320 desc = "(binder proxy)";
321 }
322 } else {
323 desc = "(local binder)";
324 }
325 } else {
326 desc = "(not promotable)";
327 }
328
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +0000329 std::stringstream ss;
330 ss << "node{" << intptr_t(this->binder.unsafe_get()) << " times sent: " << this->timesSent
331 << " times recd: " << this->timesRecd << " type: " << desc << "}";
332 return ss.str();
Steven Moreland3fa32922022-07-14 18:45:51 +0000333}
Steven Moreland5553ac42020-11-11 02:14:45 +0000334
Steven Morelanddbe71832021-05-12 23:31:00 +0000335RpcState::CommandData::CommandData(size_t size) : mSize(size) {
336 // The maximum size for regular binder is 1MB for all concurrent
337 // transactions. A very small proportion of transactions are even
338 // larger than a page, but we need to avoid allocating too much
339 // data on behalf of an arbitrary client, or we could risk being in
340 // a position where a single additional allocation could run out of
341 // memory.
342 //
343 // Note, this limit may not reflect the total amount of data allocated for a
344 // transaction (in some cases, additional fixed size amounts are added),
345 // though for rough consistency, we should avoid cases where this data type
346 // is used for multiple dynamic allocations for a single transaction.
347 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
348 if (size == 0) return;
349 if (size > kMaxTransactionAllocation) {
350 ALOGW("Transaction requested too much data allocation %zu", size);
351 return;
352 }
353 mData.reset(new (std::nothrow) uint8_t[size]);
354}
355
Frederick Mayle69a0c992022-05-26 20:38:39 +0000356status_t RpcState::rpcSend(
357 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
358 const char* what, iovec* iovs, int niovs,
359 const std::optional<android::base::function_ref<status_t()>>& altPoll,
360 const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800361 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000362 LOG_RPC_DETAIL("Sending %s (part %d of %d) on RpcTransport %p: %s",
363 what, i + 1, niovs, connection->rpcTransport.get(),
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000364 HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000365 }
366
Yifan Hong702115c2021-06-24 15:39:18 -0700367 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700368 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
Frederick Mayle69a0c992022-05-26 20:38:39 +0000369 iovs, niovs, altPoll,
370 ancillaryFds);
Steven Moreland798e0d12021-07-14 23:19:25 +0000371 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800372 LOG_RPC_DETAIL("Failed to write %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700373 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000374 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000375 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000376 }
377
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000378 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000379}
380
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000381status_t RpcState::rpcRec(
382 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
383 const char* what, iovec* iovs, int niovs,
384 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
385 if (status_t status =
386 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
387 iovs, niovs, std::nullopt,
388 ancillaryFds);
Steven Morelandee3f4662021-05-22 01:07:33 +0000389 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800390 LOG_RPC_DETAIL("Failed to read %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700391 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandae58f432021-08-05 17:53:16 -0700392 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000393 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000394 }
395
Colin Cross9adfeaf2022-01-21 17:22:09 -0800396 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000397 LOG_RPC_DETAIL("Received %s (part %d of %d) on RpcTransport %p: %s",
398 what, i + 1, niovs, connection->rpcTransport.get(),
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000399 HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000400 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000401 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000402}
403
Steven Morelandca3f6382023-05-11 23:23:26 +0000404bool RpcState::validateProtocolVersion(uint32_t version) {
Steven Moreland09034a92023-05-31 20:49:11 +0000405 if (version == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
406#if defined(__ANDROID__)
407 char codename[PROPERTY_VALUE_MAX];
408 property_get("ro.build.version.codename", codename, "");
409 if (!strcmp(codename, "REL")) {
Steven Moreland0884c552023-10-17 18:23:31 +0000410 ALOGE("Cannot use experimental RPC binder protocol in a release configuration.");
Steven Moreland09034a92023-05-31 20:49:11 +0000411 return false;
412 }
413#else
Steven Moreland687728e2023-10-28 01:07:40 +0000414 ALOGE("Cannot use experimental RPC binder protocol outside of Android.");
415 return false;
Steven Moreland09034a92023-05-31 20:49:11 +0000416#endif
417 } else if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT) {
Steven Morelandca3f6382023-05-11 23:23:26 +0000418 ALOGE("Cannot use RPC binder protocol version %u which is unknown (current protocol "
419 "version "
420 "is %u).",
421 version, RPC_WIRE_PROTOCOL_VERSION);
422 return false;
423 }
Steven Moreland09034a92023-05-31 20:49:11 +0000424
Steven Morelandca3f6382023-05-11 23:23:26 +0000425 return true;
426}
427
Steven Morelandbf57bce2021-07-26 15:26:12 -0700428status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
429 const sp<RpcSession>& session, uint32_t* version) {
430 RpcNewSessionResponse response;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000431 iovec iov{&response, sizeof(response)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000432 if (status_t status = rpcRec(connection, session, "new session response", &iov, 1, nullptr);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700433 status != OK) {
434 return status;
435 }
436 *version = response.version;
437 return OK;
438}
439
Steven Moreland5ae62562021-06-10 03:21:42 +0000440status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
441 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000442 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000443 .msg = RPC_CONNECTION_INIT_OKAY,
444 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000445 iovec iov{&init, sizeof(init)};
Devin Moore695368f2022-06-03 22:29:14 +0000446 return rpcSend(connection, session, "connection init", &iov, 1, std::nullopt);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000447}
448
Steven Moreland5ae62562021-06-10 03:21:42 +0000449status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
450 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000451 RpcOutgoingConnectionInit init;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000452 iovec iov{&init, sizeof(init)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000453 if (status_t status = rpcRec(connection, session, "connection init", &iov, 1, nullptr);
454 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000455 return status;
456
457 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
458 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
459 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
460 init.msg);
461 return BAD_VALUE;
462 }
463 return OK;
464}
465
Steven Moreland5ae62562021-06-10 03:21:42 +0000466sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
467 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000468 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000469 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000470 Parcel reply;
471
Steven Moreland5623d1a2021-09-10 15:45:34 -0700472 status_t status =
473 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000474 if (status != OK) {
475 ALOGE("Error getting root object: %s", statusToString(status).c_str());
476 return nullptr;
477 }
478
479 return reply.readStrongBinder();
480}
481
Steven Moreland5ae62562021-06-10 03:21:42 +0000482status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
483 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000484 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000485 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000486 Parcel reply;
487
Steven Moreland5623d1a2021-09-10 15:45:34 -0700488 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
489 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000490 if (status != OK) {
491 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
492 return status;
493 }
494
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000495 int32_t maxThreads;
496 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000497 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000498 if (maxThreads <= 0) {
499 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000500 return BAD_VALUE;
501 }
502
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000503 *maxThreadsOut = maxThreads;
504 return OK;
505}
506
Steven Moreland5ae62562021-06-10 03:21:42 +0000507status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700508 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000509 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000510 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000511 Parcel reply;
512
Steven Moreland5623d1a2021-09-10 15:45:34 -0700513 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
514 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000515 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000516 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000517 return status;
518 }
519
Steven Moreland826367f2021-09-10 14:05:31 -0700520 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000521}
522
Steven Moreland5ae62562021-06-10 03:21:42 +0000523status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
524 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
525 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000526 std::string errorMsg;
527 if (status_t status = validateParcel(session, data, &errorMsg); status != OK) {
528 ALOGE("Refusing to send RPC on binder %p code %" PRIu32 ": Parcel %p failed validation: %s",
529 binder.get(), code, &data, errorMsg.c_str());
530 return status;
Steven Morelandf5174272021-05-25 00:39:28 +0000531 }
Steven Moreland5623d1a2021-09-10 15:45:34 -0700532 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000533 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
534
Steven Moreland5ae62562021-06-10 03:21:42 +0000535 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000536}
537
Steven Moreland5ae62562021-06-10 03:21:42 +0000538status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700539 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000540 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000541 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
542 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
543
Steven Moreland5553ac42020-11-11 02:14:45 +0000544 uint64_t asyncNumber = 0;
545
Steven Moreland5623d1a2021-09-10 15:45:34 -0700546 if (address != 0) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000547 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000548 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
549 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700550 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
551 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000552
553 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000554 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000555 if (!nodeProgressAsyncNumber(&it->second)) {
556 _l.unlock();
557 (void)session->shutdownAndWait(false);
558 return DEAD_OBJECT;
559 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000560 }
561 }
562
Frederick Mayle69a0c992022-05-26 20:38:39 +0000563 auto* rpcFields = data.maybeRpcFields();
564 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
565
566 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
567 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +0000568
Frederick Mayle778c0902022-05-27 01:14:57 +0000569 uint32_t bodySize;
570 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(sizeof(RpcWireTransaction), data.dataSize(),
Frederick Mayledc07cf82022-05-26 20:30:12 +0000571 &bodySize) ||
572 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
573 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +0000574 "Too much data %zu", data.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +0000575 RpcWireHeader command{
576 .command = RPC_COMMAND_TRANSACT,
Frederick Mayle778c0902022-05-27 01:14:57 +0000577 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +0000578 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700579
Steven Moreland5553ac42020-11-11 02:14:45 +0000580 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700581 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000582 .code = code,
583 .flags = flags,
584 .asyncNumber = asyncNumber,
Frederick Mayledc07cf82022-05-26 20:30:12 +0000585 // bodySize didn't overflow => this cast is safe
586 .parcelDataSize = static_cast<uint32_t>(data.dataSize()),
Steven Moreland5553ac42020-11-11 02:14:45 +0000587 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000588
Steven Moreland43921d52021-09-27 17:15:56 -0700589 // Oneway calls have no sync point, so if many are sent before, whether this
590 // is a twoway or oneway transaction, they may have filled up the socket.
Devin Moore695368f2022-06-03 22:29:14 +0000591 // So, make sure we drain them before polling
Steven Morelandda31af62023-02-25 01:55:58 +0000592 constexpr size_t kWaitMaxUs = 1000000;
593 constexpr size_t kWaitLogUs = 10000;
594 size_t waitUs = 0;
Steven Moreland43921d52021-09-27 17:15:56 -0700595
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000596 iovec iovs[]{
597 {&command, sizeof(RpcWireHeader)},
598 {&transaction, sizeof(RpcWireTransaction)},
599 {const_cast<uint8_t*>(data.data()), data.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +0000600 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000601 };
Frederick Mayle69a0c992022-05-26 20:38:39 +0000602 if (status_t status = rpcSend(
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -0700603 connection, session, "transaction", iovs, countof(iovs),
Frederick Mayle69a0c992022-05-26 20:38:39 +0000604 [&] {
605 if (waitUs > kWaitLogUs) {
606 ALOGE("Cannot send command, trying to process pending refcounts. Waiting "
607 "%zuus. Too many oneway calls?",
608 waitUs);
609 }
Devin Moore695368f2022-06-03 22:29:14 +0000610
Frederick Mayle69a0c992022-05-26 20:38:39 +0000611 if (waitUs > 0) {
612 usleep(waitUs);
613 waitUs = std::min(kWaitMaxUs, waitUs * 2);
614 } else {
615 waitUs = 1;
616 }
Devin Moore695368f2022-06-03 22:29:14 +0000617
Frederick Mayle69a0c992022-05-26 20:38:39 +0000618 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
619 },
620 rpcFields->mFds.get());
Steven Moreland43921d52021-09-27 17:15:56 -0700621 status != OK) {
Steven Morelandda31af62023-02-25 01:55:58 +0000622 // rpcSend calls shutdownAndWait, so all refcounts should be reset. If we ever tolerate
623 // errors here, then we may need to undo the binder-sent counts for the transaction as
624 // well as for the binder objects in the Parcel
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000625 return status;
Steven Moreland43921d52021-09-27 17:15:56 -0700626 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000627
628 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700629 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
630 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000631
632 // Do not wait on result.
Steven Moreland43921d52021-09-27 17:15:56 -0700633 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000634 }
635
636 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
637
Steven Moreland5ae62562021-06-10 03:21:42 +0000638 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000639}
640
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000641static void cleanup_reply_data(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
642 size_t objectsCount) {
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000643 delete[] const_cast<uint8_t*>(data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000644 (void)dataSize;
645 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000646 (void)objectsCount;
Steven Moreland5553ac42020-11-11 02:14:45 +0000647}
648
Steven Moreland5ae62562021-06-10 03:21:42 +0000649status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
650 const sp<RpcSession>& session, Parcel* reply) {
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000651 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000652 RpcWireHeader command;
653 while (true) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000654 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000655 if (status_t status = rpcRec(connection, session, "command header (for reply)", &iov, 1,
656 enableAncillaryFds(session->getFileDescriptorTransportMode())
657 ? &ancillaryFds
658 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000659 status != OK)
660 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000661
662 if (command.command == RPC_COMMAND_REPLY) break;
663
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000664 if (status_t status = processCommand(connection, session, command, CommandType::ANY,
665 std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000666 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000667 return status;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000668
669 // Reset to avoid spurious use-after-move warning from clang-tidy.
670 ancillaryFds = decltype(ancillaryFds)();
Steven Moreland5553ac42020-11-11 02:14:45 +0000671 }
672
Frederick Mayledc07cf82022-05-26 20:30:12 +0000673 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
674
675 if (command.bodySize < rpcReplyWireSize) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000676 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
677 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000678 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000679 return BAD_VALUE;
680 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000681
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000682 RpcWireReply rpcReply;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000683 memset(&rpcReply, 0, sizeof(RpcWireReply)); // zero because of potential short read
684
685 CommandData data(command.bodySize - rpcReplyWireSize);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000686 if (!data.valid()) return NO_MEMORY;
687
688 iovec iovs[]{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000689 {&rpcReply, rpcReplyWireSize},
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000690 {data.data(), data.size()},
691 };
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -0700692 if (status_t status = rpcRec(connection, session, "reply body", iovs, countof(iovs), nullptr);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000693 status != OK)
694 return status;
Frederick Mayle69a0c992022-05-26 20:38:39 +0000695
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000696 if (rpcReply.status != OK) return rpcReply.status;
697
Frederick Mayledc07cf82022-05-26 20:30:12 +0000698 Span<const uint8_t> parcelSpan = {data.data(), data.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000699 Span<const uint32_t> objectTableSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000700 if (session->getProtocolVersion().value() >=
701 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000702 std::optional<Span<const uint8_t>> objectTableBytes =
703 parcelSpan.splitOff(rpcReply.parcelDataSize);
704 if (!objectTableBytes.has_value()) {
705 ALOGE("Parcel size larger than available bytes: %" PRId32 " vs %zu. Terminating!",
706 rpcReply.parcelDataSize, parcelSpan.byteSize());
707 (void)session->shutdownAndWait(false);
708 return BAD_VALUE;
709 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000710 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000711 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000712 if (!maybeSpan.has_value()) {
713 ALOGE("Bad object table size inferred from RpcWireReply. Saw bodySize=%" PRId32
714 " sizeofHeader=%zu parcelSize=%" PRId32 " objectTableBytesSize=%zu. Terminating!",
715 command.bodySize, rpcReplyWireSize, rpcReply.parcelDataSize,
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000716 objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000717 return BAD_VALUE;
718 }
719 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000720 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000721
Frederick Mayledc07cf82022-05-26 20:30:12 +0000722 data.release();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000723 return reply->rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
724 objectTableSpan.data, objectTableSpan.size,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000725 std::move(ancillaryFds), cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000726}
727
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000728status_t RpcState::sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection,
729 const sp<RpcSession>& session, uint64_t addr,
730 size_t target) {
731 RpcDecStrong body = {
732 .address = RpcWireAddress::fromRaw(addr),
733 };
734
Steven Moreland5553ac42020-11-11 02:14:45 +0000735 {
Steven Moreland67f85902023-03-15 01:13:49 +0000736 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000737 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
738 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700739 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
740 "Sending dec strong on unknown address %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000741
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000742 LOG_ALWAYS_FATAL_IF(it->second.timesRecd < target, "Can't dec count of %zu to %zu.",
743 it->second.timesRecd, target);
744
745 // typically this happens when multiple threads send dec refs at the
746 // same time - the transactions will get combined automatically
747 if (it->second.timesRecd == target) return OK;
748
749 body.amount = it->second.timesRecd - target;
750 it->second.timesRecd = target;
751
Steven Moreland67f85902023-03-15 01:13:49 +0000752 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(session, std::move(_l), it),
Steven Moreland31bde7a2021-06-04 00:57:36 +0000753 "Bad state. RpcState shouldn't own received binder");
Steven Moreland67f85902023-03-15 01:13:49 +0000754 // LOCK ALREADY RELEASED
Steven Moreland5553ac42020-11-11 02:14:45 +0000755 }
756
757 RpcWireHeader cmd = {
758 .command = RPC_COMMAND_DEC_STRONG,
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000759 .bodySize = sizeof(RpcDecStrong),
Steven Moreland5553ac42020-11-11 02:14:45 +0000760 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000761 iovec iovs[]{{&cmd, sizeof(cmd)}, {&body, sizeof(body)}};
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -0700762 return rpcSend(connection, session, "dec ref", iovs, countof(iovs), std::nullopt);
Steven Moreland5553ac42020-11-11 02:14:45 +0000763}
764
Steven Moreland5ae62562021-06-10 03:21:42 +0000765status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
766 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700767 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000768
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000769 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000770 RpcWireHeader command;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000771 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000772 if (status_t status =
773 rpcRec(connection, session, "command header (for server)", &iov, 1,
774 enableAncillaryFds(session->getFileDescriptorTransportMode()) ? &ancillaryFds
775 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000776 status != OK)
777 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000778
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000779 return processCommand(connection, session, command, type, std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000780}
781
Steven Moreland5ae62562021-06-10 03:21:42 +0000782status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
783 const sp<RpcSession>& session, CommandType type) {
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000784 while (true) {
Andrei Homescu1975aaa2022-03-19 02:34:57 +0000785 status_t status = connection->rpcTransport->pollRead();
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000786 if (status == WOULD_BLOCK) break;
787 if (status != OK) return status;
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000788
789 status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000790 if (status != OK) return status;
791 }
792 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000793}
794
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000795status_t RpcState::processCommand(
796 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
797 const RpcWireHeader& command, CommandType type,
798 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland32150282021-11-12 22:54:53 +0000799#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000800 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
801 IPCThreadState::SpGuard spGuard{
802 .address = __builtin_frame_address(0),
Steven Morelande42ffd02022-07-06 21:46:23 +0000803 .context = "processing binder RPC command (where RpcServer::setPerSessionRootObject is "
804 "used to distinguish callers)",
Steven Morelandd7302072021-05-15 01:32:04 +0000805 };
806 const IPCThreadState::SpGuard* origGuard;
807 if (kernelBinderState != nullptr) {
808 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
809 }
Steven Moreland32150282021-11-12 22:54:53 +0000810
811 base::ScopeGuard guardUnguard = [&]() {
Steven Morelandd7302072021-05-15 01:32:04 +0000812 if (kernelBinderState != nullptr) {
813 kernelBinderState->restoreGetCallingSpGuard(origGuard);
814 }
815 };
Steven Moreland32150282021-11-12 22:54:53 +0000816#endif // BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000817
Steven Moreland5553ac42020-11-11 02:14:45 +0000818 switch (command.command) {
819 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000820 if (type != CommandType::ANY) return BAD_TYPE;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000821 return processTransact(connection, session, command, std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000822 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000823 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000824 }
825
826 // We should always know the version of the opposing side, and since the
827 // RPC-binder-level wire protocol is not self synchronizing, we have no way
828 // to understand where the current command ends and the next one begins. We
829 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000830 // to kill us, so ending the session for misbehaving client.
831 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000832 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000833 return DEAD_OBJECT;
834}
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000835status_t RpcState::processTransact(
836 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
837 const RpcWireHeader& command,
838 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000839 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
840
Steven Morelanddbe71832021-05-12 23:31:00 +0000841 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000842 if (!transactionData.valid()) {
843 return NO_MEMORY;
844 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000845 iovec iov{transactionData.data(), transactionData.size()};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000846 if (status_t status = rpcRec(connection, session, "transaction body", &iov, 1, nullptr);
847 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000848 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000849
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000850 return processTransactInternal(connection, session, std::move(transactionData),
851 std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000852}
853
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000854static void do_nothing_to_transact_data(const uint8_t* data, size_t dataSize,
Steven Moreland438cce82021-04-02 18:04:08 +0000855 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland438cce82021-04-02 18:04:08 +0000856 (void)data;
857 (void)dataSize;
858 (void)objects;
859 (void)objectsCount;
860}
861
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000862status_t RpcState::processTransactInternal(
863 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
864 CommandData transactionData,
865 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Morelandada72bd2021-06-09 23:29:13 +0000866 // for 'recursive' calls to this, we have already read and processed the
867 // binder from the transaction data and taken reference counts into account,
868 // so it is cached here.
Steven Moreland3903bf02021-09-27 16:05:24 -0700869 sp<IBinder> target;
Steven Morelandada72bd2021-06-09 23:29:13 +0000870processTransactInternalTailCall:
871
Steven Moreland5553ac42020-11-11 02:14:45 +0000872 if (transactionData.size() < sizeof(RpcWireTransaction)) {
873 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
874 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000875 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000876 return BAD_VALUE;
877 }
878 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
879
Steven Moreland5623d1a2021-09-10 15:45:34 -0700880 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000881 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000882
883 status_t replyStatus = OK;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700884 if (addr != 0) {
Steven Moreland3903bf02021-09-27 16:05:24 -0700885 if (!target) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000886 replyStatus = onBinderEntering(session, addr, &target);
Steven Morelandf5174272021-05-25 00:39:28 +0000887 }
888
Steven Moreland7227c8a2021-06-02 00:24:32 +0000889 if (replyStatus != OK) {
890 // do nothing
891 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000892 // This can happen if the binder is remote in this process, and
893 // another thread has called the last decStrong on this binder.
894 // However, for local binders, it indicates a misbehaving client
895 // (any binder which is being transacted on should be holding a
896 // strong ref count), so in either case, terminating the
897 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700898 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
899 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000900 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000901 replyStatus = BAD_VALUE;
902 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700903 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
904 ". Terminating!",
905 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000906 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000907 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000908 } else if (oneway) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000909 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000910 auto it = mNodeForAddress.find(addr);
911 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700912 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000913 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000914 } else if (transaction->asyncNumber != it->second.asyncNumber) {
915 // we need to process some other asynchronous transaction
916 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000917 it->second.asyncTodo.push(BinderNode::AsyncTodo{
918 .ref = target,
919 .data = std::move(transactionData),
Frederick Mayleb0221d12022-10-03 23:10:53 +0000920 .ancillaryFds = std::move(ancillaryFds),
Steven Morelandf5174272021-05-25 00:39:28 +0000921 .asyncNumber = transaction->asyncNumber,
922 });
Steven Morelandd45be622021-06-04 02:19:37 +0000923
924 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700925 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
926 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000927
928 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
929 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
930 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
931
932 if (numPending >= kArbitraryOnewayCallWarnLevel) {
933 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
934 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
935 _l.unlock();
936 (void)session->shutdownAndWait(false);
937 return FAILED_TRANSACTION;
938 }
939
940 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
941 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
942 target.get(), numPending);
943 }
944 }
Steven Morelandf5174272021-05-25 00:39:28 +0000945 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000946 }
947 }
948 }
949
Steven Moreland5553ac42020-11-11 02:14:45 +0000950 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000951 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000952
953 if (replyStatus == OK) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000954 Span<const uint8_t> parcelSpan = {transaction->data,
955 transactionData.size() -
956 offsetof(RpcWireTransaction, data)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000957 Span<const uint32_t> objectTableSpan;
Steven Moreland28c87282023-04-14 21:03:01 +0000958 if (session->getProtocolVersion().value() >=
Frederick Mayledc07cf82022-05-26 20:30:12 +0000959 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000960 std::optional<Span<const uint8_t>> objectTableBytes =
961 parcelSpan.splitOff(transaction->parcelDataSize);
962 if (!objectTableBytes.has_value()) {
963 ALOGE("Parcel size (%" PRId32 ") greater than available bytes (%zu). Terminating!",
964 transaction->parcelDataSize, parcelSpan.byteSize());
965 (void)session->shutdownAndWait(false);
966 return BAD_VALUE;
967 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000968 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000969 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000970 if (!maybeSpan.has_value()) {
971 ALOGE("Bad object table size inferred from RpcWireTransaction. Saw bodySize=%zu "
972 "sizeofHeader=%zu parcelSize=%" PRId32
973 " objectTableBytesSize=%zu. Terminating!",
974 transactionData.size(), sizeof(RpcWireTransaction),
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000975 transaction->parcelDataSize, objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000976 return BAD_VALUE;
977 }
978 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000979 }
980
Steven Morelandeff77c12021-04-15 00:37:19 +0000981 Parcel data;
982 // transaction->data is owned by this function. Parcel borrows this data and
983 // only holds onto it for the duration of this function call. Parcel will be
984 // deleted before the 'transactionData' object.
Frederick Mayledc07cf82022-05-26 20:30:12 +0000985
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000986 replyStatus =
987 data.rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
988 objectTableSpan.data, objectTableSpan.size,
989 std::move(ancillaryFds), do_nothing_to_transact_data);
990 // Reset to avoid spurious use-after-move warning from clang-tidy.
991 ancillaryFds = std::remove_reference<decltype(ancillaryFds)>::type();
Steven Morelandeff77c12021-04-15 00:37:19 +0000992
Frederick Mayle69a0c992022-05-26 20:38:39 +0000993 if (replyStatus == OK) {
994 if (target) {
995 bool origAllowNested = connection->allowNested;
996 connection->allowNested = !oneway;
Steven Morelandc7d40132021-06-10 03:42:11 +0000997
Frederick Mayle69a0c992022-05-26 20:38:39 +0000998 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000999
Frederick Mayle69a0c992022-05-26 20:38:39 +00001000 connection->allowNested = origAllowNested;
1001 } else {
1002 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +00001003
Frederick Mayle69a0c992022-05-26 20:38:39 +00001004 switch (transaction->code) {
1005 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
1006 replyStatus = reply.writeInt32(session->getMaxIncomingThreads());
1007 break;
1008 }
1009 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
1010 // for client connections, this should always report the value
1011 // originally returned from the server, so this is asserting
1012 // that it exists
1013 replyStatus = reply.writeByteVector(session->mId);
1014 break;
1015 }
1016 default: {
1017 sp<RpcServer> server = session->server();
1018 if (server) {
1019 switch (transaction->code) {
1020 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
1021 sp<IBinder> root = session->mSessionSpecificRootObject
1022 ?: server->getRootObject();
1023 replyStatus = reply.writeStrongBinder(root);
1024 break;
1025 }
1026 default: {
1027 replyStatus = UNKNOWN_TRANSACTION;
1028 }
Steven Moreland103424e2021-06-02 18:16:19 +00001029 }
Frederick Mayle69a0c992022-05-26 20:38:39 +00001030 } else {
1031 ALOGE("Special command sent, but no server object attached.");
Steven Moreland103424e2021-06-02 18:16:19 +00001032 }
Steven Morelandf137de92021-04-24 01:54:26 +00001033 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001034 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001035 }
1036 }
1037 }
1038
Steven Morelandc7d40132021-06-10 03:42:11 +00001039 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001040 if (replyStatus != OK) {
1041 ALOGW("Oneway call failed with error: %d", replyStatus);
1042 }
1043
Steven Moreland5623d1a2021-09-10 15:45:34 -07001044 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
1045 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001046
1047 // Check to see if there is another asynchronous transaction to process.
1048 // This behavior differs from binder behavior, since in the binder
1049 // driver, asynchronous transactions will be processed after existing
1050 // pending binder transactions on the queue. The downside of this is
1051 // that asynchronous transactions can be drowned out by synchronous
1052 // transactions. However, we have no easy way to queue these
1053 // transactions after the synchronous transactions we may want to read
1054 // from the wire. So, in socket binder here, we have the opposite
1055 // downside: asynchronous transactions may drown out synchronous
1056 // transactions.
1057 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001058 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001059 auto it = mNodeForAddress.find(addr);
1060 // last refcount dropped after this transaction happened
1061 if (it == mNodeForAddress.end()) return OK;
1062
Steven Morelandc9d7b532021-06-04 20:57:41 +00001063 if (!nodeProgressAsyncNumber(&it->second)) {
1064 _l.unlock();
1065 (void)session->shutdownAndWait(false);
1066 return DEAD_OBJECT;
1067 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001068
Andrei Homescuae5f0d12023-02-25 05:03:31 +00001069 if (it->second.asyncTodo.size() != 0 &&
1070 it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001071 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
1072 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001073
1074 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +00001075 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +00001076 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +00001077 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
1078
Steven Morelandada72bd2021-06-09 23:29:13 +00001079 // reset up arguments
1080 transactionData = std::move(todo.data);
Frederick Mayleb0221d12022-10-03 23:10:53 +00001081 ancillaryFds = std::move(todo.ancillaryFds);
Steven Moreland3903bf02021-09-27 16:05:24 -07001082 LOG_ALWAYS_FATAL_IF(target != todo.ref,
1083 "async list should be associated with a binder");
Steven Morelandf5174272021-05-25 00:39:28 +00001084
Steven Moreland5553ac42020-11-11 02:14:45 +00001085 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +00001086 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +00001087 }
1088 }
Steven Morelandd8083312021-09-22 13:37:10 -07001089
1090 // done processing all the async commands on this binder that we can, so
1091 // write decstrongs on the binder
1092 if (addr != 0 && replyStatus == OK) {
1093 return flushExcessBinderRefs(session, addr, target);
1094 }
1095
Steven Moreland5553ac42020-11-11 02:14:45 +00001096 return OK;
1097 }
1098
Steven Moreland6709cf42021-09-30 15:21:54 -07001099 // Binder refs are flushed for oneway calls only after all calls which are
1100 // built up are executed. Otherwise, they fill up the binder buffer.
1101 if (addr != 0 && replyStatus == OK) {
1102 replyStatus = flushExcessBinderRefs(session, addr, target);
1103 }
1104
Frederick Mayle69a0c992022-05-26 20:38:39 +00001105 std::string errorMsg;
1106 if (status_t status = validateParcel(session, reply, &errorMsg); status != OK) {
1107 ALOGE("Reply Parcel failed validation: %s", errorMsg.c_str());
1108 // Forward the error to the client of the transaction.
1109 reply.freeData();
1110 reply.markForRpc(session);
1111 replyStatus = status;
1112 }
1113
1114 auto* rpcFields = reply.maybeRpcFields();
1115 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
1116
Frederick Mayledc07cf82022-05-26 20:30:12 +00001117 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
1118
Frederick Mayle69a0c992022-05-26 20:38:39 +00001119 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
1120 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +00001121
Frederick Mayle778c0902022-05-27 01:14:57 +00001122 uint32_t bodySize;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001123 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(rpcReplyWireSize, reply.dataSize(), &bodySize) ||
1124 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
1125 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +00001126 "Too much data for reply %zu", reply.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +00001127 RpcWireHeader cmdReply{
1128 .command = RPC_COMMAND_REPLY,
Frederick Mayle778c0902022-05-27 01:14:57 +00001129 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +00001130 };
Steven Moreland5553ac42020-11-11 02:14:45 +00001131 RpcWireReply rpcReply{
1132 .status = replyStatus,
Frederick Mayledc07cf82022-05-26 20:30:12 +00001133 // NOTE: Not necessarily written to socket depending on session
1134 // version.
1135 // NOTE: bodySize didn't overflow => this cast is safe
1136 .parcelDataSize = static_cast<uint32_t>(reply.dataSize()),
1137 .reserved = {0, 0, 0},
Steven Moreland5553ac42020-11-11 02:14:45 +00001138 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001139 iovec iovs[]{
1140 {&cmdReply, sizeof(RpcWireHeader)},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001141 {&rpcReply, rpcReplyWireSize},
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001142 {const_cast<uint8_t*>(reply.data()), reply.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001143 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001144 };
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -07001145 return rpcSend(connection, session, "reply", iovs, countof(iovs), std::nullopt,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001146 rpcFields->mFds.get());
Steven Moreland5553ac42020-11-11 02:14:45 +00001147}
1148
Steven Moreland5ae62562021-06-10 03:21:42 +00001149status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
1150 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001151 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
1152
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001153 if (command.bodySize != sizeof(RpcDecStrong)) {
1154 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcDecStrong. Terminating!",
1155 sizeof(RpcDecStrong), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001156 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001157 return BAD_VALUE;
1158 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001159
Frederick Mayleb86cda42022-06-09 23:17:45 +00001160 RpcDecStrong body;
1161 iovec iov{&body, sizeof(RpcDecStrong)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001162 if (status_t status = rpcRec(connection, session, "dec ref body", &iov, 1, nullptr);
1163 status != OK)
Frederick Mayleb86cda42022-06-09 23:17:45 +00001164 return status;
1165
1166 uint64_t addr = RpcWireAddress::toRaw(body.address);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001167 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001168 auto it = mNodeForAddress.find(addr);
1169 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001170 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001171 return OK;
1172 }
1173
1174 sp<IBinder> target = it->second.binder.promote();
1175 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001176 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
1177 ". Terminating!",
1178 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001179 _l.unlock();
1180 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001181 return BAD_VALUE;
1182 }
1183
Frederick Mayleb86cda42022-06-09 23:17:45 +00001184 if (it->second.timesSent < body.amount) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001185 ALOGE("Record of sending binder %zu times, but requested decStrong for %" PRIu64 " of %u",
Frederick Mayleb86cda42022-06-09 23:17:45 +00001186 it->second.timesSent, addr, body.amount);
Steven Moreland5553ac42020-11-11 02:14:45 +00001187 return OK;
1188 }
1189
Steven Moreland5623d1a2021-09-10 15:45:34 -07001190 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
1191 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001192
Frederick Mayleb86cda42022-06-09 23:17:45 +00001193 LOG_RPC_DETAIL("Processing dec strong of %" PRIu64 " by %u from %zu", addr, body.amount,
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001194 it->second.timesSent);
1195
Frederick Mayleb86cda42022-06-09 23:17:45 +00001196 it->second.timesSent -= body.amount;
Steven Moreland67f85902023-03-15 01:13:49 +00001197 sp<IBinder> tempHold = tryEraseNode(session, std::move(_l), it);
1198 // LOCK ALREADY RELEASED
Steven Moreland31bde7a2021-06-04 00:57:36 +00001199 tempHold = nullptr; // destructor may make binder calls on this session
1200
1201 return OK;
1202}
1203
Frederick Mayle69a0c992022-05-26 20:38:39 +00001204status_t RpcState::validateParcel(const sp<RpcSession>& session, const Parcel& parcel,
1205 std::string* errorMsg) {
1206 auto* rpcFields = parcel.maybeRpcFields();
1207 if (rpcFields == nullptr) {
1208 *errorMsg = "Parcel not crafted for RPC call";
1209 return BAD_TYPE;
1210 }
1211
1212 if (rpcFields->mSession != session) {
1213 *errorMsg = "Parcel's session doesn't match";
1214 return BAD_TYPE;
1215 }
1216
1217 uint32_t protocolVersion = session->getProtocolVersion().value();
1218 if (protocolVersion < RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE &&
1219 !rpcFields->mObjectPositions.empty()) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +00001220 std::stringstream ss;
1221 ss << "Parcel has attached objects but the session's protocol version (" << protocolVersion
1222 << ") is too old, must be at least "
1223 << RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE;
1224 *errorMsg = ss.str();
Frederick Mayle69a0c992022-05-26 20:38:39 +00001225 return BAD_VALUE;
1226 }
1227
1228 if (rpcFields->mFds && !rpcFields->mFds->empty()) {
1229 switch (session->getFileDescriptorTransportMode()) {
1230 case RpcSession::FileDescriptorTransportMode::NONE:
1231 *errorMsg =
1232 "Parcel has file descriptors, but no file descriptor transport is enabled";
1233 return FDS_NOT_ALLOWED;
1234 case RpcSession::FileDescriptorTransportMode::UNIX: {
1235 constexpr size_t kMaxFdsPerMsg = 253;
1236 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +00001237 std::stringstream ss;
1238 ss << "Too many file descriptors in Parcel for unix domain socket: "
1239 << rpcFields->mFds->size() << " (max is " << kMaxFdsPerMsg << ")";
1240 *errorMsg = ss.str();
Frederick Mayle69a0c992022-05-26 20:38:39 +00001241 return BAD_VALUE;
1242 }
Andrei Homescu1c18a802022-08-17 04:59:01 +00001243 break;
1244 }
1245 case RpcSession::FileDescriptorTransportMode::TRUSTY: {
1246 // Keep this in sync with trusty_ipc.h!!!
1247 // We could import that file here on Trusty, but it's not
1248 // available on Android
1249 constexpr size_t kMaxFdsPerMsg = 8;
1250 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +00001251 std::stringstream ss;
1252 ss << "Too many file descriptors in Parcel for Trusty IPC connection: "
1253 << rpcFields->mFds->size() << " (max is " << kMaxFdsPerMsg << ")";
1254 *errorMsg = ss.str();
Andrei Homescu1c18a802022-08-17 04:59:01 +00001255 return BAD_VALUE;
1256 }
1257 break;
Frederick Mayle69a0c992022-05-26 20:38:39 +00001258 }
1259 }
1260 }
1261
1262 return OK;
1263}
1264
Steven Moreland67f85902023-03-15 01:13:49 +00001265sp<IBinder> RpcState::tryEraseNode(const sp<RpcSession>& session, RpcMutexUniqueLock nodeLock,
1266 std::map<uint64_t, BinderNode>::iterator& it) {
1267 bool shouldShutdown = false;
1268
Steven Moreland31bde7a2021-06-04 00:57:36 +00001269 sp<IBinder> ref;
1270
Steven Moreland5553ac42020-11-11 02:14:45 +00001271 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001272 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +00001273
1274 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +00001275 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
1276 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +00001277 mNodeForAddress.erase(it);
Steven Moreland67f85902023-03-15 01:13:49 +00001278
1279 if (mNodeForAddress.size() == 0) {
1280 shouldShutdown = true;
1281 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001282 }
1283 }
1284
Steven Moreland67f85902023-03-15 01:13:49 +00001285 // If we shutdown, prevent RpcState from being re-used. This prevents another
1286 // thread from getting the root object again.
1287 if (shouldShutdown) {
1288 clear(std::move(nodeLock));
1289 } else {
1290 nodeLock.unlock(); // explicit
1291 }
1292 // LOCK IS RELEASED
1293
1294 if (shouldShutdown) {
1295 ALOGI("RpcState has no binders left, so triggering shutdown...");
1296 (void)session->shutdownAndWait(false);
1297 }
1298
Steven Moreland31bde7a2021-06-04 00:57:36 +00001299 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +00001300}
1301
Steven Morelandc9d7b532021-06-04 20:57:41 +00001302bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +00001303 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
1304 // a single binder
1305 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
1306 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +00001307 return false;
1308 }
1309 node->asyncNumber++;
1310 return true;
1311}
1312
Steven Moreland5553ac42020-11-11 02:14:45 +00001313} // namespace android