blob: ed3ce24e46e2e76610ea1cd172daf9f2f15106fc [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
37namespace android {
38
Frederick Mayle69a0c992022-05-26 20:38:39 +000039using base::StringPrintf;
Steven Morelandd7302072021-05-15 01:32:04 +000040
Devin Moore08256432021-07-02 13:03:49 -070041#if RPC_FLAKE_PRONE
Steven Morelandb8176792021-06-22 20:29:21 +000042void rpcMaybeWaitToFlake() {
Devin Moore08256432021-07-02 13:03:49 -070043 [[clang::no_destroy]] static std::random_device r;
Steven Moreland7e2675c2022-09-28 23:34:52 +000044 [[clang::no_destroy]] static RpcMutex m;
Steven Morelandb8176792021-06-22 20:29:21 +000045 unsigned num;
46 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000047 RpcMutexLockGuard lock(m);
Steven Morelandb8176792021-06-22 20:29:21 +000048 num = r();
49 }
50 if (num % 10 == 0) usleep(num % 1000);
51}
52#endif
53
Frederick Mayle69a0c992022-05-26 20:38:39 +000054static bool enableAncillaryFds(RpcSession::FileDescriptorTransportMode mode) {
55 switch (mode) {
56 case RpcSession::FileDescriptorTransportMode::NONE:
57 return false;
58 case RpcSession::FileDescriptorTransportMode::UNIX:
Andrei Homescu1c18a802022-08-17 04:59:01 +000059 case RpcSession::FileDescriptorTransportMode::TRUSTY:
Frederick Mayle69a0c992022-05-26 20:38:39 +000060 return true;
61 }
62}
63
Steven Moreland5553ac42020-11-11 02:14:45 +000064RpcState::RpcState() {}
65RpcState::~RpcState() {}
66
Steven Morelandbdb53ab2021-05-05 17:57:41 +000067status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5623d1a2021-09-10 15:45:34 -070068 uint64_t* outAddress) {
Steven Moreland5553ac42020-11-11 02:14:45 +000069 bool isRemote = binder->remoteBinder();
70 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
71
Steven Moreland99157622021-09-13 16:27:34 -070072 if (isRpc && binder->remoteBinder()->getPrivateAccessor().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000073 // We need to be able to send instructions over the socket for how to
74 // connect to a different server, and we also need to let the host
75 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000076 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000077 return INVALID_OPERATION;
78 }
79
80 if (isRemote && !isRpc) {
81 // Without additional work, this would have the effect of using this
82 // process to proxy calls from the socket over to the other process, and
83 // it would make those calls look like they come from us (not over the
84 // sockets). In order to make this work transparently like binder, we
85 // would instead need to send instructions over the socket for how to
86 // connect to the host process, and we also need to let the host process
87 // know this was happening.
88 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
89 return INVALID_OPERATION;
90 }
91
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000092 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000093 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +000094
95 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
96 // in RpcState
97 for (auto& [addr, node] : mNodeForAddress) {
98 if (binder == node.binder) {
99 if (isRpc) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700100 // check integrity of data structure
Steven Moreland99157622021-09-13 16:27:34 -0700101 uint64_t actualAddr = binder->remoteBinder()->getPrivateAccessor().rpcAddress();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700102 LOG_ALWAYS_FATAL_IF(addr != actualAddr, "Address mismatch %" PRIu64 " vs %" PRIu64,
103 addr, actualAddr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000104 }
105 node.timesSent++;
106 node.sentRef = binder; // might already be set
107 *outAddress = addr;
108 return OK;
109 }
110 }
111 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
112
Steven Moreland91538242021-06-10 23:35:35 +0000113 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +0000114
Steven Moreland5623d1a2021-09-10 15:45:34 -0700115 // arbitrary limit for maximum number of nodes in a process (otherwise we
116 // might run out of addresses)
117 if (mNodeForAddress.size() > 100000) {
118 return NO_MEMORY;
119 }
120
121 while (true) {
122 RpcWireAddress address{
123 .options = RPC_WIRE_ADDRESS_OPTION_CREATED,
124 .address = mNextId,
125 };
126 if (forServer) {
127 address.options |= RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
128 }
129
130 // avoid ubsan abort
131 if (mNextId >= std::numeric_limits<uint32_t>::max()) {
132 mNextId = 0;
133 } else {
134 mNextId++;
135 }
136
137 auto&& [it, inserted] = mNodeForAddress.insert({RpcWireAddress::toRaw(address),
Steven Moreland91538242021-06-10 23:35:35 +0000138 BinderNode{
139 .binder = binder,
Steven Moreland91538242021-06-10 23:35:35 +0000140 .sentRef = binder,
Andrei Homescu5a036f32022-03-08 22:54:40 +0000141 .timesSent = 1,
Steven Moreland91538242021-06-10 23:35:35 +0000142 }});
143 if (inserted) {
144 *outAddress = it->first;
145 return OK;
146 }
Steven Moreland91538242021-06-10 23:35:35 +0000147 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000148}
149
Steven Moreland5623d1a2021-09-10 15:45:34 -0700150status_t RpcState::onBinderEntering(const sp<RpcSession>& session, uint64_t address,
Steven Moreland7227c8a2021-06-02 00:24:32 +0000151 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000152 // ensure that: if we want to use addresses for something else in the future (for
153 // instance, allowing transitive binder sends), that we don't accidentally
154 // send those addresses to old server. Accidentally ignoring this in that
155 // case and considering the binder to be recognized could cause this
156 // process to accidentally proxy transactions for that binder. Of course,
157 // if we communicate with a binder, it could always be proxying
158 // information. However, we want to make sure that isn't done on accident
159 // by a client.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700160 RpcWireAddress addr = RpcWireAddress::fromRaw(address);
161 constexpr uint32_t kKnownOptions =
162 RPC_WIRE_ADDRESS_OPTION_CREATED | RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
163 if (addr.options & ~kKnownOptions) {
164 ALOGE("Address is of an unknown type, rejecting: %" PRIu64, address);
Steven Moreland91538242021-06-10 23:35:35 +0000165 return BAD_VALUE;
166 }
167
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000168 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000169 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000170
171 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000172 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000173
174 // implicitly have strong RPC refcount, since we received this binder
175 it->second.timesRecd++;
Steven Morelandd8083312021-09-22 13:37:10 -0700176 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000177 }
178
Steven Moreland91538242021-06-10 23:35:35 +0000179 // we don't know about this binder, so the other side of the connection
180 // should have created it.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700181 if ((addr.options & RPC_WIRE_ADDRESS_OPTION_FOR_SERVER) == !!session->server()) {
182 ALOGE("Server received unrecognized address which we should own the creation of %" PRIu64,
183 address);
Steven Moreland91538242021-06-10 23:35:35 +0000184 return BAD_VALUE;
185 }
186
Steven Moreland5553ac42020-11-11 02:14:45 +0000187 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
188 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
189
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000190 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000191 // device global binders in the RPC world).
Steven Moreland99157622021-09-13 16:27:34 -0700192 it->second.binder = *out = BpBinder::PrivateAccessor::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000193 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000194 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000195}
196
Steven Morelandd8083312021-09-22 13:37:10 -0700197status_t RpcState::flushExcessBinderRefs(const sp<RpcSession>& session, uint64_t address,
198 const sp<IBinder>& binder) {
Steven Morelande96ed0e2021-09-27 17:43:53 -0700199 // We can flush all references when the binder is destroyed. No need to send
200 // extra reference counting packets now.
201 if (binder->remoteBinder()) return OK;
202
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000203 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandd8083312021-09-22 13:37:10 -0700204 if (mTerminated) return DEAD_OBJECT;
205
206 auto it = mNodeForAddress.find(address);
207
208 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Can't be deleted while we hold sp<>");
209 LOG_ALWAYS_FATAL_IF(it->second.binder != binder,
210 "Caller of flushExcessBinderRefs using inconsistent arguments");
211
Steven Morelande96ed0e2021-09-27 17:43:53 -0700212 LOG_ALWAYS_FATAL_IF(it->second.timesSent <= 0, "Local binder must have been sent %p",
213 binder.get());
Steven Morelandd8083312021-09-22 13:37:10 -0700214
Steven Morelande96ed0e2021-09-27 17:43:53 -0700215 // For a local binder, we only need to know that we sent it. Now that we
216 // have an sp<> for this call, we don't need anything more. If the other
217 // process is done with this binder, it needs to know we received the
218 // refcount associated with this call, so we can acknowledge that we
219 // received it. Once (or if) it has no other refcounts, it would reply with
220 // its own decStrong so that it could be removed from this session.
221 if (it->second.timesRecd != 0) {
Steven Morelandd8083312021-09-22 13:37:10 -0700222 _l.unlock();
223
Steven Morelande96ed0e2021-09-27 17:43:53 -0700224 return session->sendDecStrongToTarget(address, 0);
Steven Morelandd8083312021-09-22 13:37:10 -0700225 }
226
227 return OK;
228}
229
Devin Moore66d5b7a2022-07-07 21:42:10 +0000230status_t RpcState::sendObituaries(const sp<RpcSession>& session) {
231 RpcMutexUniqueLock _l(mNodeMutex);
232
233 // Gather strong pointers to all of the remote binders for this session so
234 // we hold the strong references. remoteBinder() returns a raw pointer.
235 // Send the obituaries and drop the strong pointers outside of the lock so
236 // the destructors and the onBinderDied calls are not done while locked.
237 std::vector<sp<IBinder>> remoteBinders;
238 for (const auto& [_, binderNode] : mNodeForAddress) {
239 if (auto binder = binderNode.binder.promote()) {
240 remoteBinders.push_back(std::move(binder));
241 }
242 }
243 _l.unlock();
244
245 for (const auto& binder : remoteBinders) {
246 if (binder->remoteBinder() &&
247 binder->remoteBinder()->getPrivateAccessor().rpcSession() == session) {
248 binder->remoteBinder()->sendObituary();
249 }
250 }
251 return OK;
252}
253
Steven Moreland5553ac42020-11-11 02:14:45 +0000254size_t RpcState::countBinders() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000255 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000256 return mNodeForAddress.size();
257}
258
259void RpcState::dump() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000260 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000261 dumpLocked();
262}
263
Steven Morelandc9d7b532021-06-04 20:57:41 +0000264void RpcState::clear() {
Steven Moreland67f85902023-03-15 01:13:49 +0000265 return clear(RpcMutexUniqueLock(mNodeMutex));
266}
Steven Morelandc9d7b532021-06-04 20:57:41 +0000267
Steven Moreland67f85902023-03-15 01:13:49 +0000268void RpcState::clear(RpcMutexUniqueLock nodeLock) {
Steven Morelandc9d7b532021-06-04 20:57:41 +0000269 if (mTerminated) {
270 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
271 "New state should be impossible after terminating!");
272 return;
273 }
Steven Moreland0092fe32022-07-15 00:15:34 +0000274 mTerminated = true;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000275
276 if (SHOULD_LOG_RPC_DETAIL) {
277 ALOGE("RpcState::clear()");
278 dumpLocked();
279 }
280
Steven Moreland0092fe32022-07-15 00:15:34 +0000281 // invariants
Steven Morelandc9d7b532021-06-04 20:57:41 +0000282 for (auto& [address, node] : mNodeForAddress) {
Steven Moreland0092fe32022-07-15 00:15:34 +0000283 bool guaranteedHaveBinder = node.timesSent > 0;
284 if (guaranteedHaveBinder) {
285 LOG_ALWAYS_FATAL_IF(node.sentRef == nullptr,
286 "Binder expected to be owned with address: %" PRIu64 " %s", address,
287 node.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000288 }
289 }
290
Steven Moreland0092fe32022-07-15 00:15:34 +0000291 // if the destructor of a binder object makes another RPC call, then calling
292 // decStrong could deadlock. So, we must hold onto these binders until
293 // mNodeMutex is no longer taken.
294 auto temp = std::move(mNodeForAddress);
295 mNodeForAddress.clear(); // RpcState isn't reusable, but for future/explicit
Steven Morelandc9d7b532021-06-04 20:57:41 +0000296
Steven Moreland67f85902023-03-15 01:13:49 +0000297 nodeLock.unlock();
Steven Moreland0092fe32022-07-15 00:15:34 +0000298 temp.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000299}
300
301void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000302 ALOGE("DUMP OF RpcState %p", this);
303 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
304 for (const auto& [address, node] : mNodeForAddress) {
Steven Moreland3fa32922022-07-14 18:45:51 +0000305 ALOGE("- address: %" PRIu64 " %s", address, node.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000306 }
307 ALOGE("END DUMP OF RpcState");
308}
309
Steven Moreland3fa32922022-07-14 18:45:51 +0000310std::string RpcState::BinderNode::toString() const {
311 sp<IBinder> strongBinder = this->binder.promote();
312
313 const char* desc;
314 if (strongBinder) {
315 if (strongBinder->remoteBinder()) {
316 if (strongBinder->remoteBinder()->isRpcBinder()) {
317 desc = "(rpc binder proxy)";
318 } else {
319 desc = "(binder proxy)";
320 }
321 } else {
322 desc = "(local binder)";
323 }
324 } else {
325 desc = "(not promotable)";
326 }
327
328 return StringPrintf("node{%p times sent: %zu times recd: %zu type: %s}",
329 this->binder.unsafe_get(), this->timesSent, this->timesRecd, desc);
330}
Steven Moreland5553ac42020-11-11 02:14:45 +0000331
Steven Morelanddbe71832021-05-12 23:31:00 +0000332RpcState::CommandData::CommandData(size_t size) : mSize(size) {
333 // The maximum size for regular binder is 1MB for all concurrent
334 // transactions. A very small proportion of transactions are even
335 // larger than a page, but we need to avoid allocating too much
336 // data on behalf of an arbitrary client, or we could risk being in
337 // a position where a single additional allocation could run out of
338 // memory.
339 //
340 // Note, this limit may not reflect the total amount of data allocated for a
341 // transaction (in some cases, additional fixed size amounts are added),
342 // though for rough consistency, we should avoid cases where this data type
343 // is used for multiple dynamic allocations for a single transaction.
344 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
345 if (size == 0) return;
346 if (size > kMaxTransactionAllocation) {
347 ALOGW("Transaction requested too much data allocation %zu", size);
348 return;
349 }
350 mData.reset(new (std::nothrow) uint8_t[size]);
351}
352
Frederick Mayle69a0c992022-05-26 20:38:39 +0000353status_t RpcState::rpcSend(
354 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
355 const char* what, iovec* iovs, int niovs,
356 const std::optional<android::base::function_ref<status_t()>>& altPoll,
357 const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800358 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000359 LOG_RPC_DETAIL("Sending %s (part %d of %d) on RpcTransport %p: %s",
360 what, i + 1, niovs, connection->rpcTransport.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000361 android::base::HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000362 }
363
Yifan Hong702115c2021-06-24 15:39:18 -0700364 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700365 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
Frederick Mayle69a0c992022-05-26 20:38:39 +0000366 iovs, niovs, altPoll,
367 ancillaryFds);
Steven Moreland798e0d12021-07-14 23:19:25 +0000368 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800369 LOG_RPC_DETAIL("Failed to write %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700370 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000371 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000372 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000373 }
374
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000375 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000376}
377
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000378status_t RpcState::rpcRec(
379 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
380 const char* what, iovec* iovs, int niovs,
381 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
382 if (status_t status =
383 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
384 iovs, niovs, std::nullopt,
385 ancillaryFds);
Steven Morelandee3f4662021-05-22 01:07:33 +0000386 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800387 LOG_RPC_DETAIL("Failed to read %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700388 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandae58f432021-08-05 17:53:16 -0700389 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000390 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000391 }
392
Colin Cross9adfeaf2022-01-21 17:22:09 -0800393 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000394 LOG_RPC_DETAIL("Received %s (part %d of %d) on RpcTransport %p: %s",
395 what, i + 1, niovs, connection->rpcTransport.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000396 android::base::HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
397 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000398 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000399}
400
Steven Morelandbf57bce2021-07-26 15:26:12 -0700401status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
402 const sp<RpcSession>& session, uint32_t* version) {
403 RpcNewSessionResponse response;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000404 iovec iov{&response, sizeof(response)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000405 if (status_t status = rpcRec(connection, session, "new session response", &iov, 1, nullptr);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700406 status != OK) {
407 return status;
408 }
409 *version = response.version;
410 return OK;
411}
412
Steven Moreland5ae62562021-06-10 03:21:42 +0000413status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
414 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000415 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000416 .msg = RPC_CONNECTION_INIT_OKAY,
417 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000418 iovec iov{&init, sizeof(init)};
Devin Moore695368f2022-06-03 22:29:14 +0000419 return rpcSend(connection, session, "connection init", &iov, 1, std::nullopt);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000420}
421
Steven Moreland5ae62562021-06-10 03:21:42 +0000422status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
423 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000424 RpcOutgoingConnectionInit init;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000425 iovec iov{&init, sizeof(init)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000426 if (status_t status = rpcRec(connection, session, "connection init", &iov, 1, nullptr);
427 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000428 return status;
429
430 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
431 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
432 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
433 init.msg);
434 return BAD_VALUE;
435 }
436 return OK;
437}
438
Steven Moreland5ae62562021-06-10 03:21:42 +0000439sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
440 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000441 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000442 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000443 Parcel reply;
444
Steven Moreland5623d1a2021-09-10 15:45:34 -0700445 status_t status =
446 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000447 if (status != OK) {
448 ALOGE("Error getting root object: %s", statusToString(status).c_str());
449 return nullptr;
450 }
451
452 return reply.readStrongBinder();
453}
454
Steven Moreland5ae62562021-06-10 03:21:42 +0000455status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
456 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000457 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000458 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000459 Parcel reply;
460
Steven Moreland5623d1a2021-09-10 15:45:34 -0700461 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
462 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000463 if (status != OK) {
464 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
465 return status;
466 }
467
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000468 int32_t maxThreads;
469 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000470 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000471 if (maxThreads <= 0) {
472 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000473 return BAD_VALUE;
474 }
475
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000476 *maxThreadsOut = maxThreads;
477 return OK;
478}
479
Steven Moreland5ae62562021-06-10 03:21:42 +0000480status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700481 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000482 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000483 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000484 Parcel reply;
485
Steven Moreland5623d1a2021-09-10 15:45:34 -0700486 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
487 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000488 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000489 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000490 return status;
491 }
492
Steven Moreland826367f2021-09-10 14:05:31 -0700493 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000494}
495
Steven Moreland5ae62562021-06-10 03:21:42 +0000496status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
497 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
498 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000499 std::string errorMsg;
500 if (status_t status = validateParcel(session, data, &errorMsg); status != OK) {
501 ALOGE("Refusing to send RPC on binder %p code %" PRIu32 ": Parcel %p failed validation: %s",
502 binder.get(), code, &data, errorMsg.c_str());
503 return status;
Steven Morelandf5174272021-05-25 00:39:28 +0000504 }
Steven Moreland5623d1a2021-09-10 15:45:34 -0700505 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000506 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
507
Steven Moreland5ae62562021-06-10 03:21:42 +0000508 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000509}
510
Steven Moreland5ae62562021-06-10 03:21:42 +0000511status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700512 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000513 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000514 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
515 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
516
Steven Moreland5553ac42020-11-11 02:14:45 +0000517 uint64_t asyncNumber = 0;
518
Steven Moreland5623d1a2021-09-10 15:45:34 -0700519 if (address != 0) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000520 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000521 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
522 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700523 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
524 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000525
526 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000527 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000528 if (!nodeProgressAsyncNumber(&it->second)) {
529 _l.unlock();
530 (void)session->shutdownAndWait(false);
531 return DEAD_OBJECT;
532 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000533 }
534 }
535
Frederick Mayle69a0c992022-05-26 20:38:39 +0000536 auto* rpcFields = data.maybeRpcFields();
537 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
538
539 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
540 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +0000541
Frederick Mayle778c0902022-05-27 01:14:57 +0000542 uint32_t bodySize;
543 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(sizeof(RpcWireTransaction), data.dataSize(),
Frederick Mayledc07cf82022-05-26 20:30:12 +0000544 &bodySize) ||
545 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
546 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +0000547 "Too much data %zu", data.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +0000548 RpcWireHeader command{
549 .command = RPC_COMMAND_TRANSACT,
Frederick Mayle778c0902022-05-27 01:14:57 +0000550 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +0000551 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700552
Steven Moreland5553ac42020-11-11 02:14:45 +0000553 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700554 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000555 .code = code,
556 .flags = flags,
557 .asyncNumber = asyncNumber,
Frederick Mayledc07cf82022-05-26 20:30:12 +0000558 // bodySize didn't overflow => this cast is safe
559 .parcelDataSize = static_cast<uint32_t>(data.dataSize()),
Steven Moreland5553ac42020-11-11 02:14:45 +0000560 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000561
Steven Moreland43921d52021-09-27 17:15:56 -0700562 // Oneway calls have no sync point, so if many are sent before, whether this
563 // is a twoway or oneway transaction, they may have filled up the socket.
Devin Moore695368f2022-06-03 22:29:14 +0000564 // So, make sure we drain them before polling
Steven Morelandda31af62023-02-25 01:55:58 +0000565 constexpr size_t kWaitMaxUs = 1000000;
566 constexpr size_t kWaitLogUs = 10000;
567 size_t waitUs = 0;
Steven Moreland43921d52021-09-27 17:15:56 -0700568
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000569 iovec iovs[]{
570 {&command, sizeof(RpcWireHeader)},
571 {&transaction, sizeof(RpcWireTransaction)},
572 {const_cast<uint8_t*>(data.data()), data.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +0000573 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000574 };
Frederick Mayle69a0c992022-05-26 20:38:39 +0000575 if (status_t status = rpcSend(
576 connection, session, "transaction", iovs, arraysize(iovs),
577 [&] {
578 if (waitUs > kWaitLogUs) {
579 ALOGE("Cannot send command, trying to process pending refcounts. Waiting "
580 "%zuus. Too many oneway calls?",
581 waitUs);
582 }
Devin Moore695368f2022-06-03 22:29:14 +0000583
Frederick Mayle69a0c992022-05-26 20:38:39 +0000584 if (waitUs > 0) {
585 usleep(waitUs);
586 waitUs = std::min(kWaitMaxUs, waitUs * 2);
587 } else {
588 waitUs = 1;
589 }
Devin Moore695368f2022-06-03 22:29:14 +0000590
Frederick Mayle69a0c992022-05-26 20:38:39 +0000591 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
592 },
593 rpcFields->mFds.get());
Steven Moreland43921d52021-09-27 17:15:56 -0700594 status != OK) {
Steven Morelandda31af62023-02-25 01:55:58 +0000595 // rpcSend calls shutdownAndWait, so all refcounts should be reset. If we ever tolerate
596 // errors here, then we may need to undo the binder-sent counts for the transaction as
597 // well as for the binder objects in the Parcel
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000598 return status;
Steven Moreland43921d52021-09-27 17:15:56 -0700599 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000600
601 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700602 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
603 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000604
605 // Do not wait on result.
Steven Moreland43921d52021-09-27 17:15:56 -0700606 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000607 }
608
609 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
610
Steven Moreland5ae62562021-06-10 03:21:42 +0000611 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000612}
613
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000614static void cleanup_reply_data(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
615 size_t objectsCount) {
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000616 delete[] const_cast<uint8_t*>(data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000617 (void)dataSize;
618 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000619 (void)objectsCount;
Steven Moreland5553ac42020-11-11 02:14:45 +0000620}
621
Steven Moreland5ae62562021-06-10 03:21:42 +0000622status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
623 const sp<RpcSession>& session, Parcel* reply) {
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000624 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000625 RpcWireHeader command;
626 while (true) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000627 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000628 if (status_t status = rpcRec(connection, session, "command header (for reply)", &iov, 1,
629 enableAncillaryFds(session->getFileDescriptorTransportMode())
630 ? &ancillaryFds
631 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000632 status != OK)
633 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000634
635 if (command.command == RPC_COMMAND_REPLY) break;
636
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000637 if (status_t status = processCommand(connection, session, command, CommandType::ANY,
638 std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000639 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000640 return status;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000641
642 // Reset to avoid spurious use-after-move warning from clang-tidy.
643 ancillaryFds = decltype(ancillaryFds)();
Steven Moreland5553ac42020-11-11 02:14:45 +0000644 }
645
Frederick Mayledc07cf82022-05-26 20:30:12 +0000646 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
647
648 if (command.bodySize < rpcReplyWireSize) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000649 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
650 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000651 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000652 return BAD_VALUE;
653 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000654
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000655 RpcWireReply rpcReply;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000656 memset(&rpcReply, 0, sizeof(RpcWireReply)); // zero because of potential short read
657
658 CommandData data(command.bodySize - rpcReplyWireSize);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000659 if (!data.valid()) return NO_MEMORY;
660
661 iovec iovs[]{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000662 {&rpcReply, rpcReplyWireSize},
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000663 {data.data(), data.size()},
664 };
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000665 if (status_t status = rpcRec(connection, session, "reply body", iovs, arraysize(iovs), nullptr);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000666 status != OK)
667 return status;
Frederick Mayle69a0c992022-05-26 20:38:39 +0000668
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000669 if (rpcReply.status != OK) return rpcReply.status;
670
Frederick Mayledc07cf82022-05-26 20:30:12 +0000671 Span<const uint8_t> parcelSpan = {data.data(), data.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000672 Span<const uint32_t> objectTableSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000673 if (session->getProtocolVersion().value() >=
674 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000675 std::optional<Span<const uint8_t>> objectTableBytes =
676 parcelSpan.splitOff(rpcReply.parcelDataSize);
677 if (!objectTableBytes.has_value()) {
678 ALOGE("Parcel size larger than available bytes: %" PRId32 " vs %zu. Terminating!",
679 rpcReply.parcelDataSize, parcelSpan.byteSize());
680 (void)session->shutdownAndWait(false);
681 return BAD_VALUE;
682 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000683 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000684 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000685 if (!maybeSpan.has_value()) {
686 ALOGE("Bad object table size inferred from RpcWireReply. Saw bodySize=%" PRId32
687 " sizeofHeader=%zu parcelSize=%" PRId32 " objectTableBytesSize=%zu. Terminating!",
688 command.bodySize, rpcReplyWireSize, rpcReply.parcelDataSize,
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000689 objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000690 return BAD_VALUE;
691 }
692 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000693 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000694
Frederick Mayledc07cf82022-05-26 20:30:12 +0000695 data.release();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000696 return reply->rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
697 objectTableSpan.data, objectTableSpan.size,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000698 std::move(ancillaryFds), cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000699}
700
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000701status_t RpcState::sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection,
702 const sp<RpcSession>& session, uint64_t addr,
703 size_t target) {
704 RpcDecStrong body = {
705 .address = RpcWireAddress::fromRaw(addr),
706 };
707
Steven Moreland5553ac42020-11-11 02:14:45 +0000708 {
Steven Moreland67f85902023-03-15 01:13:49 +0000709 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000710 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
711 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700712 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
713 "Sending dec strong on unknown address %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000714
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000715 LOG_ALWAYS_FATAL_IF(it->second.timesRecd < target, "Can't dec count of %zu to %zu.",
716 it->second.timesRecd, target);
717
718 // typically this happens when multiple threads send dec refs at the
719 // same time - the transactions will get combined automatically
720 if (it->second.timesRecd == target) return OK;
721
722 body.amount = it->second.timesRecd - target;
723 it->second.timesRecd = target;
724
Steven Moreland67f85902023-03-15 01:13:49 +0000725 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(session, std::move(_l), it),
Steven Moreland31bde7a2021-06-04 00:57:36 +0000726 "Bad state. RpcState shouldn't own received binder");
Steven Moreland67f85902023-03-15 01:13:49 +0000727 // LOCK ALREADY RELEASED
Steven Moreland5553ac42020-11-11 02:14:45 +0000728 }
729
730 RpcWireHeader cmd = {
731 .command = RPC_COMMAND_DEC_STRONG,
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000732 .bodySize = sizeof(RpcDecStrong),
Steven Moreland5553ac42020-11-11 02:14:45 +0000733 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000734 iovec iovs[]{{&cmd, sizeof(cmd)}, {&body, sizeof(body)}};
Devin Moore695368f2022-06-03 22:29:14 +0000735 return rpcSend(connection, session, "dec ref", iovs, arraysize(iovs), std::nullopt);
Steven Moreland5553ac42020-11-11 02:14:45 +0000736}
737
Steven Moreland5ae62562021-06-10 03:21:42 +0000738status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
739 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700740 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000741
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000742 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000743 RpcWireHeader command;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000744 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000745 if (status_t status =
746 rpcRec(connection, session, "command header (for server)", &iov, 1,
747 enableAncillaryFds(session->getFileDescriptorTransportMode()) ? &ancillaryFds
748 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000749 status != OK)
750 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000751
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000752 return processCommand(connection, session, command, type, std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000753}
754
Steven Moreland5ae62562021-06-10 03:21:42 +0000755status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
756 const sp<RpcSession>& session, CommandType type) {
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000757 while (true) {
Andrei Homescu1975aaa2022-03-19 02:34:57 +0000758 status_t status = connection->rpcTransport->pollRead();
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000759 if (status == WOULD_BLOCK) break;
760 if (status != OK) return status;
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000761
762 status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000763 if (status != OK) return status;
764 }
765 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000766}
767
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000768status_t RpcState::processCommand(
769 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
770 const RpcWireHeader& command, CommandType type,
771 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland32150282021-11-12 22:54:53 +0000772#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000773 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
774 IPCThreadState::SpGuard spGuard{
775 .address = __builtin_frame_address(0),
Steven Morelande42ffd02022-07-06 21:46:23 +0000776 .context = "processing binder RPC command (where RpcServer::setPerSessionRootObject is "
777 "used to distinguish callers)",
Steven Morelandd7302072021-05-15 01:32:04 +0000778 };
779 const IPCThreadState::SpGuard* origGuard;
780 if (kernelBinderState != nullptr) {
781 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
782 }
Steven Moreland32150282021-11-12 22:54:53 +0000783
784 base::ScopeGuard guardUnguard = [&]() {
Steven Morelandd7302072021-05-15 01:32:04 +0000785 if (kernelBinderState != nullptr) {
786 kernelBinderState->restoreGetCallingSpGuard(origGuard);
787 }
788 };
Steven Moreland32150282021-11-12 22:54:53 +0000789#endif // BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000790
Steven Moreland5553ac42020-11-11 02:14:45 +0000791 switch (command.command) {
792 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000793 if (type != CommandType::ANY) return BAD_TYPE;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000794 return processTransact(connection, session, command, std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000795 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000796 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000797 }
798
799 // We should always know the version of the opposing side, and since the
800 // RPC-binder-level wire protocol is not self synchronizing, we have no way
801 // to understand where the current command ends and the next one begins. We
802 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000803 // to kill us, so ending the session for misbehaving client.
804 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000805 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000806 return DEAD_OBJECT;
807}
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000808status_t RpcState::processTransact(
809 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
810 const RpcWireHeader& command,
811 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000812 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
813
Steven Morelanddbe71832021-05-12 23:31:00 +0000814 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000815 if (!transactionData.valid()) {
816 return NO_MEMORY;
817 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000818 iovec iov{transactionData.data(), transactionData.size()};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000819 if (status_t status = rpcRec(connection, session, "transaction body", &iov, 1, nullptr);
820 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000821 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000822
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000823 return processTransactInternal(connection, session, std::move(transactionData),
824 std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000825}
826
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000827static void do_nothing_to_transact_data(const uint8_t* data, size_t dataSize,
Steven Moreland438cce82021-04-02 18:04:08 +0000828 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland438cce82021-04-02 18:04:08 +0000829 (void)data;
830 (void)dataSize;
831 (void)objects;
832 (void)objectsCount;
833}
834
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000835status_t RpcState::processTransactInternal(
836 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
837 CommandData transactionData,
838 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Morelandada72bd2021-06-09 23:29:13 +0000839 // for 'recursive' calls to this, we have already read and processed the
840 // binder from the transaction data and taken reference counts into account,
841 // so it is cached here.
Steven Moreland3903bf02021-09-27 16:05:24 -0700842 sp<IBinder> target;
Steven Morelandada72bd2021-06-09 23:29:13 +0000843processTransactInternalTailCall:
844
Steven Moreland5553ac42020-11-11 02:14:45 +0000845 if (transactionData.size() < sizeof(RpcWireTransaction)) {
846 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
847 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000848 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000849 return BAD_VALUE;
850 }
851 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
852
Steven Moreland5623d1a2021-09-10 15:45:34 -0700853 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000854 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000855
856 status_t replyStatus = OK;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700857 if (addr != 0) {
Steven Moreland3903bf02021-09-27 16:05:24 -0700858 if (!target) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000859 replyStatus = onBinderEntering(session, addr, &target);
Steven Morelandf5174272021-05-25 00:39:28 +0000860 }
861
Steven Moreland7227c8a2021-06-02 00:24:32 +0000862 if (replyStatus != OK) {
863 // do nothing
864 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000865 // This can happen if the binder is remote in this process, and
866 // another thread has called the last decStrong on this binder.
867 // However, for local binders, it indicates a misbehaving client
868 // (any binder which is being transacted on should be holding a
869 // strong ref count), so in either case, terminating the
870 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700871 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
872 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000873 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000874 replyStatus = BAD_VALUE;
875 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700876 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
877 ". Terminating!",
878 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000879 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000880 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000881 } else if (oneway) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000882 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000883 auto it = mNodeForAddress.find(addr);
884 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700885 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000886 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000887 } else if (transaction->asyncNumber != it->second.asyncNumber) {
888 // we need to process some other asynchronous transaction
889 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000890 it->second.asyncTodo.push(BinderNode::AsyncTodo{
891 .ref = target,
892 .data = std::move(transactionData),
Frederick Mayleb0221d12022-10-03 23:10:53 +0000893 .ancillaryFds = std::move(ancillaryFds),
Steven Morelandf5174272021-05-25 00:39:28 +0000894 .asyncNumber = transaction->asyncNumber,
895 });
Steven Morelandd45be622021-06-04 02:19:37 +0000896
897 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700898 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
899 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000900
901 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
902 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
903 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
904
905 if (numPending >= kArbitraryOnewayCallWarnLevel) {
906 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
907 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
908 _l.unlock();
909 (void)session->shutdownAndWait(false);
910 return FAILED_TRANSACTION;
911 }
912
913 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
914 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
915 target.get(), numPending);
916 }
917 }
Steven Morelandf5174272021-05-25 00:39:28 +0000918 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000919 }
920 }
921 }
922
Steven Moreland5553ac42020-11-11 02:14:45 +0000923 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000924 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000925
926 if (replyStatus == OK) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000927 Span<const uint8_t> parcelSpan = {transaction->data,
928 transactionData.size() -
929 offsetof(RpcWireTransaction, data)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000930 Span<const uint32_t> objectTableSpan;
931 if (session->getProtocolVersion().value() >
Frederick Mayledc07cf82022-05-26 20:30:12 +0000932 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000933 std::optional<Span<const uint8_t>> objectTableBytes =
934 parcelSpan.splitOff(transaction->parcelDataSize);
935 if (!objectTableBytes.has_value()) {
936 ALOGE("Parcel size (%" PRId32 ") greater than available bytes (%zu). Terminating!",
937 transaction->parcelDataSize, parcelSpan.byteSize());
938 (void)session->shutdownAndWait(false);
939 return BAD_VALUE;
940 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000941 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000942 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000943 if (!maybeSpan.has_value()) {
944 ALOGE("Bad object table size inferred from RpcWireTransaction. Saw bodySize=%zu "
945 "sizeofHeader=%zu parcelSize=%" PRId32
946 " objectTableBytesSize=%zu. Terminating!",
947 transactionData.size(), sizeof(RpcWireTransaction),
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000948 transaction->parcelDataSize, objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000949 return BAD_VALUE;
950 }
951 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000952 }
953
Steven Morelandeff77c12021-04-15 00:37:19 +0000954 Parcel data;
955 // transaction->data is owned by this function. Parcel borrows this data and
956 // only holds onto it for the duration of this function call. Parcel will be
957 // deleted before the 'transactionData' object.
Frederick Mayledc07cf82022-05-26 20:30:12 +0000958
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000959 replyStatus =
960 data.rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
961 objectTableSpan.data, objectTableSpan.size,
962 std::move(ancillaryFds), do_nothing_to_transact_data);
963 // Reset to avoid spurious use-after-move warning from clang-tidy.
964 ancillaryFds = std::remove_reference<decltype(ancillaryFds)>::type();
Steven Morelandeff77c12021-04-15 00:37:19 +0000965
Frederick Mayle69a0c992022-05-26 20:38:39 +0000966 if (replyStatus == OK) {
967 if (target) {
968 bool origAllowNested = connection->allowNested;
969 connection->allowNested = !oneway;
Steven Morelandc7d40132021-06-10 03:42:11 +0000970
Frederick Mayle69a0c992022-05-26 20:38:39 +0000971 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000972
Frederick Mayle69a0c992022-05-26 20:38:39 +0000973 connection->allowNested = origAllowNested;
974 } else {
975 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000976
Frederick Mayle69a0c992022-05-26 20:38:39 +0000977 switch (transaction->code) {
978 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
979 replyStatus = reply.writeInt32(session->getMaxIncomingThreads());
980 break;
981 }
982 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
983 // for client connections, this should always report the value
984 // originally returned from the server, so this is asserting
985 // that it exists
986 replyStatus = reply.writeByteVector(session->mId);
987 break;
988 }
989 default: {
990 sp<RpcServer> server = session->server();
991 if (server) {
992 switch (transaction->code) {
993 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
994 sp<IBinder> root = session->mSessionSpecificRootObject
995 ?: server->getRootObject();
996 replyStatus = reply.writeStrongBinder(root);
997 break;
998 }
999 default: {
1000 replyStatus = UNKNOWN_TRANSACTION;
1001 }
Steven Moreland103424e2021-06-02 18:16:19 +00001002 }
Frederick Mayle69a0c992022-05-26 20:38:39 +00001003 } else {
1004 ALOGE("Special command sent, but no server object attached.");
Steven Moreland103424e2021-06-02 18:16:19 +00001005 }
Steven Morelandf137de92021-04-24 01:54:26 +00001006 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001007 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001008 }
1009 }
1010 }
1011
Steven Morelandc7d40132021-06-10 03:42:11 +00001012 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001013 if (replyStatus != OK) {
1014 ALOGW("Oneway call failed with error: %d", replyStatus);
1015 }
1016
Steven Moreland5623d1a2021-09-10 15:45:34 -07001017 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
1018 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001019
1020 // Check to see if there is another asynchronous transaction to process.
1021 // This behavior differs from binder behavior, since in the binder
1022 // driver, asynchronous transactions will be processed after existing
1023 // pending binder transactions on the queue. The downside of this is
1024 // that asynchronous transactions can be drowned out by synchronous
1025 // transactions. However, we have no easy way to queue these
1026 // transactions after the synchronous transactions we may want to read
1027 // from the wire. So, in socket binder here, we have the opposite
1028 // downside: asynchronous transactions may drown out synchronous
1029 // transactions.
1030 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001031 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001032 auto it = mNodeForAddress.find(addr);
1033 // last refcount dropped after this transaction happened
1034 if (it == mNodeForAddress.end()) return OK;
1035
Steven Morelandc9d7b532021-06-04 20:57:41 +00001036 if (!nodeProgressAsyncNumber(&it->second)) {
1037 _l.unlock();
1038 (void)session->shutdownAndWait(false);
1039 return DEAD_OBJECT;
1040 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001041
Andrei Homescuae5f0d12023-02-25 05:03:31 +00001042 if (it->second.asyncTodo.size() != 0 &&
1043 it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001044 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
1045 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001046
1047 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +00001048 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +00001049 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +00001050 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
1051
Steven Morelandada72bd2021-06-09 23:29:13 +00001052 // reset up arguments
1053 transactionData = std::move(todo.data);
Frederick Mayleb0221d12022-10-03 23:10:53 +00001054 ancillaryFds = std::move(todo.ancillaryFds);
Steven Moreland3903bf02021-09-27 16:05:24 -07001055 LOG_ALWAYS_FATAL_IF(target != todo.ref,
1056 "async list should be associated with a binder");
Steven Morelandf5174272021-05-25 00:39:28 +00001057
Steven Moreland5553ac42020-11-11 02:14:45 +00001058 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +00001059 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +00001060 }
1061 }
Steven Morelandd8083312021-09-22 13:37:10 -07001062
1063 // done processing all the async commands on this binder that we can, so
1064 // write decstrongs on the binder
1065 if (addr != 0 && replyStatus == OK) {
1066 return flushExcessBinderRefs(session, addr, target);
1067 }
1068
Steven Moreland5553ac42020-11-11 02:14:45 +00001069 return OK;
1070 }
1071
Steven Moreland6709cf42021-09-30 15:21:54 -07001072 // Binder refs are flushed for oneway calls only after all calls which are
1073 // built up are executed. Otherwise, they fill up the binder buffer.
1074 if (addr != 0 && replyStatus == OK) {
1075 replyStatus = flushExcessBinderRefs(session, addr, target);
1076 }
1077
Frederick Mayle69a0c992022-05-26 20:38:39 +00001078 std::string errorMsg;
1079 if (status_t status = validateParcel(session, reply, &errorMsg); status != OK) {
1080 ALOGE("Reply Parcel failed validation: %s", errorMsg.c_str());
1081 // Forward the error to the client of the transaction.
1082 reply.freeData();
1083 reply.markForRpc(session);
1084 replyStatus = status;
1085 }
1086
1087 auto* rpcFields = reply.maybeRpcFields();
1088 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
1089
Frederick Mayledc07cf82022-05-26 20:30:12 +00001090 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
1091
Frederick Mayle69a0c992022-05-26 20:38:39 +00001092 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
1093 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +00001094
Frederick Mayle778c0902022-05-27 01:14:57 +00001095 uint32_t bodySize;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001096 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(rpcReplyWireSize, reply.dataSize(), &bodySize) ||
1097 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
1098 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +00001099 "Too much data for reply %zu", reply.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +00001100 RpcWireHeader cmdReply{
1101 .command = RPC_COMMAND_REPLY,
Frederick Mayle778c0902022-05-27 01:14:57 +00001102 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +00001103 };
Steven Moreland5553ac42020-11-11 02:14:45 +00001104 RpcWireReply rpcReply{
1105 .status = replyStatus,
Frederick Mayledc07cf82022-05-26 20:30:12 +00001106 // NOTE: Not necessarily written to socket depending on session
1107 // version.
1108 // NOTE: bodySize didn't overflow => this cast is safe
1109 .parcelDataSize = static_cast<uint32_t>(reply.dataSize()),
1110 .reserved = {0, 0, 0},
Steven Moreland5553ac42020-11-11 02:14:45 +00001111 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001112 iovec iovs[]{
1113 {&cmdReply, sizeof(RpcWireHeader)},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001114 {&rpcReply, rpcReplyWireSize},
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001115 {const_cast<uint8_t*>(reply.data()), reply.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001116 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001117 };
Frederick Mayle69a0c992022-05-26 20:38:39 +00001118 return rpcSend(connection, session, "reply", iovs, arraysize(iovs), std::nullopt,
1119 rpcFields->mFds.get());
Steven Moreland5553ac42020-11-11 02:14:45 +00001120}
1121
Steven Moreland5ae62562021-06-10 03:21:42 +00001122status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
1123 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001124 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
1125
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001126 if (command.bodySize != sizeof(RpcDecStrong)) {
1127 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcDecStrong. Terminating!",
1128 sizeof(RpcDecStrong), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001129 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001130 return BAD_VALUE;
1131 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001132
Frederick Mayleb86cda42022-06-09 23:17:45 +00001133 RpcDecStrong body;
1134 iovec iov{&body, sizeof(RpcDecStrong)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001135 if (status_t status = rpcRec(connection, session, "dec ref body", &iov, 1, nullptr);
1136 status != OK)
Frederick Mayleb86cda42022-06-09 23:17:45 +00001137 return status;
1138
1139 uint64_t addr = RpcWireAddress::toRaw(body.address);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001140 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001141 auto it = mNodeForAddress.find(addr);
1142 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001143 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001144 return OK;
1145 }
1146
1147 sp<IBinder> target = it->second.binder.promote();
1148 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001149 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
1150 ". Terminating!",
1151 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001152 _l.unlock();
1153 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001154 return BAD_VALUE;
1155 }
1156
Frederick Mayleb86cda42022-06-09 23:17:45 +00001157 if (it->second.timesSent < body.amount) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001158 ALOGE("Record of sending binder %zu times, but requested decStrong for %" PRIu64 " of %u",
Frederick Mayleb86cda42022-06-09 23:17:45 +00001159 it->second.timesSent, addr, body.amount);
Steven Moreland5553ac42020-11-11 02:14:45 +00001160 return OK;
1161 }
1162
Steven Moreland5623d1a2021-09-10 15:45:34 -07001163 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
1164 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001165
Frederick Mayleb86cda42022-06-09 23:17:45 +00001166 LOG_RPC_DETAIL("Processing dec strong of %" PRIu64 " by %u from %zu", addr, body.amount,
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001167 it->second.timesSent);
1168
Frederick Mayleb86cda42022-06-09 23:17:45 +00001169 it->second.timesSent -= body.amount;
Steven Moreland67f85902023-03-15 01:13:49 +00001170 sp<IBinder> tempHold = tryEraseNode(session, std::move(_l), it);
1171 // LOCK ALREADY RELEASED
Steven Moreland31bde7a2021-06-04 00:57:36 +00001172 tempHold = nullptr; // destructor may make binder calls on this session
1173
1174 return OK;
1175}
1176
Frederick Mayle69a0c992022-05-26 20:38:39 +00001177status_t RpcState::validateParcel(const sp<RpcSession>& session, const Parcel& parcel,
1178 std::string* errorMsg) {
1179 auto* rpcFields = parcel.maybeRpcFields();
1180 if (rpcFields == nullptr) {
1181 *errorMsg = "Parcel not crafted for RPC call";
1182 return BAD_TYPE;
1183 }
1184
1185 if (rpcFields->mSession != session) {
1186 *errorMsg = "Parcel's session doesn't match";
1187 return BAD_TYPE;
1188 }
1189
1190 uint32_t protocolVersion = session->getProtocolVersion().value();
1191 if (protocolVersion < RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE &&
1192 !rpcFields->mObjectPositions.empty()) {
1193 *errorMsg = StringPrintf("Parcel has attached objects but the session's protocol version "
1194 "(%" PRIu32 ") is too old, must be at least %" PRIu32,
1195 protocolVersion,
1196 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE);
1197 return BAD_VALUE;
1198 }
1199
1200 if (rpcFields->mFds && !rpcFields->mFds->empty()) {
1201 switch (session->getFileDescriptorTransportMode()) {
1202 case RpcSession::FileDescriptorTransportMode::NONE:
1203 *errorMsg =
1204 "Parcel has file descriptors, but no file descriptor transport is enabled";
1205 return FDS_NOT_ALLOWED;
1206 case RpcSession::FileDescriptorTransportMode::UNIX: {
1207 constexpr size_t kMaxFdsPerMsg = 253;
1208 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
1209 *errorMsg = StringPrintf("Too many file descriptors in Parcel for unix "
1210 "domain socket: %zu (max is %zu)",
1211 rpcFields->mFds->size(), kMaxFdsPerMsg);
1212 return BAD_VALUE;
1213 }
Andrei Homescu1c18a802022-08-17 04:59:01 +00001214 break;
1215 }
1216 case RpcSession::FileDescriptorTransportMode::TRUSTY: {
1217 // Keep this in sync with trusty_ipc.h!!!
1218 // We could import that file here on Trusty, but it's not
1219 // available on Android
1220 constexpr size_t kMaxFdsPerMsg = 8;
1221 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
1222 *errorMsg = StringPrintf("Too many file descriptors in Parcel for Trusty "
1223 "IPC connection: %zu (max is %zu)",
1224 rpcFields->mFds->size(), kMaxFdsPerMsg);
1225 return BAD_VALUE;
1226 }
1227 break;
Frederick Mayle69a0c992022-05-26 20:38:39 +00001228 }
1229 }
1230 }
1231
1232 return OK;
1233}
1234
Steven Moreland67f85902023-03-15 01:13:49 +00001235sp<IBinder> RpcState::tryEraseNode(const sp<RpcSession>& session, RpcMutexUniqueLock nodeLock,
1236 std::map<uint64_t, BinderNode>::iterator& it) {
1237 bool shouldShutdown = false;
1238
Steven Moreland31bde7a2021-06-04 00:57:36 +00001239 sp<IBinder> ref;
1240
Steven Moreland5553ac42020-11-11 02:14:45 +00001241 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001242 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +00001243
1244 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +00001245 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
1246 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +00001247 mNodeForAddress.erase(it);
Steven Moreland67f85902023-03-15 01:13:49 +00001248
1249 if (mNodeForAddress.size() == 0) {
1250 shouldShutdown = true;
1251 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001252 }
1253 }
1254
Steven Moreland67f85902023-03-15 01:13:49 +00001255 // If we shutdown, prevent RpcState from being re-used. This prevents another
1256 // thread from getting the root object again.
1257 if (shouldShutdown) {
1258 clear(std::move(nodeLock));
1259 } else {
1260 nodeLock.unlock(); // explicit
1261 }
1262 // LOCK IS RELEASED
1263
1264 if (shouldShutdown) {
1265 ALOGI("RpcState has no binders left, so triggering shutdown...");
1266 (void)session->shutdownAndWait(false);
1267 }
1268
Steven Moreland31bde7a2021-06-04 00:57:36 +00001269 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +00001270}
1271
Steven Morelandc9d7b532021-06-04 20:57:41 +00001272bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +00001273 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
1274 // a single binder
1275 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
1276 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +00001277 return false;
1278 }
1279 node->asyncNumber++;
1280 return true;
1281}
1282
Steven Moreland5553ac42020-11-11 02:14:45 +00001283} // namespace android