blob: ff35f5f35cbd72298831c0f3633b4d7c7fac9650 [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 Morelandca3f6382023-05-11 23:23:26 +0000401bool RpcState::validateProtocolVersion(uint32_t version) {
402 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
403 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
404 ALOGE("Cannot use RPC binder protocol version %u which is unknown (current protocol "
405 "version "
406 "is %u).",
407 version, RPC_WIRE_PROTOCOL_VERSION);
408 return false;
409 }
410 return true;
411}
412
Steven Morelandbf57bce2021-07-26 15:26:12 -0700413status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
414 const sp<RpcSession>& session, uint32_t* version) {
415 RpcNewSessionResponse response;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000416 iovec iov{&response, sizeof(response)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000417 if (status_t status = rpcRec(connection, session, "new session response", &iov, 1, nullptr);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700418 status != OK) {
419 return status;
420 }
421 *version = response.version;
422 return OK;
423}
424
Steven Moreland5ae62562021-06-10 03:21:42 +0000425status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
426 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000427 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000428 .msg = RPC_CONNECTION_INIT_OKAY,
429 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000430 iovec iov{&init, sizeof(init)};
Devin Moore695368f2022-06-03 22:29:14 +0000431 return rpcSend(connection, session, "connection init", &iov, 1, std::nullopt);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000432}
433
Steven Moreland5ae62562021-06-10 03:21:42 +0000434status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
435 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000436 RpcOutgoingConnectionInit init;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000437 iovec iov{&init, sizeof(init)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000438 if (status_t status = rpcRec(connection, session, "connection init", &iov, 1, nullptr);
439 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000440 return status;
441
442 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
443 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
444 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
445 init.msg);
446 return BAD_VALUE;
447 }
448 return OK;
449}
450
Steven Moreland5ae62562021-06-10 03:21:42 +0000451sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
452 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000453 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000454 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000455 Parcel reply;
456
Steven Moreland5623d1a2021-09-10 15:45:34 -0700457 status_t status =
458 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000459 if (status != OK) {
460 ALOGE("Error getting root object: %s", statusToString(status).c_str());
461 return nullptr;
462 }
463
464 return reply.readStrongBinder();
465}
466
Steven Moreland5ae62562021-06-10 03:21:42 +0000467status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
468 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000469 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000470 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000471 Parcel reply;
472
Steven Moreland5623d1a2021-09-10 15:45:34 -0700473 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
474 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000475 if (status != OK) {
476 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
477 return status;
478 }
479
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000480 int32_t maxThreads;
481 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000482 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000483 if (maxThreads <= 0) {
484 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000485 return BAD_VALUE;
486 }
487
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000488 *maxThreadsOut = maxThreads;
489 return OK;
490}
491
Steven Moreland5ae62562021-06-10 03:21:42 +0000492status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700493 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000494 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000495 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000496 Parcel reply;
497
Steven Moreland5623d1a2021-09-10 15:45:34 -0700498 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
499 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000500 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000501 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000502 return status;
503 }
504
Steven Moreland826367f2021-09-10 14:05:31 -0700505 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000506}
507
Steven Moreland5ae62562021-06-10 03:21:42 +0000508status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
509 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
510 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000511 std::string errorMsg;
512 if (status_t status = validateParcel(session, data, &errorMsg); status != OK) {
513 ALOGE("Refusing to send RPC on binder %p code %" PRIu32 ": Parcel %p failed validation: %s",
514 binder.get(), code, &data, errorMsg.c_str());
515 return status;
Steven Morelandf5174272021-05-25 00:39:28 +0000516 }
Steven Moreland5623d1a2021-09-10 15:45:34 -0700517 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000518 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
519
Steven Moreland5ae62562021-06-10 03:21:42 +0000520 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000521}
522
Steven Moreland5ae62562021-06-10 03:21:42 +0000523status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700524 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000525 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000526 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
527 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
528
Steven Moreland5553ac42020-11-11 02:14:45 +0000529 uint64_t asyncNumber = 0;
530
Steven Moreland5623d1a2021-09-10 15:45:34 -0700531 if (address != 0) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000532 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000533 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
534 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700535 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
536 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000537
538 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000539 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000540 if (!nodeProgressAsyncNumber(&it->second)) {
541 _l.unlock();
542 (void)session->shutdownAndWait(false);
543 return DEAD_OBJECT;
544 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000545 }
546 }
547
Frederick Mayle69a0c992022-05-26 20:38:39 +0000548 auto* rpcFields = data.maybeRpcFields();
549 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
550
551 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
552 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +0000553
Frederick Mayle778c0902022-05-27 01:14:57 +0000554 uint32_t bodySize;
555 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(sizeof(RpcWireTransaction), data.dataSize(),
Frederick Mayledc07cf82022-05-26 20:30:12 +0000556 &bodySize) ||
557 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
558 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +0000559 "Too much data %zu", data.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +0000560 RpcWireHeader command{
561 .command = RPC_COMMAND_TRANSACT,
Frederick Mayle778c0902022-05-27 01:14:57 +0000562 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +0000563 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700564
Steven Moreland5553ac42020-11-11 02:14:45 +0000565 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700566 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000567 .code = code,
568 .flags = flags,
569 .asyncNumber = asyncNumber,
Frederick Mayledc07cf82022-05-26 20:30:12 +0000570 // bodySize didn't overflow => this cast is safe
571 .parcelDataSize = static_cast<uint32_t>(data.dataSize()),
Steven Moreland5553ac42020-11-11 02:14:45 +0000572 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000573
Steven Moreland43921d52021-09-27 17:15:56 -0700574 // Oneway calls have no sync point, so if many are sent before, whether this
575 // is a twoway or oneway transaction, they may have filled up the socket.
Devin Moore695368f2022-06-03 22:29:14 +0000576 // So, make sure we drain them before polling
Steven Morelandda31af62023-02-25 01:55:58 +0000577 constexpr size_t kWaitMaxUs = 1000000;
578 constexpr size_t kWaitLogUs = 10000;
579 size_t waitUs = 0;
Steven Moreland43921d52021-09-27 17:15:56 -0700580
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000581 iovec iovs[]{
582 {&command, sizeof(RpcWireHeader)},
583 {&transaction, sizeof(RpcWireTransaction)},
584 {const_cast<uint8_t*>(data.data()), data.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +0000585 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000586 };
Frederick Mayle69a0c992022-05-26 20:38:39 +0000587 if (status_t status = rpcSend(
588 connection, session, "transaction", iovs, arraysize(iovs),
589 [&] {
590 if (waitUs > kWaitLogUs) {
591 ALOGE("Cannot send command, trying to process pending refcounts. Waiting "
592 "%zuus. Too many oneway calls?",
593 waitUs);
594 }
Devin Moore695368f2022-06-03 22:29:14 +0000595
Frederick Mayle69a0c992022-05-26 20:38:39 +0000596 if (waitUs > 0) {
597 usleep(waitUs);
598 waitUs = std::min(kWaitMaxUs, waitUs * 2);
599 } else {
600 waitUs = 1;
601 }
Devin Moore695368f2022-06-03 22:29:14 +0000602
Frederick Mayle69a0c992022-05-26 20:38:39 +0000603 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
604 },
605 rpcFields->mFds.get());
Steven Moreland43921d52021-09-27 17:15:56 -0700606 status != OK) {
Steven Morelandda31af62023-02-25 01:55:58 +0000607 // rpcSend calls shutdownAndWait, so all refcounts should be reset. If we ever tolerate
608 // errors here, then we may need to undo the binder-sent counts for the transaction as
609 // well as for the binder objects in the Parcel
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000610 return status;
Steven Moreland43921d52021-09-27 17:15:56 -0700611 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000612
613 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700614 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
615 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000616
617 // Do not wait on result.
Steven Moreland43921d52021-09-27 17:15:56 -0700618 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000619 }
620
621 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
622
Steven Moreland5ae62562021-06-10 03:21:42 +0000623 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000624}
625
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000626static void cleanup_reply_data(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
627 size_t objectsCount) {
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000628 delete[] const_cast<uint8_t*>(data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000629 (void)dataSize;
630 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000631 (void)objectsCount;
Steven Moreland5553ac42020-11-11 02:14:45 +0000632}
633
Steven Moreland5ae62562021-06-10 03:21:42 +0000634status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
635 const sp<RpcSession>& session, Parcel* reply) {
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000636 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000637 RpcWireHeader command;
638 while (true) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000639 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000640 if (status_t status = rpcRec(connection, session, "command header (for reply)", &iov, 1,
641 enableAncillaryFds(session->getFileDescriptorTransportMode())
642 ? &ancillaryFds
643 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000644 status != OK)
645 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000646
647 if (command.command == RPC_COMMAND_REPLY) break;
648
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000649 if (status_t status = processCommand(connection, session, command, CommandType::ANY,
650 std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000651 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000652 return status;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000653
654 // Reset to avoid spurious use-after-move warning from clang-tidy.
655 ancillaryFds = decltype(ancillaryFds)();
Steven Moreland5553ac42020-11-11 02:14:45 +0000656 }
657
Frederick Mayledc07cf82022-05-26 20:30:12 +0000658 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
659
660 if (command.bodySize < rpcReplyWireSize) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000661 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
662 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000663 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000664 return BAD_VALUE;
665 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000666
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000667 RpcWireReply rpcReply;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000668 memset(&rpcReply, 0, sizeof(RpcWireReply)); // zero because of potential short read
669
670 CommandData data(command.bodySize - rpcReplyWireSize);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000671 if (!data.valid()) return NO_MEMORY;
672
673 iovec iovs[]{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000674 {&rpcReply, rpcReplyWireSize},
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000675 {data.data(), data.size()},
676 };
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000677 if (status_t status = rpcRec(connection, session, "reply body", iovs, arraysize(iovs), nullptr);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000678 status != OK)
679 return status;
Frederick Mayle69a0c992022-05-26 20:38:39 +0000680
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000681 if (rpcReply.status != OK) return rpcReply.status;
682
Frederick Mayledc07cf82022-05-26 20:30:12 +0000683 Span<const uint8_t> parcelSpan = {data.data(), data.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000684 Span<const uint32_t> objectTableSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000685 if (session->getProtocolVersion().value() >=
686 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000687 std::optional<Span<const uint8_t>> objectTableBytes =
688 parcelSpan.splitOff(rpcReply.parcelDataSize);
689 if (!objectTableBytes.has_value()) {
690 ALOGE("Parcel size larger than available bytes: %" PRId32 " vs %zu. Terminating!",
691 rpcReply.parcelDataSize, parcelSpan.byteSize());
692 (void)session->shutdownAndWait(false);
693 return BAD_VALUE;
694 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000695 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000696 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000697 if (!maybeSpan.has_value()) {
698 ALOGE("Bad object table size inferred from RpcWireReply. Saw bodySize=%" PRId32
699 " sizeofHeader=%zu parcelSize=%" PRId32 " objectTableBytesSize=%zu. Terminating!",
700 command.bodySize, rpcReplyWireSize, rpcReply.parcelDataSize,
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000701 objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000702 return BAD_VALUE;
703 }
704 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000705 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000706
Frederick Mayledc07cf82022-05-26 20:30:12 +0000707 data.release();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000708 return reply->rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
709 objectTableSpan.data, objectTableSpan.size,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000710 std::move(ancillaryFds), cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000711}
712
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000713status_t RpcState::sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection,
714 const sp<RpcSession>& session, uint64_t addr,
715 size_t target) {
716 RpcDecStrong body = {
717 .address = RpcWireAddress::fromRaw(addr),
718 };
719
Steven Moreland5553ac42020-11-11 02:14:45 +0000720 {
Steven Moreland67f85902023-03-15 01:13:49 +0000721 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000722 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
723 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700724 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
725 "Sending dec strong on unknown address %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000726
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000727 LOG_ALWAYS_FATAL_IF(it->second.timesRecd < target, "Can't dec count of %zu to %zu.",
728 it->second.timesRecd, target);
729
730 // typically this happens when multiple threads send dec refs at the
731 // same time - the transactions will get combined automatically
732 if (it->second.timesRecd == target) return OK;
733
734 body.amount = it->second.timesRecd - target;
735 it->second.timesRecd = target;
736
Steven Moreland67f85902023-03-15 01:13:49 +0000737 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(session, std::move(_l), it),
Steven Moreland31bde7a2021-06-04 00:57:36 +0000738 "Bad state. RpcState shouldn't own received binder");
Steven Moreland67f85902023-03-15 01:13:49 +0000739 // LOCK ALREADY RELEASED
Steven Moreland5553ac42020-11-11 02:14:45 +0000740 }
741
742 RpcWireHeader cmd = {
743 .command = RPC_COMMAND_DEC_STRONG,
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000744 .bodySize = sizeof(RpcDecStrong),
Steven Moreland5553ac42020-11-11 02:14:45 +0000745 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000746 iovec iovs[]{{&cmd, sizeof(cmd)}, {&body, sizeof(body)}};
Devin Moore695368f2022-06-03 22:29:14 +0000747 return rpcSend(connection, session, "dec ref", iovs, arraysize(iovs), std::nullopt);
Steven Moreland5553ac42020-11-11 02:14:45 +0000748}
749
Steven Moreland5ae62562021-06-10 03:21:42 +0000750status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
751 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700752 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000753
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000754 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000755 RpcWireHeader command;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000756 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000757 if (status_t status =
758 rpcRec(connection, session, "command header (for server)", &iov, 1,
759 enableAncillaryFds(session->getFileDescriptorTransportMode()) ? &ancillaryFds
760 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000761 status != OK)
762 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000763
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000764 return processCommand(connection, session, command, type, std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000765}
766
Steven Moreland5ae62562021-06-10 03:21:42 +0000767status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
768 const sp<RpcSession>& session, CommandType type) {
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000769 while (true) {
Andrei Homescu1975aaa2022-03-19 02:34:57 +0000770 status_t status = connection->rpcTransport->pollRead();
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000771 if (status == WOULD_BLOCK) break;
772 if (status != OK) return status;
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000773
774 status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000775 if (status != OK) return status;
776 }
777 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000778}
779
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000780status_t RpcState::processCommand(
781 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
782 const RpcWireHeader& command, CommandType type,
783 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland32150282021-11-12 22:54:53 +0000784#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000785 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
786 IPCThreadState::SpGuard spGuard{
787 .address = __builtin_frame_address(0),
Steven Morelande42ffd02022-07-06 21:46:23 +0000788 .context = "processing binder RPC command (where RpcServer::setPerSessionRootObject is "
789 "used to distinguish callers)",
Steven Morelandd7302072021-05-15 01:32:04 +0000790 };
791 const IPCThreadState::SpGuard* origGuard;
792 if (kernelBinderState != nullptr) {
793 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
794 }
Steven Moreland32150282021-11-12 22:54:53 +0000795
796 base::ScopeGuard guardUnguard = [&]() {
Steven Morelandd7302072021-05-15 01:32:04 +0000797 if (kernelBinderState != nullptr) {
798 kernelBinderState->restoreGetCallingSpGuard(origGuard);
799 }
800 };
Steven Moreland32150282021-11-12 22:54:53 +0000801#endif // BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000802
Steven Moreland5553ac42020-11-11 02:14:45 +0000803 switch (command.command) {
804 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000805 if (type != CommandType::ANY) return BAD_TYPE;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000806 return processTransact(connection, session, command, std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000807 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000808 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000809 }
810
811 // We should always know the version of the opposing side, and since the
812 // RPC-binder-level wire protocol is not self synchronizing, we have no way
813 // to understand where the current command ends and the next one begins. We
814 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000815 // to kill us, so ending the session for misbehaving client.
816 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000817 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000818 return DEAD_OBJECT;
819}
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000820status_t RpcState::processTransact(
821 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
822 const RpcWireHeader& command,
823 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000824 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
825
Steven Morelanddbe71832021-05-12 23:31:00 +0000826 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000827 if (!transactionData.valid()) {
828 return NO_MEMORY;
829 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000830 iovec iov{transactionData.data(), transactionData.size()};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000831 if (status_t status = rpcRec(connection, session, "transaction body", &iov, 1, nullptr);
832 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000833 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000834
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000835 return processTransactInternal(connection, session, std::move(transactionData),
836 std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000837}
838
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000839static void do_nothing_to_transact_data(const uint8_t* data, size_t dataSize,
Steven Moreland438cce82021-04-02 18:04:08 +0000840 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland438cce82021-04-02 18:04:08 +0000841 (void)data;
842 (void)dataSize;
843 (void)objects;
844 (void)objectsCount;
845}
846
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000847status_t RpcState::processTransactInternal(
848 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
849 CommandData transactionData,
850 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Morelandada72bd2021-06-09 23:29:13 +0000851 // for 'recursive' calls to this, we have already read and processed the
852 // binder from the transaction data and taken reference counts into account,
853 // so it is cached here.
Steven Moreland3903bf02021-09-27 16:05:24 -0700854 sp<IBinder> target;
Steven Morelandada72bd2021-06-09 23:29:13 +0000855processTransactInternalTailCall:
856
Steven Moreland5553ac42020-11-11 02:14:45 +0000857 if (transactionData.size() < sizeof(RpcWireTransaction)) {
858 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
859 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000860 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000861 return BAD_VALUE;
862 }
863 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
864
Steven Moreland5623d1a2021-09-10 15:45:34 -0700865 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000866 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000867
868 status_t replyStatus = OK;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700869 if (addr != 0) {
Steven Moreland3903bf02021-09-27 16:05:24 -0700870 if (!target) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000871 replyStatus = onBinderEntering(session, addr, &target);
Steven Morelandf5174272021-05-25 00:39:28 +0000872 }
873
Steven Moreland7227c8a2021-06-02 00:24:32 +0000874 if (replyStatus != OK) {
875 // do nothing
876 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000877 // This can happen if the binder is remote in this process, and
878 // another thread has called the last decStrong on this binder.
879 // However, for local binders, it indicates a misbehaving client
880 // (any binder which is being transacted on should be holding a
881 // strong ref count), so in either case, terminating the
882 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700883 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
884 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000885 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000886 replyStatus = BAD_VALUE;
887 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700888 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
889 ". Terminating!",
890 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000891 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000892 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000893 } else if (oneway) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000894 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000895 auto it = mNodeForAddress.find(addr);
896 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700897 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000898 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000899 } else if (transaction->asyncNumber != it->second.asyncNumber) {
900 // we need to process some other asynchronous transaction
901 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000902 it->second.asyncTodo.push(BinderNode::AsyncTodo{
903 .ref = target,
904 .data = std::move(transactionData),
Frederick Mayleb0221d12022-10-03 23:10:53 +0000905 .ancillaryFds = std::move(ancillaryFds),
Steven Morelandf5174272021-05-25 00:39:28 +0000906 .asyncNumber = transaction->asyncNumber,
907 });
Steven Morelandd45be622021-06-04 02:19:37 +0000908
909 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700910 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
911 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000912
913 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
914 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
915 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
916
917 if (numPending >= kArbitraryOnewayCallWarnLevel) {
918 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
919 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
920 _l.unlock();
921 (void)session->shutdownAndWait(false);
922 return FAILED_TRANSACTION;
923 }
924
925 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
926 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
927 target.get(), numPending);
928 }
929 }
Steven Morelandf5174272021-05-25 00:39:28 +0000930 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000931 }
932 }
933 }
934
Steven Moreland5553ac42020-11-11 02:14:45 +0000935 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000936 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000937
938 if (replyStatus == OK) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000939 Span<const uint8_t> parcelSpan = {transaction->data,
940 transactionData.size() -
941 offsetof(RpcWireTransaction, data)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000942 Span<const uint32_t> objectTableSpan;
Steven Moreland28c87282023-04-14 21:03:01 +0000943 if (session->getProtocolVersion().value() >=
Frederick Mayledc07cf82022-05-26 20:30:12 +0000944 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000945 std::optional<Span<const uint8_t>> objectTableBytes =
946 parcelSpan.splitOff(transaction->parcelDataSize);
947 if (!objectTableBytes.has_value()) {
948 ALOGE("Parcel size (%" PRId32 ") greater than available bytes (%zu). Terminating!",
949 transaction->parcelDataSize, parcelSpan.byteSize());
950 (void)session->shutdownAndWait(false);
951 return BAD_VALUE;
952 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000953 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000954 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000955 if (!maybeSpan.has_value()) {
956 ALOGE("Bad object table size inferred from RpcWireTransaction. Saw bodySize=%zu "
957 "sizeofHeader=%zu parcelSize=%" PRId32
958 " objectTableBytesSize=%zu. Terminating!",
959 transactionData.size(), sizeof(RpcWireTransaction),
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000960 transaction->parcelDataSize, objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000961 return BAD_VALUE;
962 }
963 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000964 }
965
Steven Morelandeff77c12021-04-15 00:37:19 +0000966 Parcel data;
967 // transaction->data is owned by this function. Parcel borrows this data and
968 // only holds onto it for the duration of this function call. Parcel will be
969 // deleted before the 'transactionData' object.
Frederick Mayledc07cf82022-05-26 20:30:12 +0000970
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000971 replyStatus =
972 data.rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
973 objectTableSpan.data, objectTableSpan.size,
974 std::move(ancillaryFds), do_nothing_to_transact_data);
975 // Reset to avoid spurious use-after-move warning from clang-tidy.
976 ancillaryFds = std::remove_reference<decltype(ancillaryFds)>::type();
Steven Morelandeff77c12021-04-15 00:37:19 +0000977
Frederick Mayle69a0c992022-05-26 20:38:39 +0000978 if (replyStatus == OK) {
979 if (target) {
980 bool origAllowNested = connection->allowNested;
981 connection->allowNested = !oneway;
Steven Morelandc7d40132021-06-10 03:42:11 +0000982
Frederick Mayle69a0c992022-05-26 20:38:39 +0000983 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000984
Frederick Mayle69a0c992022-05-26 20:38:39 +0000985 connection->allowNested = origAllowNested;
986 } else {
987 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000988
Frederick Mayle69a0c992022-05-26 20:38:39 +0000989 switch (transaction->code) {
990 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
991 replyStatus = reply.writeInt32(session->getMaxIncomingThreads());
992 break;
993 }
994 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
995 // for client connections, this should always report the value
996 // originally returned from the server, so this is asserting
997 // that it exists
998 replyStatus = reply.writeByteVector(session->mId);
999 break;
1000 }
1001 default: {
1002 sp<RpcServer> server = session->server();
1003 if (server) {
1004 switch (transaction->code) {
1005 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
1006 sp<IBinder> root = session->mSessionSpecificRootObject
1007 ?: server->getRootObject();
1008 replyStatus = reply.writeStrongBinder(root);
1009 break;
1010 }
1011 default: {
1012 replyStatus = UNKNOWN_TRANSACTION;
1013 }
Steven Moreland103424e2021-06-02 18:16:19 +00001014 }
Frederick Mayle69a0c992022-05-26 20:38:39 +00001015 } else {
1016 ALOGE("Special command sent, but no server object attached.");
Steven Moreland103424e2021-06-02 18:16:19 +00001017 }
Steven Morelandf137de92021-04-24 01:54:26 +00001018 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001019 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001020 }
1021 }
1022 }
1023
Steven Morelandc7d40132021-06-10 03:42:11 +00001024 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001025 if (replyStatus != OK) {
1026 ALOGW("Oneway call failed with error: %d", replyStatus);
1027 }
1028
Steven Moreland5623d1a2021-09-10 15:45:34 -07001029 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
1030 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001031
1032 // Check to see if there is another asynchronous transaction to process.
1033 // This behavior differs from binder behavior, since in the binder
1034 // driver, asynchronous transactions will be processed after existing
1035 // pending binder transactions on the queue. The downside of this is
1036 // that asynchronous transactions can be drowned out by synchronous
1037 // transactions. However, we have no easy way to queue these
1038 // transactions after the synchronous transactions we may want to read
1039 // from the wire. So, in socket binder here, we have the opposite
1040 // downside: asynchronous transactions may drown out synchronous
1041 // transactions.
1042 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001043 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001044 auto it = mNodeForAddress.find(addr);
1045 // last refcount dropped after this transaction happened
1046 if (it == mNodeForAddress.end()) return OK;
1047
Steven Morelandc9d7b532021-06-04 20:57:41 +00001048 if (!nodeProgressAsyncNumber(&it->second)) {
1049 _l.unlock();
1050 (void)session->shutdownAndWait(false);
1051 return DEAD_OBJECT;
1052 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001053
Andrei Homescuae5f0d12023-02-25 05:03:31 +00001054 if (it->second.asyncTodo.size() != 0 &&
1055 it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001056 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
1057 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001058
1059 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +00001060 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +00001061 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +00001062 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
1063
Steven Morelandada72bd2021-06-09 23:29:13 +00001064 // reset up arguments
1065 transactionData = std::move(todo.data);
Frederick Mayleb0221d12022-10-03 23:10:53 +00001066 ancillaryFds = std::move(todo.ancillaryFds);
Steven Moreland3903bf02021-09-27 16:05:24 -07001067 LOG_ALWAYS_FATAL_IF(target != todo.ref,
1068 "async list should be associated with a binder");
Steven Morelandf5174272021-05-25 00:39:28 +00001069
Steven Moreland5553ac42020-11-11 02:14:45 +00001070 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +00001071 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +00001072 }
1073 }
Steven Morelandd8083312021-09-22 13:37:10 -07001074
1075 // done processing all the async commands on this binder that we can, so
1076 // write decstrongs on the binder
1077 if (addr != 0 && replyStatus == OK) {
1078 return flushExcessBinderRefs(session, addr, target);
1079 }
1080
Steven Moreland5553ac42020-11-11 02:14:45 +00001081 return OK;
1082 }
1083
Steven Moreland6709cf42021-09-30 15:21:54 -07001084 // Binder refs are flushed for oneway calls only after all calls which are
1085 // built up are executed. Otherwise, they fill up the binder buffer.
1086 if (addr != 0 && replyStatus == OK) {
1087 replyStatus = flushExcessBinderRefs(session, addr, target);
1088 }
1089
Frederick Mayle69a0c992022-05-26 20:38:39 +00001090 std::string errorMsg;
1091 if (status_t status = validateParcel(session, reply, &errorMsg); status != OK) {
1092 ALOGE("Reply Parcel failed validation: %s", errorMsg.c_str());
1093 // Forward the error to the client of the transaction.
1094 reply.freeData();
1095 reply.markForRpc(session);
1096 replyStatus = status;
1097 }
1098
1099 auto* rpcFields = reply.maybeRpcFields();
1100 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
1101
Frederick Mayledc07cf82022-05-26 20:30:12 +00001102 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
1103
Frederick Mayle69a0c992022-05-26 20:38:39 +00001104 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
1105 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +00001106
Frederick Mayle778c0902022-05-27 01:14:57 +00001107 uint32_t bodySize;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001108 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(rpcReplyWireSize, reply.dataSize(), &bodySize) ||
1109 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
1110 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +00001111 "Too much data for reply %zu", reply.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +00001112 RpcWireHeader cmdReply{
1113 .command = RPC_COMMAND_REPLY,
Frederick Mayle778c0902022-05-27 01:14:57 +00001114 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +00001115 };
Steven Moreland5553ac42020-11-11 02:14:45 +00001116 RpcWireReply rpcReply{
1117 .status = replyStatus,
Frederick Mayledc07cf82022-05-26 20:30:12 +00001118 // NOTE: Not necessarily written to socket depending on session
1119 // version.
1120 // NOTE: bodySize didn't overflow => this cast is safe
1121 .parcelDataSize = static_cast<uint32_t>(reply.dataSize()),
1122 .reserved = {0, 0, 0},
Steven Moreland5553ac42020-11-11 02:14:45 +00001123 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001124 iovec iovs[]{
1125 {&cmdReply, sizeof(RpcWireHeader)},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001126 {&rpcReply, rpcReplyWireSize},
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001127 {const_cast<uint8_t*>(reply.data()), reply.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001128 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001129 };
Frederick Mayle69a0c992022-05-26 20:38:39 +00001130 return rpcSend(connection, session, "reply", iovs, arraysize(iovs), std::nullopt,
1131 rpcFields->mFds.get());
Steven Moreland5553ac42020-11-11 02:14:45 +00001132}
1133
Steven Moreland5ae62562021-06-10 03:21:42 +00001134status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
1135 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001136 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
1137
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001138 if (command.bodySize != sizeof(RpcDecStrong)) {
1139 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcDecStrong. Terminating!",
1140 sizeof(RpcDecStrong), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001141 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001142 return BAD_VALUE;
1143 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001144
Frederick Mayleb86cda42022-06-09 23:17:45 +00001145 RpcDecStrong body;
1146 iovec iov{&body, sizeof(RpcDecStrong)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001147 if (status_t status = rpcRec(connection, session, "dec ref body", &iov, 1, nullptr);
1148 status != OK)
Frederick Mayleb86cda42022-06-09 23:17:45 +00001149 return status;
1150
1151 uint64_t addr = RpcWireAddress::toRaw(body.address);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001152 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001153 auto it = mNodeForAddress.find(addr);
1154 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001155 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001156 return OK;
1157 }
1158
1159 sp<IBinder> target = it->second.binder.promote();
1160 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001161 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
1162 ". Terminating!",
1163 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001164 _l.unlock();
1165 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001166 return BAD_VALUE;
1167 }
1168
Frederick Mayleb86cda42022-06-09 23:17:45 +00001169 if (it->second.timesSent < body.amount) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001170 ALOGE("Record of sending binder %zu times, but requested decStrong for %" PRIu64 " of %u",
Frederick Mayleb86cda42022-06-09 23:17:45 +00001171 it->second.timesSent, addr, body.amount);
Steven Moreland5553ac42020-11-11 02:14:45 +00001172 return OK;
1173 }
1174
Steven Moreland5623d1a2021-09-10 15:45:34 -07001175 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
1176 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001177
Frederick Mayleb86cda42022-06-09 23:17:45 +00001178 LOG_RPC_DETAIL("Processing dec strong of %" PRIu64 " by %u from %zu", addr, body.amount,
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001179 it->second.timesSent);
1180
Frederick Mayleb86cda42022-06-09 23:17:45 +00001181 it->second.timesSent -= body.amount;
Steven Moreland67f85902023-03-15 01:13:49 +00001182 sp<IBinder> tempHold = tryEraseNode(session, std::move(_l), it);
1183 // LOCK ALREADY RELEASED
Steven Moreland31bde7a2021-06-04 00:57:36 +00001184 tempHold = nullptr; // destructor may make binder calls on this session
1185
1186 return OK;
1187}
1188
Frederick Mayle69a0c992022-05-26 20:38:39 +00001189status_t RpcState::validateParcel(const sp<RpcSession>& session, const Parcel& parcel,
1190 std::string* errorMsg) {
1191 auto* rpcFields = parcel.maybeRpcFields();
1192 if (rpcFields == nullptr) {
1193 *errorMsg = "Parcel not crafted for RPC call";
1194 return BAD_TYPE;
1195 }
1196
1197 if (rpcFields->mSession != session) {
1198 *errorMsg = "Parcel's session doesn't match";
1199 return BAD_TYPE;
1200 }
1201
1202 uint32_t protocolVersion = session->getProtocolVersion().value();
1203 if (protocolVersion < RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE &&
1204 !rpcFields->mObjectPositions.empty()) {
1205 *errorMsg = StringPrintf("Parcel has attached objects but the session's protocol version "
1206 "(%" PRIu32 ") is too old, must be at least %" PRIu32,
1207 protocolVersion,
1208 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE);
1209 return BAD_VALUE;
1210 }
1211
1212 if (rpcFields->mFds && !rpcFields->mFds->empty()) {
1213 switch (session->getFileDescriptorTransportMode()) {
1214 case RpcSession::FileDescriptorTransportMode::NONE:
1215 *errorMsg =
1216 "Parcel has file descriptors, but no file descriptor transport is enabled";
1217 return FDS_NOT_ALLOWED;
1218 case RpcSession::FileDescriptorTransportMode::UNIX: {
1219 constexpr size_t kMaxFdsPerMsg = 253;
1220 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
1221 *errorMsg = StringPrintf("Too many file descriptors in Parcel for unix "
1222 "domain socket: %zu (max is %zu)",
1223 rpcFields->mFds->size(), kMaxFdsPerMsg);
1224 return BAD_VALUE;
1225 }
Andrei Homescu1c18a802022-08-17 04:59:01 +00001226 break;
1227 }
1228 case RpcSession::FileDescriptorTransportMode::TRUSTY: {
1229 // Keep this in sync with trusty_ipc.h!!!
1230 // We could import that file here on Trusty, but it's not
1231 // available on Android
1232 constexpr size_t kMaxFdsPerMsg = 8;
1233 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
1234 *errorMsg = StringPrintf("Too many file descriptors in Parcel for Trusty "
1235 "IPC connection: %zu (max is %zu)",
1236 rpcFields->mFds->size(), kMaxFdsPerMsg);
1237 return BAD_VALUE;
1238 }
1239 break;
Frederick Mayle69a0c992022-05-26 20:38:39 +00001240 }
1241 }
1242 }
1243
1244 return OK;
1245}
1246
Steven Moreland67f85902023-03-15 01:13:49 +00001247sp<IBinder> RpcState::tryEraseNode(const sp<RpcSession>& session, RpcMutexUniqueLock nodeLock,
1248 std::map<uint64_t, BinderNode>::iterator& it) {
1249 bool shouldShutdown = false;
1250
Steven Moreland31bde7a2021-06-04 00:57:36 +00001251 sp<IBinder> ref;
1252
Steven Moreland5553ac42020-11-11 02:14:45 +00001253 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001254 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +00001255
1256 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +00001257 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
1258 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +00001259 mNodeForAddress.erase(it);
Steven Moreland67f85902023-03-15 01:13:49 +00001260
1261 if (mNodeForAddress.size() == 0) {
1262 shouldShutdown = true;
1263 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001264 }
1265 }
1266
Steven Moreland67f85902023-03-15 01:13:49 +00001267 // If we shutdown, prevent RpcState from being re-used. This prevents another
1268 // thread from getting the root object again.
1269 if (shouldShutdown) {
1270 clear(std::move(nodeLock));
1271 } else {
1272 nodeLock.unlock(); // explicit
1273 }
1274 // LOCK IS RELEASED
1275
1276 if (shouldShutdown) {
1277 ALOGI("RpcState has no binders left, so triggering shutdown...");
1278 (void)session->shutdownAndWait(false);
1279 }
1280
Steven Moreland31bde7a2021-06-04 00:57:36 +00001281 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +00001282}
1283
Steven Morelandc9d7b532021-06-04 20:57:41 +00001284bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +00001285 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
1286 // a single binder
1287 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
1288 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +00001289 return false;
1290 }
1291 node->asyncNumber++;
1292 return true;
1293}
1294
Steven Moreland5553ac42020-11-11 02:14:45 +00001295} // namespace android