blob: bac2808b26b7a623a48d0d3302350759f56caf90 [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "RpcState"
18
19#include "RpcState.h"
20
Steven Moreland62129012021-07-29 12:14:44 -070021#include <android-base/hex.h>
Andrei Homescua39e4ed2021-12-10 08:41:54 +000022#include <android-base/macros.h>
Steven Morelandd7302072021-05-15 01:32:04 +000023#include <android-base/scopeguard.h>
Frederick Mayle69a0c992022-05-26 20:38:39 +000024#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000025#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000026#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000027#include <binder/RpcServer.h>
28
29#include "Debug.h"
30#include "RpcWireFormat.h"
Frederick Mayledc07cf82022-05-26 20:30:12 +000031#include "Utils.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000032
Steven Morelandb8176792021-06-22 20:29:21 +000033#include <random>
34
Steven Moreland5553ac42020-11-11 02:14:45 +000035#include <inttypes.h>
36
Steven Moreland09034a92023-05-31 20:49:11 +000037#ifdef __ANDROID__
38#include <cutils/properties.h>
39#endif
40
Steven Moreland5553ac42020-11-11 02:14:45 +000041namespace android {
42
Frederick Mayle69a0c992022-05-26 20:38:39 +000043using base::StringPrintf;
Steven Morelandd7302072021-05-15 01:32:04 +000044
Devin Moore08256432021-07-02 13:03:49 -070045#if RPC_FLAKE_PRONE
Steven Morelandb8176792021-06-22 20:29:21 +000046void rpcMaybeWaitToFlake() {
Devin Moore08256432021-07-02 13:03:49 -070047 [[clang::no_destroy]] static std::random_device r;
Steven Moreland7e2675c2022-09-28 23:34:52 +000048 [[clang::no_destroy]] static RpcMutex m;
Steven Morelandb8176792021-06-22 20:29:21 +000049 unsigned num;
50 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000051 RpcMutexLockGuard lock(m);
Steven Morelandb8176792021-06-22 20:29:21 +000052 num = r();
53 }
54 if (num % 10 == 0) usleep(num % 1000);
55}
56#endif
57
Frederick Mayle69a0c992022-05-26 20:38:39 +000058static bool enableAncillaryFds(RpcSession::FileDescriptorTransportMode mode) {
59 switch (mode) {
60 case RpcSession::FileDescriptorTransportMode::NONE:
61 return false;
62 case RpcSession::FileDescriptorTransportMode::UNIX:
Andrei Homescu1c18a802022-08-17 04:59:01 +000063 case RpcSession::FileDescriptorTransportMode::TRUSTY:
Frederick Mayle69a0c992022-05-26 20:38:39 +000064 return true;
65 }
Tomasz Wasilczyk7b5430b2023-06-28 14:04:51 -070066 LOG_ALWAYS_FATAL("Invalid FileDescriptorTransportMode: %d", static_cast<int>(mode));
Frederick Mayle69a0c992022-05-26 20:38:39 +000067}
68
Steven Moreland5553ac42020-11-11 02:14:45 +000069RpcState::RpcState() {}
70RpcState::~RpcState() {}
71
Steven Morelandbdb53ab2021-05-05 17:57:41 +000072status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5623d1a2021-09-10 15:45:34 -070073 uint64_t* outAddress) {
Steven Moreland5553ac42020-11-11 02:14:45 +000074 bool isRemote = binder->remoteBinder();
75 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
76
Steven Moreland99157622021-09-13 16:27:34 -070077 if (isRpc && binder->remoteBinder()->getPrivateAccessor().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000078 // We need to be able to send instructions over the socket for how to
79 // connect to a different server, and we also need to let the host
80 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000081 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000082 return INVALID_OPERATION;
83 }
84
85 if (isRemote && !isRpc) {
86 // Without additional work, this would have the effect of using this
87 // process to proxy calls from the socket over to the other process, and
88 // it would make those calls look like they come from us (not over the
89 // sockets). In order to make this work transparently like binder, we
90 // would instead need to send instructions over the socket for how to
91 // connect to the host process, and we also need to let the host process
92 // know this was happening.
93 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
94 return INVALID_OPERATION;
95 }
96
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000097 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000098 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +000099
100 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
101 // in RpcState
102 for (auto& [addr, node] : mNodeForAddress) {
103 if (binder == node.binder) {
104 if (isRpc) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700105 // check integrity of data structure
Steven Moreland99157622021-09-13 16:27:34 -0700106 uint64_t actualAddr = binder->remoteBinder()->getPrivateAccessor().rpcAddress();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700107 LOG_ALWAYS_FATAL_IF(addr != actualAddr, "Address mismatch %" PRIu64 " vs %" PRIu64,
108 addr, actualAddr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000109 }
110 node.timesSent++;
111 node.sentRef = binder; // might already be set
112 *outAddress = addr;
113 return OK;
114 }
115 }
116 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
117
Steven Moreland91538242021-06-10 23:35:35 +0000118 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +0000119
Steven Moreland5623d1a2021-09-10 15:45:34 -0700120 // arbitrary limit for maximum number of nodes in a process (otherwise we
121 // might run out of addresses)
122 if (mNodeForAddress.size() > 100000) {
123 return NO_MEMORY;
124 }
125
126 while (true) {
127 RpcWireAddress address{
128 .options = RPC_WIRE_ADDRESS_OPTION_CREATED,
129 .address = mNextId,
130 };
131 if (forServer) {
132 address.options |= RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
133 }
134
135 // avoid ubsan abort
136 if (mNextId >= std::numeric_limits<uint32_t>::max()) {
137 mNextId = 0;
138 } else {
139 mNextId++;
140 }
141
142 auto&& [it, inserted] = mNodeForAddress.insert({RpcWireAddress::toRaw(address),
Steven Moreland91538242021-06-10 23:35:35 +0000143 BinderNode{
144 .binder = binder,
Steven Moreland91538242021-06-10 23:35:35 +0000145 .sentRef = binder,
Andrei Homescu5a036f32022-03-08 22:54:40 +0000146 .timesSent = 1,
Steven Moreland91538242021-06-10 23:35:35 +0000147 }});
148 if (inserted) {
149 *outAddress = it->first;
150 return OK;
151 }
Steven Moreland91538242021-06-10 23:35:35 +0000152 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000153}
154
Steven Moreland5623d1a2021-09-10 15:45:34 -0700155status_t RpcState::onBinderEntering(const sp<RpcSession>& session, uint64_t address,
Steven Moreland7227c8a2021-06-02 00:24:32 +0000156 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000157 // ensure that: if we want to use addresses for something else in the future (for
158 // instance, allowing transitive binder sends), that we don't accidentally
159 // send those addresses to old server. Accidentally ignoring this in that
160 // case and considering the binder to be recognized could cause this
161 // process to accidentally proxy transactions for that binder. Of course,
162 // if we communicate with a binder, it could always be proxying
163 // information. However, we want to make sure that isn't done on accident
164 // by a client.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700165 RpcWireAddress addr = RpcWireAddress::fromRaw(address);
166 constexpr uint32_t kKnownOptions =
167 RPC_WIRE_ADDRESS_OPTION_CREATED | RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
168 if (addr.options & ~kKnownOptions) {
169 ALOGE("Address is of an unknown type, rejecting: %" PRIu64, address);
Steven Moreland91538242021-06-10 23:35:35 +0000170 return BAD_VALUE;
171 }
172
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000173 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000174 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000175
176 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000177 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000178
179 // implicitly have strong RPC refcount, since we received this binder
180 it->second.timesRecd++;
Steven Morelandd8083312021-09-22 13:37:10 -0700181 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000182 }
183
Steven Moreland91538242021-06-10 23:35:35 +0000184 // we don't know about this binder, so the other side of the connection
185 // should have created it.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700186 if ((addr.options & RPC_WIRE_ADDRESS_OPTION_FOR_SERVER) == !!session->server()) {
187 ALOGE("Server received unrecognized address which we should own the creation of %" PRIu64,
188 address);
Steven Moreland91538242021-06-10 23:35:35 +0000189 return BAD_VALUE;
190 }
191
Steven Moreland5553ac42020-11-11 02:14:45 +0000192 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
193 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
194
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000195 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000196 // device global binders in the RPC world).
Steven Moreland99157622021-09-13 16:27:34 -0700197 it->second.binder = *out = BpBinder::PrivateAccessor::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000198 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000199 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000200}
201
Steven Morelandd8083312021-09-22 13:37:10 -0700202status_t RpcState::flushExcessBinderRefs(const sp<RpcSession>& session, uint64_t address,
203 const sp<IBinder>& binder) {
Steven Morelande96ed0e2021-09-27 17:43:53 -0700204 // We can flush all references when the binder is destroyed. No need to send
205 // extra reference counting packets now.
206 if (binder->remoteBinder()) return OK;
207
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000208 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandd8083312021-09-22 13:37:10 -0700209 if (mTerminated) return DEAD_OBJECT;
210
211 auto it = mNodeForAddress.find(address);
212
213 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Can't be deleted while we hold sp<>");
214 LOG_ALWAYS_FATAL_IF(it->second.binder != binder,
215 "Caller of flushExcessBinderRefs using inconsistent arguments");
216
Steven Morelande96ed0e2021-09-27 17:43:53 -0700217 LOG_ALWAYS_FATAL_IF(it->second.timesSent <= 0, "Local binder must have been sent %p",
218 binder.get());
Steven Morelandd8083312021-09-22 13:37:10 -0700219
Steven Morelande96ed0e2021-09-27 17:43:53 -0700220 // For a local binder, we only need to know that we sent it. Now that we
221 // have an sp<> for this call, we don't need anything more. If the other
222 // process is done with this binder, it needs to know we received the
223 // refcount associated with this call, so we can acknowledge that we
224 // received it. Once (or if) it has no other refcounts, it would reply with
225 // its own decStrong so that it could be removed from this session.
226 if (it->second.timesRecd != 0) {
Steven Morelandd8083312021-09-22 13:37:10 -0700227 _l.unlock();
228
Steven Morelande96ed0e2021-09-27 17:43:53 -0700229 return session->sendDecStrongToTarget(address, 0);
Steven Morelandd8083312021-09-22 13:37:10 -0700230 }
231
232 return OK;
233}
234
Devin Moore66d5b7a2022-07-07 21:42:10 +0000235status_t RpcState::sendObituaries(const sp<RpcSession>& session) {
236 RpcMutexUniqueLock _l(mNodeMutex);
237
238 // Gather strong pointers to all of the remote binders for this session so
239 // we hold the strong references. remoteBinder() returns a raw pointer.
240 // Send the obituaries and drop the strong pointers outside of the lock so
241 // the destructors and the onBinderDied calls are not done while locked.
242 std::vector<sp<IBinder>> remoteBinders;
243 for (const auto& [_, binderNode] : mNodeForAddress) {
244 if (auto binder = binderNode.binder.promote()) {
245 remoteBinders.push_back(std::move(binder));
246 }
247 }
248 _l.unlock();
249
250 for (const auto& binder : remoteBinders) {
251 if (binder->remoteBinder() &&
252 binder->remoteBinder()->getPrivateAccessor().rpcSession() == session) {
253 binder->remoteBinder()->sendObituary();
254 }
255 }
256 return OK;
257}
258
Steven Moreland5553ac42020-11-11 02:14:45 +0000259size_t RpcState::countBinders() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000260 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000261 return mNodeForAddress.size();
262}
263
264void RpcState::dump() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000265 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000266 dumpLocked();
267}
268
Steven Morelandc9d7b532021-06-04 20:57:41 +0000269void RpcState::clear() {
Steven Moreland67f85902023-03-15 01:13:49 +0000270 return clear(RpcMutexUniqueLock(mNodeMutex));
271}
Steven Morelandc9d7b532021-06-04 20:57:41 +0000272
Steven Moreland67f85902023-03-15 01:13:49 +0000273void RpcState::clear(RpcMutexUniqueLock nodeLock) {
Steven Morelandc9d7b532021-06-04 20:57:41 +0000274 if (mTerminated) {
275 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
276 "New state should be impossible after terminating!");
277 return;
278 }
Steven Moreland0092fe32022-07-15 00:15:34 +0000279 mTerminated = true;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000280
281 if (SHOULD_LOG_RPC_DETAIL) {
282 ALOGE("RpcState::clear()");
283 dumpLocked();
284 }
285
Steven Moreland0092fe32022-07-15 00:15:34 +0000286 // invariants
Steven Morelandc9d7b532021-06-04 20:57:41 +0000287 for (auto& [address, node] : mNodeForAddress) {
Steven Moreland0092fe32022-07-15 00:15:34 +0000288 bool guaranteedHaveBinder = node.timesSent > 0;
289 if (guaranteedHaveBinder) {
290 LOG_ALWAYS_FATAL_IF(node.sentRef == nullptr,
291 "Binder expected to be owned with address: %" PRIu64 " %s", address,
292 node.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000293 }
294 }
295
Steven Moreland0092fe32022-07-15 00:15:34 +0000296 // if the destructor of a binder object makes another RPC call, then calling
297 // decStrong could deadlock. So, we must hold onto these binders until
298 // mNodeMutex is no longer taken.
299 auto temp = std::move(mNodeForAddress);
300 mNodeForAddress.clear(); // RpcState isn't reusable, but for future/explicit
Steven Morelandc9d7b532021-06-04 20:57:41 +0000301
Steven Moreland67f85902023-03-15 01:13:49 +0000302 nodeLock.unlock();
Steven Moreland0092fe32022-07-15 00:15:34 +0000303 temp.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000304}
305
306void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000307 ALOGE("DUMP OF RpcState %p", this);
308 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
309 for (const auto& [address, node] : mNodeForAddress) {
Steven Moreland3fa32922022-07-14 18:45:51 +0000310 ALOGE("- address: %" PRIu64 " %s", address, node.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000311 }
312 ALOGE("END DUMP OF RpcState");
313}
314
Steven Moreland3fa32922022-07-14 18:45:51 +0000315std::string RpcState::BinderNode::toString() const {
316 sp<IBinder> strongBinder = this->binder.promote();
317
318 const char* desc;
319 if (strongBinder) {
320 if (strongBinder->remoteBinder()) {
321 if (strongBinder->remoteBinder()->isRpcBinder()) {
322 desc = "(rpc binder proxy)";
323 } else {
324 desc = "(binder proxy)";
325 }
326 } else {
327 desc = "(local binder)";
328 }
329 } else {
330 desc = "(not promotable)";
331 }
332
333 return StringPrintf("node{%p times sent: %zu times recd: %zu type: %s}",
334 this->binder.unsafe_get(), this->timesSent, this->timesRecd, desc);
335}
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(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000366 android::base::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(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000401 android::base::HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
402 }
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")) {
412 ALOGE("Cannot use experimental RPC binder protocol on a release branch.");
413 return false;
414 }
415#else
416 // don't restrict on other platforms, though experimental should
417 // only really be used for testing, we don't have a good way to see
418 // what is shipping outside of Android
419#endif
420 } else if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT) {
Steven Morelandca3f6382023-05-11 23:23:26 +0000421 ALOGE("Cannot use RPC binder protocol version %u which is unknown (current protocol "
422 "version "
423 "is %u).",
424 version, RPC_WIRE_PROTOCOL_VERSION);
425 return false;
426 }
Steven Moreland09034a92023-05-31 20:49:11 +0000427
Steven Morelandca3f6382023-05-11 23:23:26 +0000428 return true;
429}
430
Steven Morelandbf57bce2021-07-26 15:26:12 -0700431status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
432 const sp<RpcSession>& session, uint32_t* version) {
433 RpcNewSessionResponse response;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000434 iovec iov{&response, sizeof(response)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000435 if (status_t status = rpcRec(connection, session, "new session response", &iov, 1, nullptr);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700436 status != OK) {
437 return status;
438 }
439 *version = response.version;
440 return OK;
441}
442
Steven Moreland5ae62562021-06-10 03:21:42 +0000443status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
444 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000445 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000446 .msg = RPC_CONNECTION_INIT_OKAY,
447 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000448 iovec iov{&init, sizeof(init)};
Devin Moore695368f2022-06-03 22:29:14 +0000449 return rpcSend(connection, session, "connection init", &iov, 1, std::nullopt);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000450}
451
Steven Moreland5ae62562021-06-10 03:21:42 +0000452status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
453 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000454 RpcOutgoingConnectionInit init;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000455 iovec iov{&init, sizeof(init)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000456 if (status_t status = rpcRec(connection, session, "connection init", &iov, 1, nullptr);
457 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000458 return status;
459
460 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
461 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
462 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
463 init.msg);
464 return BAD_VALUE;
465 }
466 return OK;
467}
468
Steven Moreland5ae62562021-06-10 03:21:42 +0000469sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
470 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000471 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000472 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000473 Parcel reply;
474
Steven Moreland5623d1a2021-09-10 15:45:34 -0700475 status_t status =
476 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000477 if (status != OK) {
478 ALOGE("Error getting root object: %s", statusToString(status).c_str());
479 return nullptr;
480 }
481
482 return reply.readStrongBinder();
483}
484
Steven Moreland5ae62562021-06-10 03:21:42 +0000485status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
486 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000487 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000488 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000489 Parcel reply;
490
Steven Moreland5623d1a2021-09-10 15:45:34 -0700491 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
492 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000493 if (status != OK) {
494 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
495 return status;
496 }
497
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000498 int32_t maxThreads;
499 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000500 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000501 if (maxThreads <= 0) {
502 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000503 return BAD_VALUE;
504 }
505
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000506 *maxThreadsOut = maxThreads;
507 return OK;
508}
509
Steven Moreland5ae62562021-06-10 03:21:42 +0000510status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700511 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000512 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000513 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000514 Parcel reply;
515
Steven Moreland5623d1a2021-09-10 15:45:34 -0700516 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
517 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000518 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000519 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000520 return status;
521 }
522
Steven Moreland826367f2021-09-10 14:05:31 -0700523 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000524}
525
Steven Moreland5ae62562021-06-10 03:21:42 +0000526status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
527 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
528 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000529 std::string errorMsg;
530 if (status_t status = validateParcel(session, data, &errorMsg); status != OK) {
531 ALOGE("Refusing to send RPC on binder %p code %" PRIu32 ": Parcel %p failed validation: %s",
532 binder.get(), code, &data, errorMsg.c_str());
533 return status;
Steven Morelandf5174272021-05-25 00:39:28 +0000534 }
Steven Moreland5623d1a2021-09-10 15:45:34 -0700535 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000536 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
537
Steven Moreland5ae62562021-06-10 03:21:42 +0000538 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000539}
540
Steven Moreland5ae62562021-06-10 03:21:42 +0000541status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700542 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000543 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000544 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
545 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
546
Steven Moreland5553ac42020-11-11 02:14:45 +0000547 uint64_t asyncNumber = 0;
548
Steven Moreland5623d1a2021-09-10 15:45:34 -0700549 if (address != 0) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000550 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000551 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
552 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700553 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
554 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000555
556 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000557 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000558 if (!nodeProgressAsyncNumber(&it->second)) {
559 _l.unlock();
560 (void)session->shutdownAndWait(false);
561 return DEAD_OBJECT;
562 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000563 }
564 }
565
Frederick Mayle69a0c992022-05-26 20:38:39 +0000566 auto* rpcFields = data.maybeRpcFields();
567 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
568
569 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
570 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +0000571
Frederick Mayle778c0902022-05-27 01:14:57 +0000572 uint32_t bodySize;
573 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(sizeof(RpcWireTransaction), data.dataSize(),
Frederick Mayledc07cf82022-05-26 20:30:12 +0000574 &bodySize) ||
575 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
576 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +0000577 "Too much data %zu", data.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +0000578 RpcWireHeader command{
579 .command = RPC_COMMAND_TRANSACT,
Frederick Mayle778c0902022-05-27 01:14:57 +0000580 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +0000581 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700582
Steven Moreland5553ac42020-11-11 02:14:45 +0000583 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700584 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000585 .code = code,
586 .flags = flags,
587 .asyncNumber = asyncNumber,
Frederick Mayledc07cf82022-05-26 20:30:12 +0000588 // bodySize didn't overflow => this cast is safe
589 .parcelDataSize = static_cast<uint32_t>(data.dataSize()),
Steven Moreland5553ac42020-11-11 02:14:45 +0000590 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000591
Steven Moreland43921d52021-09-27 17:15:56 -0700592 // Oneway calls have no sync point, so if many are sent before, whether this
593 // is a twoway or oneway transaction, they may have filled up the socket.
Devin Moore695368f2022-06-03 22:29:14 +0000594 // So, make sure we drain them before polling
Steven Morelandda31af62023-02-25 01:55:58 +0000595 constexpr size_t kWaitMaxUs = 1000000;
596 constexpr size_t kWaitLogUs = 10000;
597 size_t waitUs = 0;
Steven Moreland43921d52021-09-27 17:15:56 -0700598
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000599 iovec iovs[]{
600 {&command, sizeof(RpcWireHeader)},
601 {&transaction, sizeof(RpcWireTransaction)},
602 {const_cast<uint8_t*>(data.data()), data.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +0000603 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000604 };
Frederick Mayle69a0c992022-05-26 20:38:39 +0000605 if (status_t status = rpcSend(
606 connection, session, "transaction", iovs, arraysize(iovs),
607 [&] {
608 if (waitUs > kWaitLogUs) {
609 ALOGE("Cannot send command, trying to process pending refcounts. Waiting "
610 "%zuus. Too many oneway calls?",
611 waitUs);
612 }
Devin Moore695368f2022-06-03 22:29:14 +0000613
Frederick Mayle69a0c992022-05-26 20:38:39 +0000614 if (waitUs > 0) {
615 usleep(waitUs);
616 waitUs = std::min(kWaitMaxUs, waitUs * 2);
617 } else {
618 waitUs = 1;
619 }
Devin Moore695368f2022-06-03 22:29:14 +0000620
Frederick Mayle69a0c992022-05-26 20:38:39 +0000621 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
622 },
623 rpcFields->mFds.get());
Steven Moreland43921d52021-09-27 17:15:56 -0700624 status != OK) {
Steven Morelandda31af62023-02-25 01:55:58 +0000625 // rpcSend calls shutdownAndWait, so all refcounts should be reset. If we ever tolerate
626 // errors here, then we may need to undo the binder-sent counts for the transaction as
627 // well as for the binder objects in the Parcel
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000628 return status;
Steven Moreland43921d52021-09-27 17:15:56 -0700629 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000630
631 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700632 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
633 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000634
635 // Do not wait on result.
Steven Moreland43921d52021-09-27 17:15:56 -0700636 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000637 }
638
639 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
640
Steven Moreland5ae62562021-06-10 03:21:42 +0000641 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000642}
643
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000644static void cleanup_reply_data(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
645 size_t objectsCount) {
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000646 delete[] const_cast<uint8_t*>(data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000647 (void)dataSize;
648 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000649 (void)objectsCount;
Steven Moreland5553ac42020-11-11 02:14:45 +0000650}
651
Steven Moreland5ae62562021-06-10 03:21:42 +0000652status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
653 const sp<RpcSession>& session, Parcel* reply) {
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000654 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000655 RpcWireHeader command;
656 while (true) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000657 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000658 if (status_t status = rpcRec(connection, session, "command header (for reply)", &iov, 1,
659 enableAncillaryFds(session->getFileDescriptorTransportMode())
660 ? &ancillaryFds
661 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000662 status != OK)
663 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000664
665 if (command.command == RPC_COMMAND_REPLY) break;
666
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000667 if (status_t status = processCommand(connection, session, command, CommandType::ANY,
668 std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000669 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000670 return status;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000671
672 // Reset to avoid spurious use-after-move warning from clang-tidy.
673 ancillaryFds = decltype(ancillaryFds)();
Steven Moreland5553ac42020-11-11 02:14:45 +0000674 }
675
Frederick Mayledc07cf82022-05-26 20:30:12 +0000676 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
677
678 if (command.bodySize < rpcReplyWireSize) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000679 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
680 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000681 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000682 return BAD_VALUE;
683 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000684
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000685 RpcWireReply rpcReply;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000686 memset(&rpcReply, 0, sizeof(RpcWireReply)); // zero because of potential short read
687
688 CommandData data(command.bodySize - rpcReplyWireSize);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000689 if (!data.valid()) return NO_MEMORY;
690
691 iovec iovs[]{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000692 {&rpcReply, rpcReplyWireSize},
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000693 {data.data(), data.size()},
694 };
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000695 if (status_t status = rpcRec(connection, session, "reply body", iovs, arraysize(iovs), nullptr);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000696 status != OK)
697 return status;
Frederick Mayle69a0c992022-05-26 20:38:39 +0000698
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000699 if (rpcReply.status != OK) return rpcReply.status;
700
Frederick Mayledc07cf82022-05-26 20:30:12 +0000701 Span<const uint8_t> parcelSpan = {data.data(), data.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000702 Span<const uint32_t> objectTableSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000703 if (session->getProtocolVersion().value() >=
704 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000705 std::optional<Span<const uint8_t>> objectTableBytes =
706 parcelSpan.splitOff(rpcReply.parcelDataSize);
707 if (!objectTableBytes.has_value()) {
708 ALOGE("Parcel size larger than available bytes: %" PRId32 " vs %zu. Terminating!",
709 rpcReply.parcelDataSize, parcelSpan.byteSize());
710 (void)session->shutdownAndWait(false);
711 return BAD_VALUE;
712 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000713 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000714 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000715 if (!maybeSpan.has_value()) {
716 ALOGE("Bad object table size inferred from RpcWireReply. Saw bodySize=%" PRId32
717 " sizeofHeader=%zu parcelSize=%" PRId32 " objectTableBytesSize=%zu. Terminating!",
718 command.bodySize, rpcReplyWireSize, rpcReply.parcelDataSize,
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000719 objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000720 return BAD_VALUE;
721 }
722 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000723 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000724
Frederick Mayledc07cf82022-05-26 20:30:12 +0000725 data.release();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000726 return reply->rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
727 objectTableSpan.data, objectTableSpan.size,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000728 std::move(ancillaryFds), cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000729}
730
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000731status_t RpcState::sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection,
732 const sp<RpcSession>& session, uint64_t addr,
733 size_t target) {
734 RpcDecStrong body = {
735 .address = RpcWireAddress::fromRaw(addr),
736 };
737
Steven Moreland5553ac42020-11-11 02:14:45 +0000738 {
Steven Moreland67f85902023-03-15 01:13:49 +0000739 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000740 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
741 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700742 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
743 "Sending dec strong on unknown address %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000744
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000745 LOG_ALWAYS_FATAL_IF(it->second.timesRecd < target, "Can't dec count of %zu to %zu.",
746 it->second.timesRecd, target);
747
748 // typically this happens when multiple threads send dec refs at the
749 // same time - the transactions will get combined automatically
750 if (it->second.timesRecd == target) return OK;
751
752 body.amount = it->second.timesRecd - target;
753 it->second.timesRecd = target;
754
Steven Moreland67f85902023-03-15 01:13:49 +0000755 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(session, std::move(_l), it),
Steven Moreland31bde7a2021-06-04 00:57:36 +0000756 "Bad state. RpcState shouldn't own received binder");
Steven Moreland67f85902023-03-15 01:13:49 +0000757 // LOCK ALREADY RELEASED
Steven Moreland5553ac42020-11-11 02:14:45 +0000758 }
759
760 RpcWireHeader cmd = {
761 .command = RPC_COMMAND_DEC_STRONG,
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000762 .bodySize = sizeof(RpcDecStrong),
Steven Moreland5553ac42020-11-11 02:14:45 +0000763 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000764 iovec iovs[]{{&cmd, sizeof(cmd)}, {&body, sizeof(body)}};
Devin Moore695368f2022-06-03 22:29:14 +0000765 return rpcSend(connection, session, "dec ref", iovs, arraysize(iovs), std::nullopt);
Steven Moreland5553ac42020-11-11 02:14:45 +0000766}
767
Steven Moreland5ae62562021-06-10 03:21:42 +0000768status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
769 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700770 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000771
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000772 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000773 RpcWireHeader command;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000774 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000775 if (status_t status =
776 rpcRec(connection, session, "command header (for server)", &iov, 1,
777 enableAncillaryFds(session->getFileDescriptorTransportMode()) ? &ancillaryFds
778 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000779 status != OK)
780 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000781
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000782 return processCommand(connection, session, command, type, std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000783}
784
Steven Moreland5ae62562021-06-10 03:21:42 +0000785status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
786 const sp<RpcSession>& session, CommandType type) {
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000787 while (true) {
Andrei Homescu1975aaa2022-03-19 02:34:57 +0000788 status_t status = connection->rpcTransport->pollRead();
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000789 if (status == WOULD_BLOCK) break;
790 if (status != OK) return status;
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000791
792 status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000793 if (status != OK) return status;
794 }
795 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000796}
797
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000798status_t RpcState::processCommand(
799 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
800 const RpcWireHeader& command, CommandType type,
801 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland32150282021-11-12 22:54:53 +0000802#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000803 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
804 IPCThreadState::SpGuard spGuard{
805 .address = __builtin_frame_address(0),
Steven Morelande42ffd02022-07-06 21:46:23 +0000806 .context = "processing binder RPC command (where RpcServer::setPerSessionRootObject is "
807 "used to distinguish callers)",
Steven Morelandd7302072021-05-15 01:32:04 +0000808 };
809 const IPCThreadState::SpGuard* origGuard;
810 if (kernelBinderState != nullptr) {
811 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
812 }
Steven Moreland32150282021-11-12 22:54:53 +0000813
814 base::ScopeGuard guardUnguard = [&]() {
Steven Morelandd7302072021-05-15 01:32:04 +0000815 if (kernelBinderState != nullptr) {
816 kernelBinderState->restoreGetCallingSpGuard(origGuard);
817 }
818 };
Steven Moreland32150282021-11-12 22:54:53 +0000819#endif // BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000820
Steven Moreland5553ac42020-11-11 02:14:45 +0000821 switch (command.command) {
822 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000823 if (type != CommandType::ANY) return BAD_TYPE;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000824 return processTransact(connection, session, command, std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000825 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000826 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000827 }
828
829 // We should always know the version of the opposing side, and since the
830 // RPC-binder-level wire protocol is not self synchronizing, we have no way
831 // to understand where the current command ends and the next one begins. We
832 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000833 // to kill us, so ending the session for misbehaving client.
834 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000835 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000836 return DEAD_OBJECT;
837}
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000838status_t RpcState::processTransact(
839 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
840 const RpcWireHeader& command,
841 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000842 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
843
Steven Morelanddbe71832021-05-12 23:31:00 +0000844 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000845 if (!transactionData.valid()) {
846 return NO_MEMORY;
847 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000848 iovec iov{transactionData.data(), transactionData.size()};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000849 if (status_t status = rpcRec(connection, session, "transaction body", &iov, 1, nullptr);
850 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000851 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000852
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000853 return processTransactInternal(connection, session, std::move(transactionData),
854 std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000855}
856
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000857static void do_nothing_to_transact_data(const uint8_t* data, size_t dataSize,
Steven Moreland438cce82021-04-02 18:04:08 +0000858 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland438cce82021-04-02 18:04:08 +0000859 (void)data;
860 (void)dataSize;
861 (void)objects;
862 (void)objectsCount;
863}
864
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000865status_t RpcState::processTransactInternal(
866 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
867 CommandData transactionData,
868 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Morelandada72bd2021-06-09 23:29:13 +0000869 // for 'recursive' calls to this, we have already read and processed the
870 // binder from the transaction data and taken reference counts into account,
871 // so it is cached here.
Steven Moreland3903bf02021-09-27 16:05:24 -0700872 sp<IBinder> target;
Steven Morelandada72bd2021-06-09 23:29:13 +0000873processTransactInternalTailCall:
874
Steven Moreland5553ac42020-11-11 02:14:45 +0000875 if (transactionData.size() < sizeof(RpcWireTransaction)) {
876 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
877 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000878 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000879 return BAD_VALUE;
880 }
881 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
882
Steven Moreland5623d1a2021-09-10 15:45:34 -0700883 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000884 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000885
886 status_t replyStatus = OK;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700887 if (addr != 0) {
Steven Moreland3903bf02021-09-27 16:05:24 -0700888 if (!target) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000889 replyStatus = onBinderEntering(session, addr, &target);
Steven Morelandf5174272021-05-25 00:39:28 +0000890 }
891
Steven Moreland7227c8a2021-06-02 00:24:32 +0000892 if (replyStatus != OK) {
893 // do nothing
894 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000895 // This can happen if the binder is remote in this process, and
896 // another thread has called the last decStrong on this binder.
897 // However, for local binders, it indicates a misbehaving client
898 // (any binder which is being transacted on should be holding a
899 // strong ref count), so in either case, terminating the
900 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700901 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
902 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000903 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000904 replyStatus = BAD_VALUE;
905 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700906 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
907 ". Terminating!",
908 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000909 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000910 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000911 } else if (oneway) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000912 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000913 auto it = mNodeForAddress.find(addr);
914 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700915 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000916 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000917 } else if (transaction->asyncNumber != it->second.asyncNumber) {
918 // we need to process some other asynchronous transaction
919 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000920 it->second.asyncTodo.push(BinderNode::AsyncTodo{
921 .ref = target,
922 .data = std::move(transactionData),
Frederick Mayleb0221d12022-10-03 23:10:53 +0000923 .ancillaryFds = std::move(ancillaryFds),
Steven Morelandf5174272021-05-25 00:39:28 +0000924 .asyncNumber = transaction->asyncNumber,
925 });
Steven Morelandd45be622021-06-04 02:19:37 +0000926
927 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700928 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
929 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000930
931 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
932 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
933 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
934
935 if (numPending >= kArbitraryOnewayCallWarnLevel) {
936 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
937 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
938 _l.unlock();
939 (void)session->shutdownAndWait(false);
940 return FAILED_TRANSACTION;
941 }
942
943 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
944 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
945 target.get(), numPending);
946 }
947 }
Steven Morelandf5174272021-05-25 00:39:28 +0000948 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000949 }
950 }
951 }
952
Steven Moreland5553ac42020-11-11 02:14:45 +0000953 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000954 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000955
956 if (replyStatus == OK) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000957 Span<const uint8_t> parcelSpan = {transaction->data,
958 transactionData.size() -
959 offsetof(RpcWireTransaction, data)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000960 Span<const uint32_t> objectTableSpan;
Steven Moreland28c87282023-04-14 21:03:01 +0000961 if (session->getProtocolVersion().value() >=
Frederick Mayledc07cf82022-05-26 20:30:12 +0000962 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000963 std::optional<Span<const uint8_t>> objectTableBytes =
964 parcelSpan.splitOff(transaction->parcelDataSize);
965 if (!objectTableBytes.has_value()) {
966 ALOGE("Parcel size (%" PRId32 ") greater than available bytes (%zu). Terminating!",
967 transaction->parcelDataSize, parcelSpan.byteSize());
968 (void)session->shutdownAndWait(false);
969 return BAD_VALUE;
970 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000971 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000972 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000973 if (!maybeSpan.has_value()) {
974 ALOGE("Bad object table size inferred from RpcWireTransaction. Saw bodySize=%zu "
975 "sizeofHeader=%zu parcelSize=%" PRId32
976 " objectTableBytesSize=%zu. Terminating!",
977 transactionData.size(), sizeof(RpcWireTransaction),
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000978 transaction->parcelDataSize, objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000979 return BAD_VALUE;
980 }
981 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000982 }
983
Steven Morelandeff77c12021-04-15 00:37:19 +0000984 Parcel data;
985 // transaction->data is owned by this function. Parcel borrows this data and
986 // only holds onto it for the duration of this function call. Parcel will be
987 // deleted before the 'transactionData' object.
Frederick Mayledc07cf82022-05-26 20:30:12 +0000988
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000989 replyStatus =
990 data.rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
991 objectTableSpan.data, objectTableSpan.size,
992 std::move(ancillaryFds), do_nothing_to_transact_data);
993 // Reset to avoid spurious use-after-move warning from clang-tidy.
994 ancillaryFds = std::remove_reference<decltype(ancillaryFds)>::type();
Steven Morelandeff77c12021-04-15 00:37:19 +0000995
Frederick Mayle69a0c992022-05-26 20:38:39 +0000996 if (replyStatus == OK) {
997 if (target) {
998 bool origAllowNested = connection->allowNested;
999 connection->allowNested = !oneway;
Steven Morelandc7d40132021-06-10 03:42:11 +00001000
Frederick Mayle69a0c992022-05-26 20:38:39 +00001001 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +00001002
Frederick Mayle69a0c992022-05-26 20:38:39 +00001003 connection->allowNested = origAllowNested;
1004 } else {
1005 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +00001006
Frederick Mayle69a0c992022-05-26 20:38:39 +00001007 switch (transaction->code) {
1008 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
1009 replyStatus = reply.writeInt32(session->getMaxIncomingThreads());
1010 break;
1011 }
1012 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
1013 // for client connections, this should always report the value
1014 // originally returned from the server, so this is asserting
1015 // that it exists
1016 replyStatus = reply.writeByteVector(session->mId);
1017 break;
1018 }
1019 default: {
1020 sp<RpcServer> server = session->server();
1021 if (server) {
1022 switch (transaction->code) {
1023 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
1024 sp<IBinder> root = session->mSessionSpecificRootObject
1025 ?: server->getRootObject();
1026 replyStatus = reply.writeStrongBinder(root);
1027 break;
1028 }
1029 default: {
1030 replyStatus = UNKNOWN_TRANSACTION;
1031 }
Steven Moreland103424e2021-06-02 18:16:19 +00001032 }
Frederick Mayle69a0c992022-05-26 20:38:39 +00001033 } else {
1034 ALOGE("Special command sent, but no server object attached.");
Steven Moreland103424e2021-06-02 18:16:19 +00001035 }
Steven Morelandf137de92021-04-24 01:54:26 +00001036 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001037 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001038 }
1039 }
1040 }
1041
Steven Morelandc7d40132021-06-10 03:42:11 +00001042 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001043 if (replyStatus != OK) {
1044 ALOGW("Oneway call failed with error: %d", replyStatus);
1045 }
1046
Steven Moreland5623d1a2021-09-10 15:45:34 -07001047 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
1048 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001049
1050 // Check to see if there is another asynchronous transaction to process.
1051 // This behavior differs from binder behavior, since in the binder
1052 // driver, asynchronous transactions will be processed after existing
1053 // pending binder transactions on the queue. The downside of this is
1054 // that asynchronous transactions can be drowned out by synchronous
1055 // transactions. However, we have no easy way to queue these
1056 // transactions after the synchronous transactions we may want to read
1057 // from the wire. So, in socket binder here, we have the opposite
1058 // downside: asynchronous transactions may drown out synchronous
1059 // transactions.
1060 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001061 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001062 auto it = mNodeForAddress.find(addr);
1063 // last refcount dropped after this transaction happened
1064 if (it == mNodeForAddress.end()) return OK;
1065
Steven Morelandc9d7b532021-06-04 20:57:41 +00001066 if (!nodeProgressAsyncNumber(&it->second)) {
1067 _l.unlock();
1068 (void)session->shutdownAndWait(false);
1069 return DEAD_OBJECT;
1070 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001071
Andrei Homescuae5f0d12023-02-25 05:03:31 +00001072 if (it->second.asyncTodo.size() != 0 &&
1073 it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001074 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
1075 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001076
1077 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +00001078 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +00001079 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +00001080 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
1081
Steven Morelandada72bd2021-06-09 23:29:13 +00001082 // reset up arguments
1083 transactionData = std::move(todo.data);
Frederick Mayleb0221d12022-10-03 23:10:53 +00001084 ancillaryFds = std::move(todo.ancillaryFds);
Steven Moreland3903bf02021-09-27 16:05:24 -07001085 LOG_ALWAYS_FATAL_IF(target != todo.ref,
1086 "async list should be associated with a binder");
Steven Morelandf5174272021-05-25 00:39:28 +00001087
Steven Moreland5553ac42020-11-11 02:14:45 +00001088 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +00001089 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +00001090 }
1091 }
Steven Morelandd8083312021-09-22 13:37:10 -07001092
1093 // done processing all the async commands on this binder that we can, so
1094 // write decstrongs on the binder
1095 if (addr != 0 && replyStatus == OK) {
1096 return flushExcessBinderRefs(session, addr, target);
1097 }
1098
Steven Moreland5553ac42020-11-11 02:14:45 +00001099 return OK;
1100 }
1101
Steven Moreland6709cf42021-09-30 15:21:54 -07001102 // Binder refs are flushed for oneway calls only after all calls which are
1103 // built up are executed. Otherwise, they fill up the binder buffer.
1104 if (addr != 0 && replyStatus == OK) {
1105 replyStatus = flushExcessBinderRefs(session, addr, target);
1106 }
1107
Frederick Mayle69a0c992022-05-26 20:38:39 +00001108 std::string errorMsg;
1109 if (status_t status = validateParcel(session, reply, &errorMsg); status != OK) {
1110 ALOGE("Reply Parcel failed validation: %s", errorMsg.c_str());
1111 // Forward the error to the client of the transaction.
1112 reply.freeData();
1113 reply.markForRpc(session);
1114 replyStatus = status;
1115 }
1116
1117 auto* rpcFields = reply.maybeRpcFields();
1118 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
1119
Frederick Mayledc07cf82022-05-26 20:30:12 +00001120 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
1121
Frederick Mayle69a0c992022-05-26 20:38:39 +00001122 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
1123 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +00001124
Frederick Mayle778c0902022-05-27 01:14:57 +00001125 uint32_t bodySize;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001126 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(rpcReplyWireSize, reply.dataSize(), &bodySize) ||
1127 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
1128 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +00001129 "Too much data for reply %zu", reply.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +00001130 RpcWireHeader cmdReply{
1131 .command = RPC_COMMAND_REPLY,
Frederick Mayle778c0902022-05-27 01:14:57 +00001132 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +00001133 };
Steven Moreland5553ac42020-11-11 02:14:45 +00001134 RpcWireReply rpcReply{
1135 .status = replyStatus,
Frederick Mayledc07cf82022-05-26 20:30:12 +00001136 // NOTE: Not necessarily written to socket depending on session
1137 // version.
1138 // NOTE: bodySize didn't overflow => this cast is safe
1139 .parcelDataSize = static_cast<uint32_t>(reply.dataSize()),
1140 .reserved = {0, 0, 0},
Steven Moreland5553ac42020-11-11 02:14:45 +00001141 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001142 iovec iovs[]{
1143 {&cmdReply, sizeof(RpcWireHeader)},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001144 {&rpcReply, rpcReplyWireSize},
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001145 {const_cast<uint8_t*>(reply.data()), reply.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001146 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001147 };
Frederick Mayle69a0c992022-05-26 20:38:39 +00001148 return rpcSend(connection, session, "reply", iovs, arraysize(iovs), std::nullopt,
1149 rpcFields->mFds.get());
Steven Moreland5553ac42020-11-11 02:14:45 +00001150}
1151
Steven Moreland5ae62562021-06-10 03:21:42 +00001152status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
1153 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001154 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
1155
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001156 if (command.bodySize != sizeof(RpcDecStrong)) {
1157 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcDecStrong. Terminating!",
1158 sizeof(RpcDecStrong), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001159 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001160 return BAD_VALUE;
1161 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001162
Frederick Mayleb86cda42022-06-09 23:17:45 +00001163 RpcDecStrong body;
1164 iovec iov{&body, sizeof(RpcDecStrong)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001165 if (status_t status = rpcRec(connection, session, "dec ref body", &iov, 1, nullptr);
1166 status != OK)
Frederick Mayleb86cda42022-06-09 23:17:45 +00001167 return status;
1168
1169 uint64_t addr = RpcWireAddress::toRaw(body.address);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001170 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001171 auto it = mNodeForAddress.find(addr);
1172 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001173 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001174 return OK;
1175 }
1176
1177 sp<IBinder> target = it->second.binder.promote();
1178 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001179 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
1180 ". Terminating!",
1181 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001182 _l.unlock();
1183 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001184 return BAD_VALUE;
1185 }
1186
Frederick Mayleb86cda42022-06-09 23:17:45 +00001187 if (it->second.timesSent < body.amount) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001188 ALOGE("Record of sending binder %zu times, but requested decStrong for %" PRIu64 " of %u",
Frederick Mayleb86cda42022-06-09 23:17:45 +00001189 it->second.timesSent, addr, body.amount);
Steven Moreland5553ac42020-11-11 02:14:45 +00001190 return OK;
1191 }
1192
Steven Moreland5623d1a2021-09-10 15:45:34 -07001193 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
1194 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001195
Frederick Mayleb86cda42022-06-09 23:17:45 +00001196 LOG_RPC_DETAIL("Processing dec strong of %" PRIu64 " by %u from %zu", addr, body.amount,
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001197 it->second.timesSent);
1198
Frederick Mayleb86cda42022-06-09 23:17:45 +00001199 it->second.timesSent -= body.amount;
Steven Moreland67f85902023-03-15 01:13:49 +00001200 sp<IBinder> tempHold = tryEraseNode(session, std::move(_l), it);
1201 // LOCK ALREADY RELEASED
Steven Moreland31bde7a2021-06-04 00:57:36 +00001202 tempHold = nullptr; // destructor may make binder calls on this session
1203
1204 return OK;
1205}
1206
Frederick Mayle69a0c992022-05-26 20:38:39 +00001207status_t RpcState::validateParcel(const sp<RpcSession>& session, const Parcel& parcel,
1208 std::string* errorMsg) {
1209 auto* rpcFields = parcel.maybeRpcFields();
1210 if (rpcFields == nullptr) {
1211 *errorMsg = "Parcel not crafted for RPC call";
1212 return BAD_TYPE;
1213 }
1214
1215 if (rpcFields->mSession != session) {
1216 *errorMsg = "Parcel's session doesn't match";
1217 return BAD_TYPE;
1218 }
1219
1220 uint32_t protocolVersion = session->getProtocolVersion().value();
1221 if (protocolVersion < RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE &&
1222 !rpcFields->mObjectPositions.empty()) {
1223 *errorMsg = StringPrintf("Parcel has attached objects but the session's protocol version "
1224 "(%" PRIu32 ") is too old, must be at least %" PRIu32,
1225 protocolVersion,
1226 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE);
1227 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) {
1239 *errorMsg = StringPrintf("Too many file descriptors in Parcel for unix "
1240 "domain socket: %zu (max is %zu)",
1241 rpcFields->mFds->size(), kMaxFdsPerMsg);
1242 return BAD_VALUE;
1243 }
Andrei Homescu1c18a802022-08-17 04:59:01 +00001244 break;
1245 }
1246 case RpcSession::FileDescriptorTransportMode::TRUSTY: {
1247 // Keep this in sync with trusty_ipc.h!!!
1248 // We could import that file here on Trusty, but it's not
1249 // available on Android
1250 constexpr size_t kMaxFdsPerMsg = 8;
1251 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
1252 *errorMsg = StringPrintf("Too many file descriptors in Parcel for Trusty "
1253 "IPC connection: %zu (max is %zu)",
1254 rpcFields->mFds->size(), kMaxFdsPerMsg);
1255 return BAD_VALUE;
1256 }
1257 break;
Frederick Mayle69a0c992022-05-26 20:38:39 +00001258 }
1259 }
1260 }
1261
1262 return OK;
1263}
1264
Steven Moreland67f85902023-03-15 01:13:49 +00001265sp<IBinder> RpcState::tryEraseNode(const sp<RpcSession>& session, RpcMutexUniqueLock nodeLock,
1266 std::map<uint64_t, BinderNode>::iterator& it) {
1267 bool shouldShutdown = false;
1268
Steven Moreland31bde7a2021-06-04 00:57:36 +00001269 sp<IBinder> ref;
1270
Steven Moreland5553ac42020-11-11 02:14:45 +00001271 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001272 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +00001273
1274 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +00001275 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
1276 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +00001277 mNodeForAddress.erase(it);
Steven Moreland67f85902023-03-15 01:13:49 +00001278
1279 if (mNodeForAddress.size() == 0) {
1280 shouldShutdown = true;
1281 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001282 }
1283 }
1284
Steven Moreland67f85902023-03-15 01:13:49 +00001285 // If we shutdown, prevent RpcState from being re-used. This prevents another
1286 // thread from getting the root object again.
1287 if (shouldShutdown) {
1288 clear(std::move(nodeLock));
1289 } else {
1290 nodeLock.unlock(); // explicit
1291 }
1292 // LOCK IS RELEASED
1293
1294 if (shouldShutdown) {
1295 ALOGI("RpcState has no binders left, so triggering shutdown...");
1296 (void)session->shutdownAndWait(false);
1297 }
1298
Steven Moreland31bde7a2021-06-04 00:57:36 +00001299 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +00001300}
1301
Steven Morelandc9d7b532021-06-04 20:57:41 +00001302bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +00001303 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
1304 // a single binder
1305 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
1306 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +00001307 return false;
1308 }
1309 node->asyncNumber++;
1310 return true;
1311}
1312
Steven Moreland5553ac42020-11-11 02:14:45 +00001313} // namespace android