blob: aa26b91274a6bb08ed80dd6d31dce41aa0d4c2f1 [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
Andrei Homescua39e4ed2021-12-10 08:41:54 +000021#include <android-base/macros.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000022#include <binder/BpBinder.h>
Tomasz Wasilczykd6c8a4c2023-10-11 20:41:51 +000023#include <binder/Functional.h>
Steven Morelandd7302072021-05-15 01:32:04 +000024#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000025#include <binder/RpcServer.h>
26
27#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 Wasilczykd6c8a4c2023-10-11 20:41:51 +000042using namespace android::binder::impl;
43
Devin Moore08256432021-07-02 13:03:49 -070044#if RPC_FLAKE_PRONE
Steven Morelandb8176792021-06-22 20:29:21 +000045void rpcMaybeWaitToFlake() {
Devin Moore08256432021-07-02 13:03:49 -070046 [[clang::no_destroy]] static std::random_device r;
Steven Moreland7e2675c2022-09-28 23:34:52 +000047 [[clang::no_destroy]] static RpcMutex m;
Steven Morelandb8176792021-06-22 20:29:21 +000048 unsigned num;
49 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000050 RpcMutexLockGuard lock(m);
Steven Morelandb8176792021-06-22 20:29:21 +000051 num = r();
52 }
53 if (num % 10 == 0) usleep(num % 1000);
54}
55#endif
56
Frederick Mayle69a0c992022-05-26 20:38:39 +000057static bool enableAncillaryFds(RpcSession::FileDescriptorTransportMode mode) {
58 switch (mode) {
59 case RpcSession::FileDescriptorTransportMode::NONE:
60 return false;
61 case RpcSession::FileDescriptorTransportMode::UNIX:
Andrei Homescu1c18a802022-08-17 04:59:01 +000062 case RpcSession::FileDescriptorTransportMode::TRUSTY:
Frederick Mayle69a0c992022-05-26 20:38:39 +000063 return true;
64 }
Tomasz Wasilczyk7b5430b2023-06-28 14:04:51 -070065 LOG_ALWAYS_FATAL("Invalid FileDescriptorTransportMode: %d", static_cast<int>(mode));
Frederick Mayle69a0c992022-05-26 20:38:39 +000066}
67
Steven Moreland5553ac42020-11-11 02:14:45 +000068RpcState::RpcState() {}
69RpcState::~RpcState() {}
70
Steven Morelandbdb53ab2021-05-05 17:57:41 +000071status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5623d1a2021-09-10 15:45:34 -070072 uint64_t* outAddress) {
Steven Moreland5553ac42020-11-11 02:14:45 +000073 bool isRemote = binder->remoteBinder();
74 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
75
Steven Moreland99157622021-09-13 16:27:34 -070076 if (isRpc && binder->remoteBinder()->getPrivateAccessor().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000077 // We need to be able to send instructions over the socket for how to
78 // connect to a different server, and we also need to let the host
79 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000080 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000081 return INVALID_OPERATION;
82 }
83
84 if (isRemote && !isRpc) {
85 // Without additional work, this would have the effect of using this
86 // process to proxy calls from the socket over to the other process, and
87 // it would make those calls look like they come from us (not over the
88 // sockets). In order to make this work transparently like binder, we
89 // would instead need to send instructions over the socket for how to
90 // connect to the host process, and we also need to let the host process
91 // know this was happening.
92 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
93 return INVALID_OPERATION;
94 }
95
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000096 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000097 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +000098
99 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
100 // in RpcState
101 for (auto& [addr, node] : mNodeForAddress) {
102 if (binder == node.binder) {
103 if (isRpc) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700104 // check integrity of data structure
Steven Moreland99157622021-09-13 16:27:34 -0700105 uint64_t actualAddr = binder->remoteBinder()->getPrivateAccessor().rpcAddress();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700106 LOG_ALWAYS_FATAL_IF(addr != actualAddr, "Address mismatch %" PRIu64 " vs %" PRIu64,
107 addr, actualAddr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000108 }
109 node.timesSent++;
110 node.sentRef = binder; // might already be set
111 *outAddress = addr;
112 return OK;
113 }
114 }
115 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
116
Steven Moreland91538242021-06-10 23:35:35 +0000117 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +0000118
Steven Moreland5623d1a2021-09-10 15:45:34 -0700119 // arbitrary limit for maximum number of nodes in a process (otherwise we
120 // might run out of addresses)
121 if (mNodeForAddress.size() > 100000) {
122 return NO_MEMORY;
123 }
124
125 while (true) {
126 RpcWireAddress address{
127 .options = RPC_WIRE_ADDRESS_OPTION_CREATED,
128 .address = mNextId,
129 };
130 if (forServer) {
131 address.options |= RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
132 }
133
134 // avoid ubsan abort
135 if (mNextId >= std::numeric_limits<uint32_t>::max()) {
136 mNextId = 0;
137 } else {
138 mNextId++;
139 }
140
141 auto&& [it, inserted] = mNodeForAddress.insert({RpcWireAddress::toRaw(address),
Steven Moreland91538242021-06-10 23:35:35 +0000142 BinderNode{
143 .binder = binder,
Steven Moreland91538242021-06-10 23:35:35 +0000144 .sentRef = binder,
Andrei Homescu5a036f32022-03-08 22:54:40 +0000145 .timesSent = 1,
Steven Moreland91538242021-06-10 23:35:35 +0000146 }});
147 if (inserted) {
148 *outAddress = it->first;
149 return OK;
150 }
Steven Moreland91538242021-06-10 23:35:35 +0000151 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000152}
153
Steven Moreland5623d1a2021-09-10 15:45:34 -0700154status_t RpcState::onBinderEntering(const sp<RpcSession>& session, uint64_t address,
Steven Moreland7227c8a2021-06-02 00:24:32 +0000155 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000156 // ensure that: if we want to use addresses for something else in the future (for
157 // instance, allowing transitive binder sends), that we don't accidentally
158 // send those addresses to old server. Accidentally ignoring this in that
159 // case and considering the binder to be recognized could cause this
160 // process to accidentally proxy transactions for that binder. Of course,
161 // if we communicate with a binder, it could always be proxying
162 // information. However, we want to make sure that isn't done on accident
163 // by a client.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700164 RpcWireAddress addr = RpcWireAddress::fromRaw(address);
165 constexpr uint32_t kKnownOptions =
166 RPC_WIRE_ADDRESS_OPTION_CREATED | RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
167 if (addr.options & ~kKnownOptions) {
168 ALOGE("Address is of an unknown type, rejecting: %" PRIu64, address);
Steven Moreland91538242021-06-10 23:35:35 +0000169 return BAD_VALUE;
170 }
171
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000172 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000173 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000174
175 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000176 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000177
178 // implicitly have strong RPC refcount, since we received this binder
179 it->second.timesRecd++;
Steven Morelandd8083312021-09-22 13:37:10 -0700180 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000181 }
182
Steven Moreland91538242021-06-10 23:35:35 +0000183 // we don't know about this binder, so the other side of the connection
184 // should have created it.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700185 if ((addr.options & RPC_WIRE_ADDRESS_OPTION_FOR_SERVER) == !!session->server()) {
186 ALOGE("Server received unrecognized address which we should own the creation of %" PRIu64,
187 address);
Steven Moreland91538242021-06-10 23:35:35 +0000188 return BAD_VALUE;
189 }
190
Steven Moreland5553ac42020-11-11 02:14:45 +0000191 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
192 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
193
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000194 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000195 // device global binders in the RPC world).
Steven Moreland99157622021-09-13 16:27:34 -0700196 it->second.binder = *out = BpBinder::PrivateAccessor::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000197 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000198 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000199}
200
Steven Morelandd8083312021-09-22 13:37:10 -0700201status_t RpcState::flushExcessBinderRefs(const sp<RpcSession>& session, uint64_t address,
202 const sp<IBinder>& binder) {
Steven Morelande96ed0e2021-09-27 17:43:53 -0700203 // We can flush all references when the binder is destroyed. No need to send
204 // extra reference counting packets now.
205 if (binder->remoteBinder()) return OK;
206
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000207 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandd8083312021-09-22 13:37:10 -0700208 if (mTerminated) return DEAD_OBJECT;
209
210 auto it = mNodeForAddress.find(address);
211
212 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Can't be deleted while we hold sp<>");
213 LOG_ALWAYS_FATAL_IF(it->second.binder != binder,
214 "Caller of flushExcessBinderRefs using inconsistent arguments");
215
Steven Morelande96ed0e2021-09-27 17:43:53 -0700216 LOG_ALWAYS_FATAL_IF(it->second.timesSent <= 0, "Local binder must have been sent %p",
217 binder.get());
Steven Morelandd8083312021-09-22 13:37:10 -0700218
Steven Morelande96ed0e2021-09-27 17:43:53 -0700219 // For a local binder, we only need to know that we sent it. Now that we
220 // have an sp<> for this call, we don't need anything more. If the other
221 // process is done with this binder, it needs to know we received the
222 // refcount associated with this call, so we can acknowledge that we
223 // received it. Once (or if) it has no other refcounts, it would reply with
224 // its own decStrong so that it could be removed from this session.
225 if (it->second.timesRecd != 0) {
Steven Morelandd8083312021-09-22 13:37:10 -0700226 _l.unlock();
227
Steven Morelande96ed0e2021-09-27 17:43:53 -0700228 return session->sendDecStrongToTarget(address, 0);
Steven Morelandd8083312021-09-22 13:37:10 -0700229 }
230
231 return OK;
232}
233
Devin Moore66d5b7a2022-07-07 21:42:10 +0000234status_t RpcState::sendObituaries(const sp<RpcSession>& session) {
235 RpcMutexUniqueLock _l(mNodeMutex);
236
237 // Gather strong pointers to all of the remote binders for this session so
238 // we hold the strong references. remoteBinder() returns a raw pointer.
239 // Send the obituaries and drop the strong pointers outside of the lock so
240 // the destructors and the onBinderDied calls are not done while locked.
241 std::vector<sp<IBinder>> remoteBinders;
242 for (const auto& [_, binderNode] : mNodeForAddress) {
243 if (auto binder = binderNode.binder.promote()) {
244 remoteBinders.push_back(std::move(binder));
245 }
246 }
247 _l.unlock();
248
249 for (const auto& binder : remoteBinders) {
250 if (binder->remoteBinder() &&
251 binder->remoteBinder()->getPrivateAccessor().rpcSession() == session) {
252 binder->remoteBinder()->sendObituary();
253 }
254 }
255 return OK;
256}
257
Steven Moreland5553ac42020-11-11 02:14:45 +0000258size_t RpcState::countBinders() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000259 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000260 return mNodeForAddress.size();
261}
262
263void RpcState::dump() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000264 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000265 dumpLocked();
266}
267
Steven Morelandc9d7b532021-06-04 20:57:41 +0000268void RpcState::clear() {
Steven Moreland67f85902023-03-15 01:13:49 +0000269 return clear(RpcMutexUniqueLock(mNodeMutex));
270}
Steven Morelandc9d7b532021-06-04 20:57:41 +0000271
Steven Moreland67f85902023-03-15 01:13:49 +0000272void RpcState::clear(RpcMutexUniqueLock nodeLock) {
Steven Morelandc9d7b532021-06-04 20:57:41 +0000273 if (mTerminated) {
274 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
275 "New state should be impossible after terminating!");
276 return;
277 }
Steven Moreland0092fe32022-07-15 00:15:34 +0000278 mTerminated = true;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000279
280 if (SHOULD_LOG_RPC_DETAIL) {
281 ALOGE("RpcState::clear()");
282 dumpLocked();
283 }
284
Steven Moreland0092fe32022-07-15 00:15:34 +0000285 // invariants
Steven Morelandc9d7b532021-06-04 20:57:41 +0000286 for (auto& [address, node] : mNodeForAddress) {
Steven Moreland0092fe32022-07-15 00:15:34 +0000287 bool guaranteedHaveBinder = node.timesSent > 0;
288 if (guaranteedHaveBinder) {
289 LOG_ALWAYS_FATAL_IF(node.sentRef == nullptr,
290 "Binder expected to be owned with address: %" PRIu64 " %s", address,
291 node.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000292 }
293 }
294
Steven Moreland0092fe32022-07-15 00:15:34 +0000295 // if the destructor of a binder object makes another RPC call, then calling
296 // decStrong could deadlock. So, we must hold onto these binders until
297 // mNodeMutex is no longer taken.
298 auto temp = std::move(mNodeForAddress);
299 mNodeForAddress.clear(); // RpcState isn't reusable, but for future/explicit
Steven Morelandc9d7b532021-06-04 20:57:41 +0000300
Steven Moreland67f85902023-03-15 01:13:49 +0000301 nodeLock.unlock();
Steven Moreland0092fe32022-07-15 00:15:34 +0000302 temp.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000303}
304
305void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000306 ALOGE("DUMP OF RpcState %p", this);
307 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
308 for (const auto& [address, node] : mNodeForAddress) {
Steven Moreland3fa32922022-07-14 18:45:51 +0000309 ALOGE("- address: %" PRIu64 " %s", address, node.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000310 }
311 ALOGE("END DUMP OF RpcState");
312}
313
Steven Moreland3fa32922022-07-14 18:45:51 +0000314std::string RpcState::BinderNode::toString() const {
315 sp<IBinder> strongBinder = this->binder.promote();
316
317 const char* desc;
318 if (strongBinder) {
319 if (strongBinder->remoteBinder()) {
320 if (strongBinder->remoteBinder()->isRpcBinder()) {
321 desc = "(rpc binder proxy)";
322 } else {
323 desc = "(binder proxy)";
324 }
325 } else {
326 desc = "(local binder)";
327 }
328 } else {
329 desc = "(not promotable)";
330 }
331
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +0000332 std::stringstream ss;
333 ss << "node{" << intptr_t(this->binder.unsafe_get()) << " times sent: " << this->timesSent
334 << " times recd: " << this->timesRecd << " type: " << desc << "}";
335 return ss.str();
Steven Moreland3fa32922022-07-14 18:45:51 +0000336}
Steven Moreland5553ac42020-11-11 02:14:45 +0000337
Steven Morelanddbe71832021-05-12 23:31:00 +0000338RpcState::CommandData::CommandData(size_t size) : mSize(size) {
339 // The maximum size for regular binder is 1MB for all concurrent
340 // transactions. A very small proportion of transactions are even
341 // larger than a page, but we need to avoid allocating too much
342 // data on behalf of an arbitrary client, or we could risk being in
343 // a position where a single additional allocation could run out of
344 // memory.
345 //
346 // Note, this limit may not reflect the total amount of data allocated for a
347 // transaction (in some cases, additional fixed size amounts are added),
348 // though for rough consistency, we should avoid cases where this data type
349 // is used for multiple dynamic allocations for a single transaction.
350 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
351 if (size == 0) return;
352 if (size > kMaxTransactionAllocation) {
353 ALOGW("Transaction requested too much data allocation %zu", size);
354 return;
355 }
356 mData.reset(new (std::nothrow) uint8_t[size]);
357}
358
Frederick Mayle69a0c992022-05-26 20:38:39 +0000359status_t RpcState::rpcSend(
360 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
361 const char* what, iovec* iovs, int niovs,
Sebastian Pickl84b7cff2023-10-30 08:02:24 +0000362 const std::optional<android::base::function_ref<status_t()>>& altPoll,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000363 const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800364 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000365 LOG_RPC_DETAIL("Sending %s (part %d of %d) on RpcTransport %p: %s",
366 what, i + 1, niovs, connection->rpcTransport.get(),
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000367 HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000368 }
369
Yifan Hong702115c2021-06-24 15:39:18 -0700370 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700371 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
Frederick Mayle69a0c992022-05-26 20:38:39 +0000372 iovs, niovs, altPoll,
373 ancillaryFds);
Steven Moreland798e0d12021-07-14 23:19:25 +0000374 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800375 LOG_RPC_DETAIL("Failed to write %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700376 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000377 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000378 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000379 }
380
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000381 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000382}
383
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000384status_t RpcState::rpcRec(
385 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
386 const char* what, iovec* iovs, int niovs,
387 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
388 if (status_t status =
389 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
390 iovs, niovs, std::nullopt,
391 ancillaryFds);
Steven Morelandee3f4662021-05-22 01:07:33 +0000392 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800393 LOG_RPC_DETAIL("Failed to read %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700394 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandae58f432021-08-05 17:53:16 -0700395 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000396 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000397 }
398
Colin Cross9adfeaf2022-01-21 17:22:09 -0800399 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000400 LOG_RPC_DETAIL("Received %s (part %d of %d) on RpcTransport %p: %s",
401 what, i + 1, niovs, connection->rpcTransport.get(),
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000402 HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000403 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000404 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000405}
406
Steven Morelandca3f6382023-05-11 23:23:26 +0000407bool RpcState::validateProtocolVersion(uint32_t version) {
Steven Moreland09034a92023-05-31 20:49:11 +0000408 if (version == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
409#if defined(__ANDROID__)
410 char codename[PROPERTY_VALUE_MAX];
411 property_get("ro.build.version.codename", codename, "");
412 if (!strcmp(codename, "REL")) {
Steven Moreland0884c552023-10-17 18:23:31 +0000413 ALOGE("Cannot use experimental RPC binder protocol in a release configuration.");
Steven Moreland09034a92023-05-31 20:49:11 +0000414 return false;
415 }
416#else
Steven Moreland0884c552023-10-17 18:23:31 +0000417 // TODO(b/305983144)
Steven Moreland09034a92023-05-31 20:49:11 +0000418 // don't restrict on other platforms, though experimental should
419 // only really be used for testing, we don't have a good way to see
420 // what is shipping outside of Android
421#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 };
Sebastian Pickl84b7cff2023-10-30 08:02:24 +0000607 if (status_t status = rpcSend(
608 connection, session, "transaction", iovs, arraysize(iovs),
609 [&] {
610 if (waitUs > kWaitLogUs) {
611 ALOGE("Cannot send command, trying to process pending refcounts. Waiting "
612 "%zuus. Too many oneway calls?",
613 waitUs);
614 }
Devin Moore695368f2022-06-03 22:29:14 +0000615
Sebastian Pickl84b7cff2023-10-30 08:02:24 +0000616 if (waitUs > 0) {
617 usleep(waitUs);
618 waitUs = std::min(kWaitMaxUs, waitUs * 2);
619 } else {
620 waitUs = 1;
621 }
Devin Moore695368f2022-06-03 22:29:14 +0000622
Sebastian Pickl84b7cff2023-10-30 08:02:24 +0000623 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
624 },
625 rpcFields->mFds.get());
Steven Moreland43921d52021-09-27 17:15:56 -0700626 status != OK) {
Steven Morelandda31af62023-02-25 01:55:58 +0000627 // rpcSend calls shutdownAndWait, so all refcounts should be reset. If we ever tolerate
628 // errors here, then we may need to undo the binder-sent counts for the transaction as
629 // well as for the binder objects in the Parcel
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000630 return status;
Steven Moreland43921d52021-09-27 17:15:56 -0700631 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000632
633 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700634 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
635 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000636
637 // Do not wait on result.
Steven Moreland43921d52021-09-27 17:15:56 -0700638 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000639 }
640
641 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
642
Steven Moreland5ae62562021-06-10 03:21:42 +0000643 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000644}
645
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000646static void cleanup_reply_data(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
647 size_t objectsCount) {
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000648 delete[] const_cast<uint8_t*>(data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000649 (void)dataSize;
650 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000651 (void)objectsCount;
Steven Moreland5553ac42020-11-11 02:14:45 +0000652}
653
Steven Moreland5ae62562021-06-10 03:21:42 +0000654status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
655 const sp<RpcSession>& session, Parcel* reply) {
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000656 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000657 RpcWireHeader command;
658 while (true) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000659 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000660 if (status_t status = rpcRec(connection, session, "command header (for reply)", &iov, 1,
661 enableAncillaryFds(session->getFileDescriptorTransportMode())
662 ? &ancillaryFds
663 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000664 status != OK)
665 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000666
667 if (command.command == RPC_COMMAND_REPLY) break;
668
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000669 if (status_t status = processCommand(connection, session, command, CommandType::ANY,
670 std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000671 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000672 return status;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000673
674 // Reset to avoid spurious use-after-move warning from clang-tidy.
675 ancillaryFds = decltype(ancillaryFds)();
Steven Moreland5553ac42020-11-11 02:14:45 +0000676 }
677
Frederick Mayledc07cf82022-05-26 20:30:12 +0000678 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
679
680 if (command.bodySize < rpcReplyWireSize) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000681 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
682 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000683 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000684 return BAD_VALUE;
685 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000686
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000687 RpcWireReply rpcReply;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000688 memset(&rpcReply, 0, sizeof(RpcWireReply)); // zero because of potential short read
689
690 CommandData data(command.bodySize - rpcReplyWireSize);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000691 if (!data.valid()) return NO_MEMORY;
692
693 iovec iovs[]{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000694 {&rpcReply, rpcReplyWireSize},
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000695 {data.data(), data.size()},
696 };
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000697 if (status_t status = rpcRec(connection, session, "reply body", iovs, arraysize(iovs), nullptr);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000698 status != OK)
699 return status;
Frederick Mayle69a0c992022-05-26 20:38:39 +0000700
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000701 if (rpcReply.status != OK) return rpcReply.status;
702
Frederick Mayledc07cf82022-05-26 20:30:12 +0000703 Span<const uint8_t> parcelSpan = {data.data(), data.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000704 Span<const uint32_t> objectTableSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000705 if (session->getProtocolVersion().value() >=
706 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000707 std::optional<Span<const uint8_t>> objectTableBytes =
708 parcelSpan.splitOff(rpcReply.parcelDataSize);
709 if (!objectTableBytes.has_value()) {
710 ALOGE("Parcel size larger than available bytes: %" PRId32 " vs %zu. Terminating!",
711 rpcReply.parcelDataSize, parcelSpan.byteSize());
712 (void)session->shutdownAndWait(false);
713 return BAD_VALUE;
714 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000715 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000716 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000717 if (!maybeSpan.has_value()) {
718 ALOGE("Bad object table size inferred from RpcWireReply. Saw bodySize=%" PRId32
719 " sizeofHeader=%zu parcelSize=%" PRId32 " objectTableBytesSize=%zu. Terminating!",
720 command.bodySize, rpcReplyWireSize, rpcReply.parcelDataSize,
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000721 objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000722 return BAD_VALUE;
723 }
724 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000725 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000726
Frederick Mayledc07cf82022-05-26 20:30:12 +0000727 data.release();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000728 return reply->rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
729 objectTableSpan.data, objectTableSpan.size,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000730 std::move(ancillaryFds), cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000731}
732
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000733status_t RpcState::sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection,
734 const sp<RpcSession>& session, uint64_t addr,
735 size_t target) {
736 RpcDecStrong body = {
737 .address = RpcWireAddress::fromRaw(addr),
738 };
739
Steven Moreland5553ac42020-11-11 02:14:45 +0000740 {
Steven Moreland67f85902023-03-15 01:13:49 +0000741 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000742 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
743 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700744 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
745 "Sending dec strong on unknown address %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000746
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000747 LOG_ALWAYS_FATAL_IF(it->second.timesRecd < target, "Can't dec count of %zu to %zu.",
748 it->second.timesRecd, target);
749
750 // typically this happens when multiple threads send dec refs at the
751 // same time - the transactions will get combined automatically
752 if (it->second.timesRecd == target) return OK;
753
754 body.amount = it->second.timesRecd - target;
755 it->second.timesRecd = target;
756
Steven Moreland67f85902023-03-15 01:13:49 +0000757 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(session, std::move(_l), it),
Steven Moreland31bde7a2021-06-04 00:57:36 +0000758 "Bad state. RpcState shouldn't own received binder");
Steven Moreland67f85902023-03-15 01:13:49 +0000759 // LOCK ALREADY RELEASED
Steven Moreland5553ac42020-11-11 02:14:45 +0000760 }
761
762 RpcWireHeader cmd = {
763 .command = RPC_COMMAND_DEC_STRONG,
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000764 .bodySize = sizeof(RpcDecStrong),
Steven Moreland5553ac42020-11-11 02:14:45 +0000765 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000766 iovec iovs[]{{&cmd, sizeof(cmd)}, {&body, sizeof(body)}};
Devin Moore695368f2022-06-03 22:29:14 +0000767 return rpcSend(connection, session, "dec ref", iovs, arraysize(iovs), std::nullopt);
Steven Moreland5553ac42020-11-11 02:14:45 +0000768}
769
Steven Moreland5ae62562021-06-10 03:21:42 +0000770status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
771 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700772 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000773
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000774 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000775 RpcWireHeader command;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000776 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000777 if (status_t status =
778 rpcRec(connection, session, "command header (for server)", &iov, 1,
779 enableAncillaryFds(session->getFileDescriptorTransportMode()) ? &ancillaryFds
780 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000781 status != OK)
782 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000783
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000784 return processCommand(connection, session, command, type, std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000785}
786
Steven Moreland5ae62562021-06-10 03:21:42 +0000787status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
788 const sp<RpcSession>& session, CommandType type) {
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000789 while (true) {
Andrei Homescu1975aaa2022-03-19 02:34:57 +0000790 status_t status = connection->rpcTransport->pollRead();
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000791 if (status == WOULD_BLOCK) break;
792 if (status != OK) return status;
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000793
794 status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000795 if (status != OK) return status;
796 }
797 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000798}
799
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000800status_t RpcState::processCommand(
801 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
802 const RpcWireHeader& command, CommandType type,
803 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland32150282021-11-12 22:54:53 +0000804#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000805 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
806 IPCThreadState::SpGuard spGuard{
807 .address = __builtin_frame_address(0),
Steven Morelande42ffd02022-07-06 21:46:23 +0000808 .context = "processing binder RPC command (where RpcServer::setPerSessionRootObject is "
809 "used to distinguish callers)",
Steven Morelandd7302072021-05-15 01:32:04 +0000810 };
811 const IPCThreadState::SpGuard* origGuard;
812 if (kernelBinderState != nullptr) {
813 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
814 }
Steven Moreland32150282021-11-12 22:54:53 +0000815
Tomasz Wasilczykd6c8a4c2023-10-11 20:41:51 +0000816 auto guardUnguard = make_scope_guard([&]() {
Steven Morelandd7302072021-05-15 01:32:04 +0000817 if (kernelBinderState != nullptr) {
818 kernelBinderState->restoreGetCallingSpGuard(origGuard);
819 }
Tomasz Wasilczykd6c8a4c2023-10-11 20:41:51 +0000820 });
Steven Moreland32150282021-11-12 22:54:53 +0000821#endif // BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000822
Steven Moreland5553ac42020-11-11 02:14:45 +0000823 switch (command.command) {
824 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000825 if (type != CommandType::ANY) return BAD_TYPE;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000826 return processTransact(connection, session, command, std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000827 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000828 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000829 }
830
831 // We should always know the version of the opposing side, and since the
832 // RPC-binder-level wire protocol is not self synchronizing, we have no way
833 // to understand where the current command ends and the next one begins. We
834 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000835 // to kill us, so ending the session for misbehaving client.
836 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000837 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000838 return DEAD_OBJECT;
839}
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000840status_t RpcState::processTransact(
841 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
842 const RpcWireHeader& command,
843 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000844 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
845
Steven Morelanddbe71832021-05-12 23:31:00 +0000846 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000847 if (!transactionData.valid()) {
848 return NO_MEMORY;
849 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000850 iovec iov{transactionData.data(), transactionData.size()};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000851 if (status_t status = rpcRec(connection, session, "transaction body", &iov, 1, nullptr);
852 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000853 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000854
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000855 return processTransactInternal(connection, session, std::move(transactionData),
856 std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000857}
858
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000859static void do_nothing_to_transact_data(const uint8_t* data, size_t dataSize,
Steven Moreland438cce82021-04-02 18:04:08 +0000860 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland438cce82021-04-02 18:04:08 +0000861 (void)data;
862 (void)dataSize;
863 (void)objects;
864 (void)objectsCount;
865}
866
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000867status_t RpcState::processTransactInternal(
868 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
869 CommandData transactionData,
870 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Morelandada72bd2021-06-09 23:29:13 +0000871 // for 'recursive' calls to this, we have already read and processed the
872 // binder from the transaction data and taken reference counts into account,
873 // so it is cached here.
Steven Moreland3903bf02021-09-27 16:05:24 -0700874 sp<IBinder> target;
Steven Morelandada72bd2021-06-09 23:29:13 +0000875processTransactInternalTailCall:
876
Steven Moreland5553ac42020-11-11 02:14:45 +0000877 if (transactionData.size() < sizeof(RpcWireTransaction)) {
878 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
879 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000880 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000881 return BAD_VALUE;
882 }
883 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
884
Steven Moreland5623d1a2021-09-10 15:45:34 -0700885 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000886 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000887
888 status_t replyStatus = OK;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700889 if (addr != 0) {
Steven Moreland3903bf02021-09-27 16:05:24 -0700890 if (!target) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000891 replyStatus = onBinderEntering(session, addr, &target);
Steven Morelandf5174272021-05-25 00:39:28 +0000892 }
893
Steven Moreland7227c8a2021-06-02 00:24:32 +0000894 if (replyStatus != OK) {
895 // do nothing
896 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000897 // This can happen if the binder is remote in this process, and
898 // another thread has called the last decStrong on this binder.
899 // However, for local binders, it indicates a misbehaving client
900 // (any binder which is being transacted on should be holding a
901 // strong ref count), so in either case, terminating the
902 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700903 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
904 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000905 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000906 replyStatus = BAD_VALUE;
907 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700908 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
909 ". Terminating!",
910 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000911 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000912 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000913 } else if (oneway) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000914 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000915 auto it = mNodeForAddress.find(addr);
916 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700917 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000918 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000919 } else if (transaction->asyncNumber != it->second.asyncNumber) {
920 // we need to process some other asynchronous transaction
921 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000922 it->second.asyncTodo.push(BinderNode::AsyncTodo{
923 .ref = target,
924 .data = std::move(transactionData),
Frederick Mayleb0221d12022-10-03 23:10:53 +0000925 .ancillaryFds = std::move(ancillaryFds),
Steven Morelandf5174272021-05-25 00:39:28 +0000926 .asyncNumber = transaction->asyncNumber,
927 });
Steven Morelandd45be622021-06-04 02:19:37 +0000928
929 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700930 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
931 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000932
933 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
934 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
935 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
936
937 if (numPending >= kArbitraryOnewayCallWarnLevel) {
938 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
939 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
940 _l.unlock();
941 (void)session->shutdownAndWait(false);
942 return FAILED_TRANSACTION;
943 }
944
945 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
946 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
947 target.get(), numPending);
948 }
949 }
Steven Morelandf5174272021-05-25 00:39:28 +0000950 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000951 }
952 }
953 }
954
Steven Moreland5553ac42020-11-11 02:14:45 +0000955 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000956 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000957
958 if (replyStatus == OK) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000959 Span<const uint8_t> parcelSpan = {transaction->data,
960 transactionData.size() -
961 offsetof(RpcWireTransaction, data)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000962 Span<const uint32_t> objectTableSpan;
Steven Moreland28c87282023-04-14 21:03:01 +0000963 if (session->getProtocolVersion().value() >=
Frederick Mayledc07cf82022-05-26 20:30:12 +0000964 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000965 std::optional<Span<const uint8_t>> objectTableBytes =
966 parcelSpan.splitOff(transaction->parcelDataSize);
967 if (!objectTableBytes.has_value()) {
968 ALOGE("Parcel size (%" PRId32 ") greater than available bytes (%zu). Terminating!",
969 transaction->parcelDataSize, parcelSpan.byteSize());
970 (void)session->shutdownAndWait(false);
971 return BAD_VALUE;
972 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000973 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000974 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000975 if (!maybeSpan.has_value()) {
976 ALOGE("Bad object table size inferred from RpcWireTransaction. Saw bodySize=%zu "
977 "sizeofHeader=%zu parcelSize=%" PRId32
978 " objectTableBytesSize=%zu. Terminating!",
979 transactionData.size(), sizeof(RpcWireTransaction),
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000980 transaction->parcelDataSize, objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000981 return BAD_VALUE;
982 }
983 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000984 }
985
Steven Morelandeff77c12021-04-15 00:37:19 +0000986 Parcel data;
987 // transaction->data is owned by this function. Parcel borrows this data and
988 // only holds onto it for the duration of this function call. Parcel will be
989 // deleted before the 'transactionData' object.
Frederick Mayledc07cf82022-05-26 20:30:12 +0000990
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000991 replyStatus =
992 data.rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
993 objectTableSpan.data, objectTableSpan.size,
994 std::move(ancillaryFds), do_nothing_to_transact_data);
995 // Reset to avoid spurious use-after-move warning from clang-tidy.
996 ancillaryFds = std::remove_reference<decltype(ancillaryFds)>::type();
Steven Morelandeff77c12021-04-15 00:37:19 +0000997
Frederick Mayle69a0c992022-05-26 20:38:39 +0000998 if (replyStatus == OK) {
999 if (target) {
1000 bool origAllowNested = connection->allowNested;
1001 connection->allowNested = !oneway;
Steven Morelandc7d40132021-06-10 03:42:11 +00001002
Frederick Mayle69a0c992022-05-26 20:38:39 +00001003 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +00001004
Frederick Mayle69a0c992022-05-26 20:38:39 +00001005 connection->allowNested = origAllowNested;
1006 } else {
1007 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +00001008
Frederick Mayle69a0c992022-05-26 20:38:39 +00001009 switch (transaction->code) {
1010 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
1011 replyStatus = reply.writeInt32(session->getMaxIncomingThreads());
1012 break;
1013 }
1014 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
1015 // for client connections, this should always report the value
1016 // originally returned from the server, so this is asserting
1017 // that it exists
1018 replyStatus = reply.writeByteVector(session->mId);
1019 break;
1020 }
1021 default: {
1022 sp<RpcServer> server = session->server();
1023 if (server) {
1024 switch (transaction->code) {
1025 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
1026 sp<IBinder> root = session->mSessionSpecificRootObject
1027 ?: server->getRootObject();
1028 replyStatus = reply.writeStrongBinder(root);
1029 break;
1030 }
1031 default: {
1032 replyStatus = UNKNOWN_TRANSACTION;
1033 }
Steven Moreland103424e2021-06-02 18:16:19 +00001034 }
Frederick Mayle69a0c992022-05-26 20:38:39 +00001035 } else {
1036 ALOGE("Special command sent, but no server object attached.");
Steven Moreland103424e2021-06-02 18:16:19 +00001037 }
Steven Morelandf137de92021-04-24 01:54:26 +00001038 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001039 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001040 }
1041 }
1042 }
1043
Steven Morelandc7d40132021-06-10 03:42:11 +00001044 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001045 if (replyStatus != OK) {
1046 ALOGW("Oneway call failed with error: %d", replyStatus);
1047 }
1048
Steven Moreland5623d1a2021-09-10 15:45:34 -07001049 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
1050 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001051
1052 // Check to see if there is another asynchronous transaction to process.
1053 // This behavior differs from binder behavior, since in the binder
1054 // driver, asynchronous transactions will be processed after existing
1055 // pending binder transactions on the queue. The downside of this is
1056 // that asynchronous transactions can be drowned out by synchronous
1057 // transactions. However, we have no easy way to queue these
1058 // transactions after the synchronous transactions we may want to read
1059 // from the wire. So, in socket binder here, we have the opposite
1060 // downside: asynchronous transactions may drown out synchronous
1061 // transactions.
1062 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001063 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001064 auto it = mNodeForAddress.find(addr);
1065 // last refcount dropped after this transaction happened
1066 if (it == mNodeForAddress.end()) return OK;
1067
Steven Morelandc9d7b532021-06-04 20:57:41 +00001068 if (!nodeProgressAsyncNumber(&it->second)) {
1069 _l.unlock();
1070 (void)session->shutdownAndWait(false);
1071 return DEAD_OBJECT;
1072 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001073
Andrei Homescuae5f0d12023-02-25 05:03:31 +00001074 if (it->second.asyncTodo.size() != 0 &&
1075 it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001076 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
1077 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001078
1079 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +00001080 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +00001081 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +00001082 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
1083
Steven Morelandada72bd2021-06-09 23:29:13 +00001084 // reset up arguments
1085 transactionData = std::move(todo.data);
Frederick Mayleb0221d12022-10-03 23:10:53 +00001086 ancillaryFds = std::move(todo.ancillaryFds);
Steven Moreland3903bf02021-09-27 16:05:24 -07001087 LOG_ALWAYS_FATAL_IF(target != todo.ref,
1088 "async list should be associated with a binder");
Steven Morelandf5174272021-05-25 00:39:28 +00001089
Steven Moreland5553ac42020-11-11 02:14:45 +00001090 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +00001091 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +00001092 }
1093 }
Steven Morelandd8083312021-09-22 13:37:10 -07001094
1095 // done processing all the async commands on this binder that we can, so
1096 // write decstrongs on the binder
1097 if (addr != 0 && replyStatus == OK) {
1098 return flushExcessBinderRefs(session, addr, target);
1099 }
1100
Steven Moreland5553ac42020-11-11 02:14:45 +00001101 return OK;
1102 }
1103
Steven Moreland6709cf42021-09-30 15:21:54 -07001104 // Binder refs are flushed for oneway calls only after all calls which are
1105 // built up are executed. Otherwise, they fill up the binder buffer.
1106 if (addr != 0 && replyStatus == OK) {
1107 replyStatus = flushExcessBinderRefs(session, addr, target);
1108 }
1109
Frederick Mayle69a0c992022-05-26 20:38:39 +00001110 std::string errorMsg;
1111 if (status_t status = validateParcel(session, reply, &errorMsg); status != OK) {
1112 ALOGE("Reply Parcel failed validation: %s", errorMsg.c_str());
1113 // Forward the error to the client of the transaction.
1114 reply.freeData();
1115 reply.markForRpc(session);
1116 replyStatus = status;
1117 }
1118
1119 auto* rpcFields = reply.maybeRpcFields();
1120 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
1121
Frederick Mayledc07cf82022-05-26 20:30:12 +00001122 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
1123
Frederick Mayle69a0c992022-05-26 20:38:39 +00001124 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
1125 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +00001126
Frederick Mayle778c0902022-05-27 01:14:57 +00001127 uint32_t bodySize;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001128 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(rpcReplyWireSize, reply.dataSize(), &bodySize) ||
1129 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
1130 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +00001131 "Too much data for reply %zu", reply.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +00001132 RpcWireHeader cmdReply{
1133 .command = RPC_COMMAND_REPLY,
Frederick Mayle778c0902022-05-27 01:14:57 +00001134 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +00001135 };
Steven Moreland5553ac42020-11-11 02:14:45 +00001136 RpcWireReply rpcReply{
1137 .status = replyStatus,
Frederick Mayledc07cf82022-05-26 20:30:12 +00001138 // NOTE: Not necessarily written to socket depending on session
1139 // version.
1140 // NOTE: bodySize didn't overflow => this cast is safe
1141 .parcelDataSize = static_cast<uint32_t>(reply.dataSize()),
1142 .reserved = {0, 0, 0},
Steven Moreland5553ac42020-11-11 02:14:45 +00001143 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001144 iovec iovs[]{
1145 {&cmdReply, sizeof(RpcWireHeader)},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001146 {&rpcReply, rpcReplyWireSize},
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001147 {const_cast<uint8_t*>(reply.data()), reply.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001148 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001149 };
Frederick Mayle69a0c992022-05-26 20:38:39 +00001150 return rpcSend(connection, session, "reply", iovs, arraysize(iovs), std::nullopt,
1151 rpcFields->mFds.get());
Steven Moreland5553ac42020-11-11 02:14:45 +00001152}
1153
Steven Moreland5ae62562021-06-10 03:21:42 +00001154status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
1155 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001156 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
1157
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001158 if (command.bodySize != sizeof(RpcDecStrong)) {
1159 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcDecStrong. Terminating!",
1160 sizeof(RpcDecStrong), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001161 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001162 return BAD_VALUE;
1163 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001164
Frederick Mayleb86cda42022-06-09 23:17:45 +00001165 RpcDecStrong body;
1166 iovec iov{&body, sizeof(RpcDecStrong)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001167 if (status_t status = rpcRec(connection, session, "dec ref body", &iov, 1, nullptr);
1168 status != OK)
Frederick Mayleb86cda42022-06-09 23:17:45 +00001169 return status;
1170
1171 uint64_t addr = RpcWireAddress::toRaw(body.address);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001172 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001173 auto it = mNodeForAddress.find(addr);
1174 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001175 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001176 return OK;
1177 }
1178
1179 sp<IBinder> target = it->second.binder.promote();
1180 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001181 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
1182 ". Terminating!",
1183 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001184 _l.unlock();
1185 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001186 return BAD_VALUE;
1187 }
1188
Frederick Mayleb86cda42022-06-09 23:17:45 +00001189 if (it->second.timesSent < body.amount) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001190 ALOGE("Record of sending binder %zu times, but requested decStrong for %" PRIu64 " of %u",
Frederick Mayleb86cda42022-06-09 23:17:45 +00001191 it->second.timesSent, addr, body.amount);
Steven Moreland5553ac42020-11-11 02:14:45 +00001192 return OK;
1193 }
1194
Steven Moreland5623d1a2021-09-10 15:45:34 -07001195 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
1196 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001197
Frederick Mayleb86cda42022-06-09 23:17:45 +00001198 LOG_RPC_DETAIL("Processing dec strong of %" PRIu64 " by %u from %zu", addr, body.amount,
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001199 it->second.timesSent);
1200
Frederick Mayleb86cda42022-06-09 23:17:45 +00001201 it->second.timesSent -= body.amount;
Steven Moreland67f85902023-03-15 01:13:49 +00001202 sp<IBinder> tempHold = tryEraseNode(session, std::move(_l), it);
1203 // LOCK ALREADY RELEASED
Steven Moreland31bde7a2021-06-04 00:57:36 +00001204 tempHold = nullptr; // destructor may make binder calls on this session
1205
1206 return OK;
1207}
1208
Frederick Mayle69a0c992022-05-26 20:38:39 +00001209status_t RpcState::validateParcel(const sp<RpcSession>& session, const Parcel& parcel,
1210 std::string* errorMsg) {
1211 auto* rpcFields = parcel.maybeRpcFields();
1212 if (rpcFields == nullptr) {
1213 *errorMsg = "Parcel not crafted for RPC call";
1214 return BAD_TYPE;
1215 }
1216
1217 if (rpcFields->mSession != session) {
1218 *errorMsg = "Parcel's session doesn't match";
1219 return BAD_TYPE;
1220 }
1221
1222 uint32_t protocolVersion = session->getProtocolVersion().value();
1223 if (protocolVersion < RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE &&
1224 !rpcFields->mObjectPositions.empty()) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +00001225 std::stringstream ss;
1226 ss << "Parcel has attached objects but the session's protocol version (" << protocolVersion
1227 << ") is too old, must be at least "
1228 << RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE;
1229 *errorMsg = ss.str();
Frederick Mayle69a0c992022-05-26 20:38:39 +00001230 return BAD_VALUE;
1231 }
1232
1233 if (rpcFields->mFds && !rpcFields->mFds->empty()) {
1234 switch (session->getFileDescriptorTransportMode()) {
1235 case RpcSession::FileDescriptorTransportMode::NONE:
1236 *errorMsg =
1237 "Parcel has file descriptors, but no file descriptor transport is enabled";
1238 return FDS_NOT_ALLOWED;
1239 case RpcSession::FileDescriptorTransportMode::UNIX: {
1240 constexpr size_t kMaxFdsPerMsg = 253;
1241 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +00001242 std::stringstream ss;
1243 ss << "Too many file descriptors in Parcel for unix domain socket: "
1244 << rpcFields->mFds->size() << " (max is " << kMaxFdsPerMsg << ")";
1245 *errorMsg = ss.str();
Frederick Mayle69a0c992022-05-26 20:38:39 +00001246 return BAD_VALUE;
1247 }
Andrei Homescu1c18a802022-08-17 04:59:01 +00001248 break;
1249 }
1250 case RpcSession::FileDescriptorTransportMode::TRUSTY: {
1251 // Keep this in sync with trusty_ipc.h!!!
1252 // We could import that file here on Trusty, but it's not
1253 // available on Android
1254 constexpr size_t kMaxFdsPerMsg = 8;
1255 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +00001256 std::stringstream ss;
1257 ss << "Too many file descriptors in Parcel for Trusty IPC connection: "
1258 << rpcFields->mFds->size() << " (max is " << kMaxFdsPerMsg << ")";
1259 *errorMsg = ss.str();
Andrei Homescu1c18a802022-08-17 04:59:01 +00001260 return BAD_VALUE;
1261 }
1262 break;
Frederick Mayle69a0c992022-05-26 20:38:39 +00001263 }
1264 }
1265 }
1266
1267 return OK;
1268}
1269
Steven Moreland67f85902023-03-15 01:13:49 +00001270sp<IBinder> RpcState::tryEraseNode(const sp<RpcSession>& session, RpcMutexUniqueLock nodeLock,
1271 std::map<uint64_t, BinderNode>::iterator& it) {
1272 bool shouldShutdown = false;
1273
Steven Moreland31bde7a2021-06-04 00:57:36 +00001274 sp<IBinder> ref;
1275
Steven Moreland5553ac42020-11-11 02:14:45 +00001276 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001277 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +00001278
1279 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +00001280 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
1281 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +00001282 mNodeForAddress.erase(it);
Steven Moreland67f85902023-03-15 01:13:49 +00001283
1284 if (mNodeForAddress.size() == 0) {
1285 shouldShutdown = true;
1286 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001287 }
1288 }
1289
Steven Moreland67f85902023-03-15 01:13:49 +00001290 // If we shutdown, prevent RpcState from being re-used. This prevents another
1291 // thread from getting the root object again.
1292 if (shouldShutdown) {
1293 clear(std::move(nodeLock));
1294 } else {
1295 nodeLock.unlock(); // explicit
1296 }
1297 // LOCK IS RELEASED
1298
1299 if (shouldShutdown) {
1300 ALOGI("RpcState has no binders left, so triggering shutdown...");
1301 (void)session->shutdownAndWait(false);
1302 }
1303
Steven Moreland31bde7a2021-06-04 00:57:36 +00001304 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +00001305}
1306
Steven Morelandc9d7b532021-06-04 20:57:41 +00001307bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +00001308 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
1309 // a single binder
1310 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
1311 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +00001312 return false;
1313 }
1314 node->asyncNumber++;
1315 return true;
1316}
1317
Steven Moreland5553ac42020-11-11 02:14:45 +00001318} // namespace android