blob: c090a9c36fa538f46195ee9d0c9ac91a1f4d29ca [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "RpcState"
18
19#include "RpcState.h"
20
21#include <binder/BpBinder.h>
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000022#include <binder/Functional.h>
Steven Morelandd7302072021-05-15 01:32:04 +000023#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000024#include <binder/RpcServer.h>
25
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
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000041using namespace android::binder::impl;
42
Devin Moore08256432021-07-02 13:03:49 -070043#if RPC_FLAKE_PRONE
Steven Morelandb8176792021-06-22 20:29:21 +000044void rpcMaybeWaitToFlake() {
Devin Moore08256432021-07-02 13:03:49 -070045 [[clang::no_destroy]] static std::random_device r;
Steven Moreland7e2675c2022-09-28 23:34:52 +000046 [[clang::no_destroy]] static RpcMutex m;
Steven Morelandb8176792021-06-22 20:29:21 +000047 unsigned num;
48 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000049 RpcMutexLockGuard lock(m);
Steven Morelandb8176792021-06-22 20:29:21 +000050 num = r();
51 }
52 if (num % 10 == 0) usleep(num % 1000);
53}
54#endif
55
Frederick Mayle69a0c992022-05-26 20:38:39 +000056static bool enableAncillaryFds(RpcSession::FileDescriptorTransportMode mode) {
57 switch (mode) {
58 case RpcSession::FileDescriptorTransportMode::NONE:
59 return false;
60 case RpcSession::FileDescriptorTransportMode::UNIX:
Andrei Homescu1c18a802022-08-17 04:59:01 +000061 case RpcSession::FileDescriptorTransportMode::TRUSTY:
Frederick Mayle69a0c992022-05-26 20:38:39 +000062 return true;
63 }
Tomasz Wasilczyk7b5430b2023-06-28 14:04:51 -070064 LOG_ALWAYS_FATAL("Invalid FileDescriptorTransportMode: %d", static_cast<int>(mode));
Frederick Mayle69a0c992022-05-26 20:38:39 +000065}
66
Steven Moreland5553ac42020-11-11 02:14:45 +000067RpcState::RpcState() {}
68RpcState::~RpcState() {}
69
Steven Morelandbdb53ab2021-05-05 17:57:41 +000070status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5623d1a2021-09-10 15:45:34 -070071 uint64_t* outAddress) {
Steven Moreland5553ac42020-11-11 02:14:45 +000072 bool isRemote = binder->remoteBinder();
73 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
74
Steven Moreland99157622021-09-13 16:27:34 -070075 if (isRpc && binder->remoteBinder()->getPrivateAccessor().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000076 // We need to be able to send instructions over the socket for how to
77 // connect to a different server, and we also need to let the host
78 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000079 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000080 return INVALID_OPERATION;
81 }
82
83 if (isRemote && !isRpc) {
84 // Without additional work, this would have the effect of using this
85 // process to proxy calls from the socket over to the other process, and
86 // it would make those calls look like they come from us (not over the
87 // sockets). In order to make this work transparently like binder, we
88 // would instead need to send instructions over the socket for how to
89 // connect to the host process, and we also need to let the host process
90 // know this was happening.
91 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
92 return INVALID_OPERATION;
93 }
94
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000095 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000096 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +000097
98 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
99 // in RpcState
100 for (auto& [addr, node] : mNodeForAddress) {
101 if (binder == node.binder) {
102 if (isRpc) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700103 // check integrity of data structure
Steven Moreland99157622021-09-13 16:27:34 -0700104 uint64_t actualAddr = binder->remoteBinder()->getPrivateAccessor().rpcAddress();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700105 LOG_ALWAYS_FATAL_IF(addr != actualAddr, "Address mismatch %" PRIu64 " vs %" PRIu64,
106 addr, actualAddr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000107 }
108 node.timesSent++;
109 node.sentRef = binder; // might already be set
110 *outAddress = addr;
111 return OK;
112 }
113 }
114 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
115
Steven Moreland91538242021-06-10 23:35:35 +0000116 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +0000117
Steven Moreland5623d1a2021-09-10 15:45:34 -0700118 // arbitrary limit for maximum number of nodes in a process (otherwise we
119 // might run out of addresses)
120 if (mNodeForAddress.size() > 100000) {
121 return NO_MEMORY;
122 }
123
124 while (true) {
125 RpcWireAddress address{
126 .options = RPC_WIRE_ADDRESS_OPTION_CREATED,
127 .address = mNextId,
128 };
129 if (forServer) {
130 address.options |= RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
131 }
132
133 // avoid ubsan abort
134 if (mNextId >= std::numeric_limits<uint32_t>::max()) {
135 mNextId = 0;
136 } else {
137 mNextId++;
138 }
139
140 auto&& [it, inserted] = mNodeForAddress.insert({RpcWireAddress::toRaw(address),
Steven Moreland91538242021-06-10 23:35:35 +0000141 BinderNode{
142 .binder = binder,
Steven Moreland91538242021-06-10 23:35:35 +0000143 .sentRef = binder,
Andrei Homescu5a036f32022-03-08 22:54:40 +0000144 .timesSent = 1,
Steven Moreland91538242021-06-10 23:35:35 +0000145 }});
146 if (inserted) {
147 *outAddress = it->first;
148 return OK;
149 }
Steven Moreland91538242021-06-10 23:35:35 +0000150 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000151}
152
Steven Moreland5623d1a2021-09-10 15:45:34 -0700153status_t RpcState::onBinderEntering(const sp<RpcSession>& session, uint64_t address,
Steven Moreland7227c8a2021-06-02 00:24:32 +0000154 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000155 // ensure that: if we want to use addresses for something else in the future (for
156 // instance, allowing transitive binder sends), that we don't accidentally
157 // send those addresses to old server. Accidentally ignoring this in that
158 // case and considering the binder to be recognized could cause this
159 // process to accidentally proxy transactions for that binder. Of course,
160 // if we communicate with a binder, it could always be proxying
161 // information. However, we want to make sure that isn't done on accident
162 // by a client.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700163 RpcWireAddress addr = RpcWireAddress::fromRaw(address);
164 constexpr uint32_t kKnownOptions =
165 RPC_WIRE_ADDRESS_OPTION_CREATED | RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
166 if (addr.options & ~kKnownOptions) {
167 ALOGE("Address is of an unknown type, rejecting: %" PRIu64, address);
Steven Moreland91538242021-06-10 23:35:35 +0000168 return BAD_VALUE;
169 }
170
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000171 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000172 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000173
174 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000175 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000176
177 // implicitly have strong RPC refcount, since we received this binder
178 it->second.timesRecd++;
Steven Morelandd8083312021-09-22 13:37:10 -0700179 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000180 }
181
Steven Moreland91538242021-06-10 23:35:35 +0000182 // we don't know about this binder, so the other side of the connection
183 // should have created it.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700184 if ((addr.options & RPC_WIRE_ADDRESS_OPTION_FOR_SERVER) == !!session->server()) {
185 ALOGE("Server received unrecognized address which we should own the creation of %" PRIu64,
186 address);
Steven Moreland91538242021-06-10 23:35:35 +0000187 return BAD_VALUE;
188 }
189
Steven Moreland5553ac42020-11-11 02:14:45 +0000190 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
191 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
192
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000193 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000194 // device global binders in the RPC world).
Steven Moreland99157622021-09-13 16:27:34 -0700195 it->second.binder = *out = BpBinder::PrivateAccessor::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000196 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000197 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000198}
199
Steven Morelandd8083312021-09-22 13:37:10 -0700200status_t RpcState::flushExcessBinderRefs(const sp<RpcSession>& session, uint64_t address,
201 const sp<IBinder>& binder) {
Steven Morelande96ed0e2021-09-27 17:43:53 -0700202 // We can flush all references when the binder is destroyed. No need to send
203 // extra reference counting packets now.
204 if (binder->remoteBinder()) return OK;
205
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000206 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandd8083312021-09-22 13:37:10 -0700207 if (mTerminated) return DEAD_OBJECT;
208
209 auto it = mNodeForAddress.find(address);
210
211 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Can't be deleted while we hold sp<>");
212 LOG_ALWAYS_FATAL_IF(it->second.binder != binder,
213 "Caller of flushExcessBinderRefs using inconsistent arguments");
214
Steven Morelande96ed0e2021-09-27 17:43:53 -0700215 LOG_ALWAYS_FATAL_IF(it->second.timesSent <= 0, "Local binder must have been sent %p",
216 binder.get());
Steven Morelandd8083312021-09-22 13:37:10 -0700217
Steven Morelande96ed0e2021-09-27 17:43:53 -0700218 // For a local binder, we only need to know that we sent it. Now that we
219 // have an sp<> for this call, we don't need anything more. If the other
220 // process is done with this binder, it needs to know we received the
221 // refcount associated with this call, so we can acknowledge that we
222 // received it. Once (or if) it has no other refcounts, it would reply with
223 // its own decStrong so that it could be removed from this session.
224 if (it->second.timesRecd != 0) {
Steven Morelandd8083312021-09-22 13:37:10 -0700225 _l.unlock();
226
Steven Morelande96ed0e2021-09-27 17:43:53 -0700227 return session->sendDecStrongToTarget(address, 0);
Steven Morelandd8083312021-09-22 13:37:10 -0700228 }
229
230 return OK;
231}
232
Devin Moore66d5b7a2022-07-07 21:42:10 +0000233status_t RpcState::sendObituaries(const sp<RpcSession>& session) {
234 RpcMutexUniqueLock _l(mNodeMutex);
235
236 // Gather strong pointers to all of the remote binders for this session so
237 // we hold the strong references. remoteBinder() returns a raw pointer.
238 // Send the obituaries and drop the strong pointers outside of the lock so
239 // the destructors and the onBinderDied calls are not done while locked.
240 std::vector<sp<IBinder>> remoteBinders;
241 for (const auto& [_, binderNode] : mNodeForAddress) {
242 if (auto binder = binderNode.binder.promote()) {
243 remoteBinders.push_back(std::move(binder));
244 }
245 }
246 _l.unlock();
247
248 for (const auto& binder : remoteBinders) {
249 if (binder->remoteBinder() &&
250 binder->remoteBinder()->getPrivateAccessor().rpcSession() == session) {
251 binder->remoteBinder()->sendObituary();
252 }
253 }
254 return OK;
255}
256
Steven Moreland5553ac42020-11-11 02:14:45 +0000257size_t RpcState::countBinders() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000258 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000259 return mNodeForAddress.size();
260}
261
262void RpcState::dump() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000263 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000264 dumpLocked();
265}
266
Steven Morelandc9d7b532021-06-04 20:57:41 +0000267void RpcState::clear() {
Steven Moreland67f85902023-03-15 01:13:49 +0000268 return clear(RpcMutexUniqueLock(mNodeMutex));
269}
Steven Morelandc9d7b532021-06-04 20:57:41 +0000270
Steven Moreland67f85902023-03-15 01:13:49 +0000271void RpcState::clear(RpcMutexUniqueLock nodeLock) {
Steven Morelandc9d7b532021-06-04 20:57:41 +0000272 if (mTerminated) {
273 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
274 "New state should be impossible after terminating!");
275 return;
276 }
Steven Moreland0092fe32022-07-15 00:15:34 +0000277 mTerminated = true;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000278
279 if (SHOULD_LOG_RPC_DETAIL) {
280 ALOGE("RpcState::clear()");
281 dumpLocked();
282 }
283
Steven Moreland0092fe32022-07-15 00:15:34 +0000284 // invariants
Steven Morelandc9d7b532021-06-04 20:57:41 +0000285 for (auto& [address, node] : mNodeForAddress) {
Steven Moreland0092fe32022-07-15 00:15:34 +0000286 bool guaranteedHaveBinder = node.timesSent > 0;
287 if (guaranteedHaveBinder) {
288 LOG_ALWAYS_FATAL_IF(node.sentRef == nullptr,
289 "Binder expected to be owned with address: %" PRIu64 " %s", address,
290 node.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000291 }
292 }
293
Steven Moreland0092fe32022-07-15 00:15:34 +0000294 // if the destructor of a binder object makes another RPC call, then calling
295 // decStrong could deadlock. So, we must hold onto these binders until
296 // mNodeMutex is no longer taken.
297 auto temp = std::move(mNodeForAddress);
298 mNodeForAddress.clear(); // RpcState isn't reusable, but for future/explicit
Steven Morelandc9d7b532021-06-04 20:57:41 +0000299
Steven Moreland67f85902023-03-15 01:13:49 +0000300 nodeLock.unlock();
Steven Moreland0092fe32022-07-15 00:15:34 +0000301 temp.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000302}
303
304void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000305 ALOGE("DUMP OF RpcState %p", this);
306 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
307 for (const auto& [address, node] : mNodeForAddress) {
Steven Moreland3fa32922022-07-14 18:45:51 +0000308 ALOGE("- address: %" PRIu64 " %s", address, node.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000309 }
310 ALOGE("END DUMP OF RpcState");
311}
312
Steven Moreland3fa32922022-07-14 18:45:51 +0000313std::string RpcState::BinderNode::toString() const {
314 sp<IBinder> strongBinder = this->binder.promote();
315
316 const char* desc;
317 if (strongBinder) {
318 if (strongBinder->remoteBinder()) {
319 if (strongBinder->remoteBinder()->isRpcBinder()) {
320 desc = "(rpc binder proxy)";
321 } else {
322 desc = "(binder proxy)";
323 }
324 } else {
325 desc = "(local binder)";
326 }
327 } else {
328 desc = "(not promotable)";
329 }
330
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +0000331 std::stringstream ss;
332 ss << "node{" << intptr_t(this->binder.unsafe_get()) << " times sent: " << this->timesSent
333 << " times recd: " << this->timesRecd << " type: " << desc << "}";
334 return ss.str();
Steven Moreland3fa32922022-07-14 18:45:51 +0000335}
Steven Moreland5553ac42020-11-11 02:14:45 +0000336
Steven Morelanddbe71832021-05-12 23:31:00 +0000337RpcState::CommandData::CommandData(size_t size) : mSize(size) {
338 // The maximum size for regular binder is 1MB for all concurrent
339 // transactions. A very small proportion of transactions are even
340 // larger than a page, but we need to avoid allocating too much
341 // data on behalf of an arbitrary client, or we could risk being in
342 // a position where a single additional allocation could run out of
343 // memory.
344 //
345 // Note, this limit may not reflect the total amount of data allocated for a
346 // transaction (in some cases, additional fixed size amounts are added),
347 // though for rough consistency, we should avoid cases where this data type
348 // is used for multiple dynamic allocations for a single transaction.
349 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
350 if (size == 0) return;
351 if (size > kMaxTransactionAllocation) {
352 ALOGW("Transaction requested too much data allocation %zu", size);
353 return;
354 }
355 mData.reset(new (std::nothrow) uint8_t[size]);
356}
357
Frederick Mayle69a0c992022-05-26 20:38:39 +0000358status_t RpcState::rpcSend(
359 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
360 const char* what, iovec* iovs, int niovs,
361 const std::optional<android::base::function_ref<status_t()>>& altPoll,
362 const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800363 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000364 LOG_RPC_DETAIL("Sending %s (part %d of %d) on RpcTransport %p: %s",
365 what, i + 1, niovs, connection->rpcTransport.get(),
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000366 HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000367 }
368
Yifan Hong702115c2021-06-24 15:39:18 -0700369 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700370 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
Frederick Mayle69a0c992022-05-26 20:38:39 +0000371 iovs, niovs, altPoll,
372 ancillaryFds);
Steven Moreland798e0d12021-07-14 23:19:25 +0000373 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800374 LOG_RPC_DETAIL("Failed to write %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700375 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000376 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000377 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000378 }
379
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000380 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000381}
382
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000383status_t RpcState::rpcRec(
384 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
385 const char* what, iovec* iovs, int niovs,
386 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
387 if (status_t status =
388 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
389 iovs, niovs, std::nullopt,
390 ancillaryFds);
Steven Morelandee3f4662021-05-22 01:07:33 +0000391 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800392 LOG_RPC_DETAIL("Failed to read %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700393 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandae58f432021-08-05 17:53:16 -0700394 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000395 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000396 }
397
Colin Cross9adfeaf2022-01-21 17:22:09 -0800398 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000399 LOG_RPC_DETAIL("Received %s (part %d of %d) on RpcTransport %p: %s",
400 what, i + 1, niovs, connection->rpcTransport.get(),
Tomasz Wasilczyk891f6b02023-10-11 18:35:42 +0000401 HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000402 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000403 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000404}
405
Steven Morelandca3f6382023-05-11 23:23:26 +0000406bool RpcState::validateProtocolVersion(uint32_t version) {
Steven Moreland09034a92023-05-31 20:49:11 +0000407 if (version == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
408#if defined(__ANDROID__)
409 char codename[PROPERTY_VALUE_MAX];
410 property_get("ro.build.version.codename", codename, "");
411 if (!strcmp(codename, "REL")) {
Steven Moreland0884c552023-10-17 18:23:31 +0000412 ALOGE("Cannot use experimental RPC binder protocol in a release configuration.");
Steven Moreland09034a92023-05-31 20:49:11 +0000413 return false;
414 }
415#else
Steven Moreland687728e2023-10-28 01:07:40 +0000416 ALOGE("Cannot use experimental RPC binder protocol outside of Android.");
417 return false;
Steven Moreland09034a92023-05-31 20:49:11 +0000418#endif
419 } else if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT) {
Steven Morelandca3f6382023-05-11 23:23:26 +0000420 ALOGE("Cannot use RPC binder protocol version %u which is unknown (current protocol "
421 "version "
422 "is %u).",
423 version, RPC_WIRE_PROTOCOL_VERSION);
424 return false;
425 }
Steven Moreland09034a92023-05-31 20:49:11 +0000426
Steven Morelandca3f6382023-05-11 23:23:26 +0000427 return true;
428}
429
Steven Morelandbf57bce2021-07-26 15:26:12 -0700430status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
431 const sp<RpcSession>& session, uint32_t* version) {
432 RpcNewSessionResponse response;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000433 iovec iov{&response, sizeof(response)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000434 if (status_t status = rpcRec(connection, session, "new session response", &iov, 1, nullptr);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700435 status != OK) {
436 return status;
437 }
438 *version = response.version;
439 return OK;
440}
441
Steven Moreland5ae62562021-06-10 03:21:42 +0000442status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
443 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000444 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000445 .msg = RPC_CONNECTION_INIT_OKAY,
446 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000447 iovec iov{&init, sizeof(init)};
Devin Moore695368f2022-06-03 22:29:14 +0000448 return rpcSend(connection, session, "connection init", &iov, 1, std::nullopt);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000449}
450
Steven Moreland5ae62562021-06-10 03:21:42 +0000451status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
452 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000453 RpcOutgoingConnectionInit init;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000454 iovec iov{&init, sizeof(init)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000455 if (status_t status = rpcRec(connection, session, "connection init", &iov, 1, nullptr);
456 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000457 return status;
458
459 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
460 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
461 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
462 init.msg);
463 return BAD_VALUE;
464 }
465 return OK;
466}
467
Steven Moreland5ae62562021-06-10 03:21:42 +0000468sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
469 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000470 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000471 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000472 Parcel reply;
473
Steven Moreland5623d1a2021-09-10 15:45:34 -0700474 status_t status =
475 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000476 if (status != OK) {
477 ALOGE("Error getting root object: %s", statusToString(status).c_str());
478 return nullptr;
479 }
480
481 return reply.readStrongBinder();
482}
483
Steven Moreland5ae62562021-06-10 03:21:42 +0000484status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
485 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000486 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000487 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000488 Parcel reply;
489
Steven Moreland5623d1a2021-09-10 15:45:34 -0700490 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
491 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000492 if (status != OK) {
493 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
494 return status;
495 }
496
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000497 int32_t maxThreads;
498 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000499 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000500 if (maxThreads <= 0) {
501 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000502 return BAD_VALUE;
503 }
504
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000505 *maxThreadsOut = maxThreads;
506 return OK;
507}
508
Steven Moreland5ae62562021-06-10 03:21:42 +0000509status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700510 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000511 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000512 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000513 Parcel reply;
514
Steven Moreland5623d1a2021-09-10 15:45:34 -0700515 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
516 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000517 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000518 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000519 return status;
520 }
521
Steven Moreland826367f2021-09-10 14:05:31 -0700522 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000523}
524
Steven Moreland5ae62562021-06-10 03:21:42 +0000525status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
526 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
527 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000528 std::string errorMsg;
529 if (status_t status = validateParcel(session, data, &errorMsg); status != OK) {
530 ALOGE("Refusing to send RPC on binder %p code %" PRIu32 ": Parcel %p failed validation: %s",
531 binder.get(), code, &data, errorMsg.c_str());
532 return status;
Steven Morelandf5174272021-05-25 00:39:28 +0000533 }
Steven Moreland5623d1a2021-09-10 15:45:34 -0700534 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000535 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
536
Steven Moreland5ae62562021-06-10 03:21:42 +0000537 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000538}
539
Steven Moreland5ae62562021-06-10 03:21:42 +0000540status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700541 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000542 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000543 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
544 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
545
Steven Moreland5553ac42020-11-11 02:14:45 +0000546 uint64_t asyncNumber = 0;
547
Steven Moreland5623d1a2021-09-10 15:45:34 -0700548 if (address != 0) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000549 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000550 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
551 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700552 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
553 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000554
555 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000556 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000557 if (!nodeProgressAsyncNumber(&it->second)) {
558 _l.unlock();
559 (void)session->shutdownAndWait(false);
560 return DEAD_OBJECT;
561 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000562 }
563 }
564
Frederick Mayle69a0c992022-05-26 20:38:39 +0000565 auto* rpcFields = data.maybeRpcFields();
566 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
567
568 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
569 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +0000570
Frederick Mayle778c0902022-05-27 01:14:57 +0000571 uint32_t bodySize;
572 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(sizeof(RpcWireTransaction), data.dataSize(),
Frederick Mayledc07cf82022-05-26 20:30:12 +0000573 &bodySize) ||
574 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
575 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +0000576 "Too much data %zu", data.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +0000577 RpcWireHeader command{
578 .command = RPC_COMMAND_TRANSACT,
Frederick Mayle778c0902022-05-27 01:14:57 +0000579 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +0000580 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700581
Steven Moreland5553ac42020-11-11 02:14:45 +0000582 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700583 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000584 .code = code,
585 .flags = flags,
586 .asyncNumber = asyncNumber,
Frederick Mayledc07cf82022-05-26 20:30:12 +0000587 // bodySize didn't overflow => this cast is safe
588 .parcelDataSize = static_cast<uint32_t>(data.dataSize()),
Steven Moreland5553ac42020-11-11 02:14:45 +0000589 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000590
Steven Moreland43921d52021-09-27 17:15:56 -0700591 // Oneway calls have no sync point, so if many are sent before, whether this
592 // is a twoway or oneway transaction, they may have filled up the socket.
Devin Moore695368f2022-06-03 22:29:14 +0000593 // So, make sure we drain them before polling
Steven Morelandda31af62023-02-25 01:55:58 +0000594 constexpr size_t kWaitMaxUs = 1000000;
595 constexpr size_t kWaitLogUs = 10000;
596 size_t waitUs = 0;
Steven Moreland43921d52021-09-27 17:15:56 -0700597
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000598 iovec iovs[]{
599 {&command, sizeof(RpcWireHeader)},
600 {&transaction, sizeof(RpcWireTransaction)},
601 {const_cast<uint8_t*>(data.data()), data.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +0000602 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000603 };
Frederick Mayle69a0c992022-05-26 20:38:39 +0000604 if (status_t status = rpcSend(
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -0700605 connection, session, "transaction", iovs, countof(iovs),
Frederick Mayle69a0c992022-05-26 20:38:39 +0000606 [&] {
607 if (waitUs > kWaitLogUs) {
608 ALOGE("Cannot send command, trying to process pending refcounts. Waiting "
609 "%zuus. Too many oneway calls?",
610 waitUs);
611 }
Devin Moore695368f2022-06-03 22:29:14 +0000612
Frederick Mayle69a0c992022-05-26 20:38:39 +0000613 if (waitUs > 0) {
614 usleep(waitUs);
615 waitUs = std::min(kWaitMaxUs, waitUs * 2);
616 } else {
617 waitUs = 1;
618 }
Devin Moore695368f2022-06-03 22:29:14 +0000619
Frederick Mayle69a0c992022-05-26 20:38:39 +0000620 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
621 },
622 rpcFields->mFds.get());
Steven Moreland43921d52021-09-27 17:15:56 -0700623 status != OK) {
Steven Morelandda31af62023-02-25 01:55:58 +0000624 // rpcSend calls shutdownAndWait, so all refcounts should be reset. If we ever tolerate
625 // errors here, then we may need to undo the binder-sent counts for the transaction as
626 // well as for the binder objects in the Parcel
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000627 return status;
Steven Moreland43921d52021-09-27 17:15:56 -0700628 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000629
630 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700631 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
632 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000633
634 // Do not wait on result.
Steven Moreland43921d52021-09-27 17:15:56 -0700635 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000636 }
637
638 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
639
Steven Moreland5ae62562021-06-10 03:21:42 +0000640 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000641}
642
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000643static void cleanup_reply_data(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
644 size_t objectsCount) {
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000645 delete[] const_cast<uint8_t*>(data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000646 (void)dataSize;
647 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000648 (void)objectsCount;
Steven Moreland5553ac42020-11-11 02:14:45 +0000649}
650
Steven Moreland5ae62562021-06-10 03:21:42 +0000651status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
652 const sp<RpcSession>& session, Parcel* reply) {
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000653 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000654 RpcWireHeader command;
655 while (true) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000656 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000657 if (status_t status = rpcRec(connection, session, "command header (for reply)", &iov, 1,
658 enableAncillaryFds(session->getFileDescriptorTransportMode())
659 ? &ancillaryFds
660 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000661 status != OK)
662 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000663
664 if (command.command == RPC_COMMAND_REPLY) break;
665
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000666 if (status_t status = processCommand(connection, session, command, CommandType::ANY,
667 std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000668 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000669 return status;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000670
671 // Reset to avoid spurious use-after-move warning from clang-tidy.
672 ancillaryFds = decltype(ancillaryFds)();
Steven Moreland5553ac42020-11-11 02:14:45 +0000673 }
674
Frederick Mayledc07cf82022-05-26 20:30:12 +0000675 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
676
677 if (command.bodySize < rpcReplyWireSize) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000678 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
679 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000680 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000681 return BAD_VALUE;
682 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000683
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000684 RpcWireReply rpcReply;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000685 memset(&rpcReply, 0, sizeof(RpcWireReply)); // zero because of potential short read
686
687 CommandData data(command.bodySize - rpcReplyWireSize);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000688 if (!data.valid()) return NO_MEMORY;
689
690 iovec iovs[]{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000691 {&rpcReply, rpcReplyWireSize},
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000692 {data.data(), data.size()},
693 };
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -0700694 if (status_t status = rpcRec(connection, session, "reply body", iovs, countof(iovs), nullptr);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000695 status != OK)
696 return status;
Frederick Mayle69a0c992022-05-26 20:38:39 +0000697
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000698 if (rpcReply.status != OK) return rpcReply.status;
699
Frederick Mayledc07cf82022-05-26 20:30:12 +0000700 Span<const uint8_t> parcelSpan = {data.data(), data.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000701 Span<const uint32_t> objectTableSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000702 if (session->getProtocolVersion().value() >=
703 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000704 std::optional<Span<const uint8_t>> objectTableBytes =
705 parcelSpan.splitOff(rpcReply.parcelDataSize);
706 if (!objectTableBytes.has_value()) {
707 ALOGE("Parcel size larger than available bytes: %" PRId32 " vs %zu. Terminating!",
708 rpcReply.parcelDataSize, parcelSpan.byteSize());
709 (void)session->shutdownAndWait(false);
710 return BAD_VALUE;
711 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000712 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000713 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000714 if (!maybeSpan.has_value()) {
715 ALOGE("Bad object table size inferred from RpcWireReply. Saw bodySize=%" PRId32
716 " sizeofHeader=%zu parcelSize=%" PRId32 " objectTableBytesSize=%zu. Terminating!",
717 command.bodySize, rpcReplyWireSize, rpcReply.parcelDataSize,
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000718 objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000719 return BAD_VALUE;
720 }
721 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000722 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000723
Frederick Mayledc07cf82022-05-26 20:30:12 +0000724 data.release();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000725 return reply->rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
726 objectTableSpan.data, objectTableSpan.size,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000727 std::move(ancillaryFds), cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000728}
729
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000730status_t RpcState::sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection,
731 const sp<RpcSession>& session, uint64_t addr,
732 size_t target) {
733 RpcDecStrong body = {
734 .address = RpcWireAddress::fromRaw(addr),
735 };
736
Steven Moreland5553ac42020-11-11 02:14:45 +0000737 {
Steven Moreland67f85902023-03-15 01:13:49 +0000738 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000739 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
740 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700741 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
742 "Sending dec strong on unknown address %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000743
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000744 LOG_ALWAYS_FATAL_IF(it->second.timesRecd < target, "Can't dec count of %zu to %zu.",
745 it->second.timesRecd, target);
746
747 // typically this happens when multiple threads send dec refs at the
748 // same time - the transactions will get combined automatically
749 if (it->second.timesRecd == target) return OK;
750
751 body.amount = it->second.timesRecd - target;
752 it->second.timesRecd = target;
753
Steven Moreland67f85902023-03-15 01:13:49 +0000754 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(session, std::move(_l), it),
Steven Moreland31bde7a2021-06-04 00:57:36 +0000755 "Bad state. RpcState shouldn't own received binder");
Steven Moreland67f85902023-03-15 01:13:49 +0000756 // LOCK ALREADY RELEASED
Steven Moreland5553ac42020-11-11 02:14:45 +0000757 }
758
759 RpcWireHeader cmd = {
760 .command = RPC_COMMAND_DEC_STRONG,
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000761 .bodySize = sizeof(RpcDecStrong),
Steven Moreland5553ac42020-11-11 02:14:45 +0000762 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000763 iovec iovs[]{{&cmd, sizeof(cmd)}, {&body, sizeof(body)}};
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -0700764 return rpcSend(connection, session, "dec ref", iovs, countof(iovs), std::nullopt);
Steven Moreland5553ac42020-11-11 02:14:45 +0000765}
766
Steven Moreland5ae62562021-06-10 03:21:42 +0000767status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
768 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700769 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000770
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000771 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000772 RpcWireHeader command;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000773 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000774 if (status_t status =
775 rpcRec(connection, session, "command header (for server)", &iov, 1,
776 enableAncillaryFds(session->getFileDescriptorTransportMode()) ? &ancillaryFds
777 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000778 status != OK)
779 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000780
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000781 return processCommand(connection, session, command, type, std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000782}
783
Steven Moreland5ae62562021-06-10 03:21:42 +0000784status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
785 const sp<RpcSession>& session, CommandType type) {
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000786 while (true) {
Andrei Homescu1975aaa2022-03-19 02:34:57 +0000787 status_t status = connection->rpcTransport->pollRead();
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000788 if (status == WOULD_BLOCK) break;
789 if (status != OK) return status;
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000790
791 status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000792 if (status != OK) return status;
793 }
794 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000795}
796
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000797status_t RpcState::processCommand(
798 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
799 const RpcWireHeader& command, CommandType type,
800 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland32150282021-11-12 22:54:53 +0000801#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000802 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
803 IPCThreadState::SpGuard spGuard{
804 .address = __builtin_frame_address(0),
Steven Morelande42ffd02022-07-06 21:46:23 +0000805 .context = "processing binder RPC command (where RpcServer::setPerSessionRootObject is "
806 "used to distinguish callers)",
Steven Morelandd7302072021-05-15 01:32:04 +0000807 };
808 const IPCThreadState::SpGuard* origGuard;
809 if (kernelBinderState != nullptr) {
810 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
811 }
Steven Moreland32150282021-11-12 22:54:53 +0000812
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +0000813 auto guardUnguard = make_scope_guard([&]() {
Steven Morelandd7302072021-05-15 01:32:04 +0000814 if (kernelBinderState != nullptr) {
815 kernelBinderState->restoreGetCallingSpGuard(origGuard);
816 }
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +0000817 });
Steven Moreland32150282021-11-12 22:54:53 +0000818#endif // BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000819
Steven Moreland5553ac42020-11-11 02:14:45 +0000820 switch (command.command) {
821 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000822 if (type != CommandType::ANY) return BAD_TYPE;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000823 return processTransact(connection, session, command, std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000824 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000825 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000826 }
827
828 // We should always know the version of the opposing side, and since the
829 // RPC-binder-level wire protocol is not self synchronizing, we have no way
830 // to understand where the current command ends and the next one begins. We
831 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000832 // to kill us, so ending the session for misbehaving client.
833 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000834 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000835 return DEAD_OBJECT;
836}
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000837status_t RpcState::processTransact(
838 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
839 const RpcWireHeader& command,
840 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000841 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
842
Steven Morelanddbe71832021-05-12 23:31:00 +0000843 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000844 if (!transactionData.valid()) {
845 return NO_MEMORY;
846 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000847 iovec iov{transactionData.data(), transactionData.size()};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000848 if (status_t status = rpcRec(connection, session, "transaction body", &iov, 1, nullptr);
849 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000850 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000851
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000852 return processTransactInternal(connection, session, std::move(transactionData),
853 std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000854}
855
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000856static void do_nothing_to_transact_data(const uint8_t* data, size_t dataSize,
Steven Moreland438cce82021-04-02 18:04:08 +0000857 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland438cce82021-04-02 18:04:08 +0000858 (void)data;
859 (void)dataSize;
860 (void)objects;
861 (void)objectsCount;
862}
863
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000864status_t RpcState::processTransactInternal(
865 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
866 CommandData transactionData,
867 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Morelandada72bd2021-06-09 23:29:13 +0000868 // for 'recursive' calls to this, we have already read and processed the
869 // binder from the transaction data and taken reference counts into account,
870 // so it is cached here.
Steven Moreland3903bf02021-09-27 16:05:24 -0700871 sp<IBinder> target;
Steven Morelandada72bd2021-06-09 23:29:13 +0000872processTransactInternalTailCall:
873
Steven Moreland5553ac42020-11-11 02:14:45 +0000874 if (transactionData.size() < sizeof(RpcWireTransaction)) {
875 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
876 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000877 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000878 return BAD_VALUE;
879 }
880 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
881
Steven Moreland5623d1a2021-09-10 15:45:34 -0700882 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000883 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000884
885 status_t replyStatus = OK;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700886 if (addr != 0) {
Steven Moreland3903bf02021-09-27 16:05:24 -0700887 if (!target) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000888 replyStatus = onBinderEntering(session, addr, &target);
Steven Morelandf5174272021-05-25 00:39:28 +0000889 }
890
Steven Moreland7227c8a2021-06-02 00:24:32 +0000891 if (replyStatus != OK) {
892 // do nothing
893 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000894 // This can happen if the binder is remote in this process, and
895 // another thread has called the last decStrong on this binder.
896 // However, for local binders, it indicates a misbehaving client
897 // (any binder which is being transacted on should be holding a
898 // strong ref count), so in either case, terminating the
899 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700900 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
901 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000902 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000903 replyStatus = BAD_VALUE;
904 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700905 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
906 ". Terminating!",
907 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000908 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000909 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000910 } else if (oneway) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000911 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000912 auto it = mNodeForAddress.find(addr);
913 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700914 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000915 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000916 } else if (transaction->asyncNumber != it->second.asyncNumber) {
917 // we need to process some other asynchronous transaction
918 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000919 it->second.asyncTodo.push(BinderNode::AsyncTodo{
920 .ref = target,
921 .data = std::move(transactionData),
Frederick Mayleb0221d12022-10-03 23:10:53 +0000922 .ancillaryFds = std::move(ancillaryFds),
Steven Morelandf5174272021-05-25 00:39:28 +0000923 .asyncNumber = transaction->asyncNumber,
924 });
Steven Morelandd45be622021-06-04 02:19:37 +0000925
926 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700927 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
928 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000929
930 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
931 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
932 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
933
934 if (numPending >= kArbitraryOnewayCallWarnLevel) {
935 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
936 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
937 _l.unlock();
938 (void)session->shutdownAndWait(false);
939 return FAILED_TRANSACTION;
940 }
941
942 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
943 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
944 target.get(), numPending);
945 }
946 }
Steven Morelandf5174272021-05-25 00:39:28 +0000947 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000948 }
949 }
950 }
951
Steven Moreland5553ac42020-11-11 02:14:45 +0000952 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000953 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000954
955 if (replyStatus == OK) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000956 Span<const uint8_t> parcelSpan = {transaction->data,
957 transactionData.size() -
958 offsetof(RpcWireTransaction, data)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000959 Span<const uint32_t> objectTableSpan;
Steven Moreland28c87282023-04-14 21:03:01 +0000960 if (session->getProtocolVersion().value() >=
Frederick Mayledc07cf82022-05-26 20:30:12 +0000961 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000962 std::optional<Span<const uint8_t>> objectTableBytes =
963 parcelSpan.splitOff(transaction->parcelDataSize);
964 if (!objectTableBytes.has_value()) {
965 ALOGE("Parcel size (%" PRId32 ") greater than available bytes (%zu). Terminating!",
966 transaction->parcelDataSize, parcelSpan.byteSize());
967 (void)session->shutdownAndWait(false);
968 return BAD_VALUE;
969 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000970 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000971 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000972 if (!maybeSpan.has_value()) {
973 ALOGE("Bad object table size inferred from RpcWireTransaction. Saw bodySize=%zu "
974 "sizeofHeader=%zu parcelSize=%" PRId32
975 " objectTableBytesSize=%zu. Terminating!",
976 transactionData.size(), sizeof(RpcWireTransaction),
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000977 transaction->parcelDataSize, objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000978 return BAD_VALUE;
979 }
980 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000981 }
982
Steven Morelandeff77c12021-04-15 00:37:19 +0000983 Parcel data;
984 // transaction->data is owned by this function. Parcel borrows this data and
985 // only holds onto it for the duration of this function call. Parcel will be
986 // deleted before the 'transactionData' object.
Frederick Mayledc07cf82022-05-26 20:30:12 +0000987
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000988 replyStatus =
989 data.rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
990 objectTableSpan.data, objectTableSpan.size,
991 std::move(ancillaryFds), do_nothing_to_transact_data);
992 // Reset to avoid spurious use-after-move warning from clang-tidy.
993 ancillaryFds = std::remove_reference<decltype(ancillaryFds)>::type();
Steven Morelandeff77c12021-04-15 00:37:19 +0000994
Frederick Mayle69a0c992022-05-26 20:38:39 +0000995 if (replyStatus == OK) {
996 if (target) {
997 bool origAllowNested = connection->allowNested;
998 connection->allowNested = !oneway;
Steven Morelandc7d40132021-06-10 03:42:11 +0000999
Frederick Mayle69a0c992022-05-26 20:38:39 +00001000 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +00001001
Frederick Mayle69a0c992022-05-26 20:38:39 +00001002 connection->allowNested = origAllowNested;
1003 } else {
1004 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +00001005
Frederick Mayle69a0c992022-05-26 20:38:39 +00001006 switch (transaction->code) {
1007 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
1008 replyStatus = reply.writeInt32(session->getMaxIncomingThreads());
1009 break;
1010 }
1011 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
1012 // for client connections, this should always report the value
1013 // originally returned from the server, so this is asserting
1014 // that it exists
1015 replyStatus = reply.writeByteVector(session->mId);
1016 break;
1017 }
1018 default: {
1019 sp<RpcServer> server = session->server();
1020 if (server) {
1021 switch (transaction->code) {
1022 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
1023 sp<IBinder> root = session->mSessionSpecificRootObject
1024 ?: server->getRootObject();
1025 replyStatus = reply.writeStrongBinder(root);
1026 break;
1027 }
1028 default: {
1029 replyStatus = UNKNOWN_TRANSACTION;
1030 }
Steven Moreland103424e2021-06-02 18:16:19 +00001031 }
Frederick Mayle69a0c992022-05-26 20:38:39 +00001032 } else {
1033 ALOGE("Special command sent, but no server object attached.");
Steven Moreland103424e2021-06-02 18:16:19 +00001034 }
Steven Morelandf137de92021-04-24 01:54:26 +00001035 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001036 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001037 }
1038 }
1039 }
1040
Steven Morelandc7d40132021-06-10 03:42:11 +00001041 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001042 if (replyStatus != OK) {
1043 ALOGW("Oneway call failed with error: %d", replyStatus);
1044 }
1045
Steven Moreland5623d1a2021-09-10 15:45:34 -07001046 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
1047 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001048
1049 // Check to see if there is another asynchronous transaction to process.
1050 // This behavior differs from binder behavior, since in the binder
1051 // driver, asynchronous transactions will be processed after existing
1052 // pending binder transactions on the queue. The downside of this is
1053 // that asynchronous transactions can be drowned out by synchronous
1054 // transactions. However, we have no easy way to queue these
1055 // transactions after the synchronous transactions we may want to read
1056 // from the wire. So, in socket binder here, we have the opposite
1057 // downside: asynchronous transactions may drown out synchronous
1058 // transactions.
1059 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001060 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001061 auto it = mNodeForAddress.find(addr);
1062 // last refcount dropped after this transaction happened
1063 if (it == mNodeForAddress.end()) return OK;
1064
Steven Morelandc9d7b532021-06-04 20:57:41 +00001065 if (!nodeProgressAsyncNumber(&it->second)) {
1066 _l.unlock();
1067 (void)session->shutdownAndWait(false);
1068 return DEAD_OBJECT;
1069 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001070
Andrei Homescuae5f0d12023-02-25 05:03:31 +00001071 if (it->second.asyncTodo.size() != 0 &&
1072 it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001073 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
1074 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001075
1076 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +00001077 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +00001078 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +00001079 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
1080
Steven Morelandada72bd2021-06-09 23:29:13 +00001081 // reset up arguments
1082 transactionData = std::move(todo.data);
Frederick Mayleb0221d12022-10-03 23:10:53 +00001083 ancillaryFds = std::move(todo.ancillaryFds);
Steven Moreland3903bf02021-09-27 16:05:24 -07001084 LOG_ALWAYS_FATAL_IF(target != todo.ref,
1085 "async list should be associated with a binder");
Steven Morelandf5174272021-05-25 00:39:28 +00001086
Steven Moreland5553ac42020-11-11 02:14:45 +00001087 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +00001088 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +00001089 }
1090 }
Steven Morelandd8083312021-09-22 13:37:10 -07001091
1092 // done processing all the async commands on this binder that we can, so
1093 // write decstrongs on the binder
1094 if (addr != 0 && replyStatus == OK) {
1095 return flushExcessBinderRefs(session, addr, target);
1096 }
1097
Steven Moreland5553ac42020-11-11 02:14:45 +00001098 return OK;
1099 }
1100
Steven Moreland6709cf42021-09-30 15:21:54 -07001101 // Binder refs are flushed for oneway calls only after all calls which are
1102 // built up are executed. Otherwise, they fill up the binder buffer.
1103 if (addr != 0 && replyStatus == OK) {
1104 replyStatus = flushExcessBinderRefs(session, addr, target);
1105 }
1106
Frederick Mayle69a0c992022-05-26 20:38:39 +00001107 std::string errorMsg;
1108 if (status_t status = validateParcel(session, reply, &errorMsg); status != OK) {
1109 ALOGE("Reply Parcel failed validation: %s", errorMsg.c_str());
1110 // Forward the error to the client of the transaction.
1111 reply.freeData();
1112 reply.markForRpc(session);
1113 replyStatus = status;
1114 }
1115
1116 auto* rpcFields = reply.maybeRpcFields();
1117 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
1118
Frederick Mayledc07cf82022-05-26 20:30:12 +00001119 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
1120
Frederick Mayle69a0c992022-05-26 20:38:39 +00001121 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
1122 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +00001123
Frederick Mayle778c0902022-05-27 01:14:57 +00001124 uint32_t bodySize;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001125 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(rpcReplyWireSize, reply.dataSize(), &bodySize) ||
1126 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
1127 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +00001128 "Too much data for reply %zu", reply.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +00001129 RpcWireHeader cmdReply{
1130 .command = RPC_COMMAND_REPLY,
Frederick Mayle778c0902022-05-27 01:14:57 +00001131 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +00001132 };
Steven Moreland5553ac42020-11-11 02:14:45 +00001133 RpcWireReply rpcReply{
1134 .status = replyStatus,
Frederick Mayledc07cf82022-05-26 20:30:12 +00001135 // NOTE: Not necessarily written to socket depending on session
1136 // version.
1137 // NOTE: bodySize didn't overflow => this cast is safe
1138 .parcelDataSize = static_cast<uint32_t>(reply.dataSize()),
1139 .reserved = {0, 0, 0},
Steven Moreland5553ac42020-11-11 02:14:45 +00001140 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001141 iovec iovs[]{
1142 {&cmdReply, sizeof(RpcWireHeader)},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001143 {&rpcReply, rpcReplyWireSize},
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001144 {const_cast<uint8_t*>(reply.data()), reply.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001145 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001146 };
Tomasz Wasilczykdf07f942023-11-02 15:07:45 -07001147 return rpcSend(connection, session, "reply", iovs, countof(iovs), std::nullopt,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001148 rpcFields->mFds.get());
Steven Moreland5553ac42020-11-11 02:14:45 +00001149}
1150
Steven Moreland5ae62562021-06-10 03:21:42 +00001151status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
1152 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001153 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
1154
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001155 if (command.bodySize != sizeof(RpcDecStrong)) {
1156 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcDecStrong. Terminating!",
1157 sizeof(RpcDecStrong), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001158 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001159 return BAD_VALUE;
1160 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001161
Frederick Mayleb86cda42022-06-09 23:17:45 +00001162 RpcDecStrong body;
1163 iovec iov{&body, sizeof(RpcDecStrong)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001164 if (status_t status = rpcRec(connection, session, "dec ref body", &iov, 1, nullptr);
1165 status != OK)
Frederick Mayleb86cda42022-06-09 23:17:45 +00001166 return status;
1167
1168 uint64_t addr = RpcWireAddress::toRaw(body.address);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001169 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001170 auto it = mNodeForAddress.find(addr);
1171 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001172 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001173 return OK;
1174 }
1175
1176 sp<IBinder> target = it->second.binder.promote();
1177 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001178 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
1179 ". Terminating!",
1180 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001181 _l.unlock();
1182 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001183 return BAD_VALUE;
1184 }
1185
Frederick Mayleb86cda42022-06-09 23:17:45 +00001186 if (it->second.timesSent < body.amount) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001187 ALOGE("Record of sending binder %zu times, but requested decStrong for %" PRIu64 " of %u",
Frederick Mayleb86cda42022-06-09 23:17:45 +00001188 it->second.timesSent, addr, body.amount);
Steven Moreland5553ac42020-11-11 02:14:45 +00001189 return OK;
1190 }
1191
Steven Moreland5623d1a2021-09-10 15:45:34 -07001192 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
1193 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001194
Frederick Mayleb86cda42022-06-09 23:17:45 +00001195 LOG_RPC_DETAIL("Processing dec strong of %" PRIu64 " by %u from %zu", addr, body.amount,
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001196 it->second.timesSent);
1197
Frederick Mayleb86cda42022-06-09 23:17:45 +00001198 it->second.timesSent -= body.amount;
Steven Moreland67f85902023-03-15 01:13:49 +00001199 sp<IBinder> tempHold = tryEraseNode(session, std::move(_l), it);
1200 // LOCK ALREADY RELEASED
Steven Moreland31bde7a2021-06-04 00:57:36 +00001201 tempHold = nullptr; // destructor may make binder calls on this session
1202
1203 return OK;
1204}
1205
Frederick Mayle69a0c992022-05-26 20:38:39 +00001206status_t RpcState::validateParcel(const sp<RpcSession>& session, const Parcel& parcel,
1207 std::string* errorMsg) {
1208 auto* rpcFields = parcel.maybeRpcFields();
1209 if (rpcFields == nullptr) {
1210 *errorMsg = "Parcel not crafted for RPC call";
1211 return BAD_TYPE;
1212 }
1213
1214 if (rpcFields->mSession != session) {
1215 *errorMsg = "Parcel's session doesn't match";
1216 return BAD_TYPE;
1217 }
1218
1219 uint32_t protocolVersion = session->getProtocolVersion().value();
1220 if (protocolVersion < RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE &&
1221 !rpcFields->mObjectPositions.empty()) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +00001222 std::stringstream ss;
1223 ss << "Parcel has attached objects but the session's protocol version (" << protocolVersion
1224 << ") is too old, must be at least "
1225 << RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE;
1226 *errorMsg = ss.str();
Frederick Mayle69a0c992022-05-26 20:38:39 +00001227 return BAD_VALUE;
1228 }
1229
1230 if (rpcFields->mFds && !rpcFields->mFds->empty()) {
1231 switch (session->getFileDescriptorTransportMode()) {
1232 case RpcSession::FileDescriptorTransportMode::NONE:
1233 *errorMsg =
1234 "Parcel has file descriptors, but no file descriptor transport is enabled";
1235 return FDS_NOT_ALLOWED;
1236 case RpcSession::FileDescriptorTransportMode::UNIX: {
1237 constexpr size_t kMaxFdsPerMsg = 253;
1238 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +00001239 std::stringstream ss;
1240 ss << "Too many file descriptors in Parcel for unix domain socket: "
1241 << rpcFields->mFds->size() << " (max is " << kMaxFdsPerMsg << ")";
1242 *errorMsg = ss.str();
Frederick Mayle69a0c992022-05-26 20:38:39 +00001243 return BAD_VALUE;
1244 }
Andrei Homescu1c18a802022-08-17 04:59:01 +00001245 break;
1246 }
1247 case RpcSession::FileDescriptorTransportMode::TRUSTY: {
1248 // Keep this in sync with trusty_ipc.h!!!
1249 // We could import that file here on Trusty, but it's not
1250 // available on Android
1251 constexpr size_t kMaxFdsPerMsg = 8;
1252 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
Tomasz Wasilczyk3caae302023-10-12 20:57:02 +00001253 std::stringstream ss;
1254 ss << "Too many file descriptors in Parcel for Trusty IPC connection: "
1255 << rpcFields->mFds->size() << " (max is " << kMaxFdsPerMsg << ")";
1256 *errorMsg = ss.str();
Andrei Homescu1c18a802022-08-17 04:59:01 +00001257 return BAD_VALUE;
1258 }
1259 break;
Frederick Mayle69a0c992022-05-26 20:38:39 +00001260 }
1261 }
1262 }
1263
1264 return OK;
1265}
1266
Steven Moreland67f85902023-03-15 01:13:49 +00001267sp<IBinder> RpcState::tryEraseNode(const sp<RpcSession>& session, RpcMutexUniqueLock nodeLock,
1268 std::map<uint64_t, BinderNode>::iterator& it) {
1269 bool shouldShutdown = false;
1270
Steven Moreland31bde7a2021-06-04 00:57:36 +00001271 sp<IBinder> ref;
1272
Steven Moreland5553ac42020-11-11 02:14:45 +00001273 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001274 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +00001275
1276 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +00001277 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
1278 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +00001279 mNodeForAddress.erase(it);
Steven Moreland67f85902023-03-15 01:13:49 +00001280
1281 if (mNodeForAddress.size() == 0) {
1282 shouldShutdown = true;
1283 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001284 }
1285 }
1286
Steven Moreland67f85902023-03-15 01:13:49 +00001287 // If we shutdown, prevent RpcState from being re-used. This prevents another
1288 // thread from getting the root object again.
1289 if (shouldShutdown) {
1290 clear(std::move(nodeLock));
1291 } else {
1292 nodeLock.unlock(); // explicit
1293 }
1294 // LOCK IS RELEASED
1295
1296 if (shouldShutdown) {
1297 ALOGI("RpcState has no binders left, so triggering shutdown...");
1298 (void)session->shutdownAndWait(false);
1299 }
1300
Steven Moreland31bde7a2021-06-04 00:57:36 +00001301 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +00001302}
1303
Steven Morelandc9d7b532021-06-04 20:57:41 +00001304bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +00001305 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
1306 // a single binder
1307 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
1308 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +00001309 return false;
1310 }
1311 node->asyncNumber++;
1312 return true;
1313}
1314
Steven Moreland5553ac42020-11-11 02:14:45 +00001315} // namespace android