blob: 4d4830920cc60f431b3bc323bb28894798e53375 [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() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000265 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000266
267 if (mTerminated) {
268 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
269 "New state should be impossible after terminating!");
270 return;
271 }
Steven Moreland0092fe32022-07-15 00:15:34 +0000272 mTerminated = true;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000273
274 if (SHOULD_LOG_RPC_DETAIL) {
275 ALOGE("RpcState::clear()");
276 dumpLocked();
277 }
278
Steven Moreland0092fe32022-07-15 00:15:34 +0000279 // invariants
Steven Morelandc9d7b532021-06-04 20:57:41 +0000280 for (auto& [address, node] : mNodeForAddress) {
Steven Moreland0092fe32022-07-15 00:15:34 +0000281 bool guaranteedHaveBinder = node.timesSent > 0;
282 if (guaranteedHaveBinder) {
283 LOG_ALWAYS_FATAL_IF(node.sentRef == nullptr,
284 "Binder expected to be owned with address: %" PRIu64 " %s", address,
285 node.toString().c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000286 }
287 }
288
Steven Moreland0092fe32022-07-15 00:15:34 +0000289 // if the destructor of a binder object makes another RPC call, then calling
290 // decStrong could deadlock. So, we must hold onto these binders until
291 // mNodeMutex is no longer taken.
292 auto temp = std::move(mNodeForAddress);
293 mNodeForAddress.clear(); // RpcState isn't reusable, but for future/explicit
Steven Morelandc9d7b532021-06-04 20:57:41 +0000294
295 _l.unlock();
Steven Moreland0092fe32022-07-15 00:15:34 +0000296 temp.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000297}
298
299void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000300 ALOGE("DUMP OF RpcState %p", this);
301 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
302 for (const auto& [address, node] : mNodeForAddress) {
Steven Moreland3fa32922022-07-14 18:45:51 +0000303 ALOGE("- address: %" PRIu64 " %s", address, node.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000304 }
305 ALOGE("END DUMP OF RpcState");
306}
307
Steven Moreland3fa32922022-07-14 18:45:51 +0000308std::string RpcState::BinderNode::toString() const {
309 sp<IBinder> strongBinder = this->binder.promote();
310
311 const char* desc;
312 if (strongBinder) {
313 if (strongBinder->remoteBinder()) {
314 if (strongBinder->remoteBinder()->isRpcBinder()) {
315 desc = "(rpc binder proxy)";
316 } else {
317 desc = "(binder proxy)";
318 }
319 } else {
320 desc = "(local binder)";
321 }
322 } else {
323 desc = "(not promotable)";
324 }
325
326 return StringPrintf("node{%p times sent: %zu times recd: %zu type: %s}",
327 this->binder.unsafe_get(), this->timesSent, this->timesRecd, desc);
328}
Steven Moreland5553ac42020-11-11 02:14:45 +0000329
Steven Morelanddbe71832021-05-12 23:31:00 +0000330RpcState::CommandData::CommandData(size_t size) : mSize(size) {
331 // The maximum size for regular binder is 1MB for all concurrent
332 // transactions. A very small proportion of transactions are even
333 // larger than a page, but we need to avoid allocating too much
334 // data on behalf of an arbitrary client, or we could risk being in
335 // a position where a single additional allocation could run out of
336 // memory.
337 //
338 // Note, this limit may not reflect the total amount of data allocated for a
339 // transaction (in some cases, additional fixed size amounts are added),
340 // though for rough consistency, we should avoid cases where this data type
341 // is used for multiple dynamic allocations for a single transaction.
342 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
343 if (size == 0) return;
344 if (size > kMaxTransactionAllocation) {
345 ALOGW("Transaction requested too much data allocation %zu", size);
346 return;
347 }
348 mData.reset(new (std::nothrow) uint8_t[size]);
349}
350
Frederick Mayle69a0c992022-05-26 20:38:39 +0000351status_t RpcState::rpcSend(
352 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
353 const char* what, iovec* iovs, int niovs,
354 const std::optional<android::base::function_ref<status_t()>>& altPoll,
355 const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800356 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000357 LOG_RPC_DETAIL("Sending %s (part %d of %d) on RpcTransport %p: %s",
358 what, i + 1, niovs, connection->rpcTransport.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000359 android::base::HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000360 }
361
Yifan Hong702115c2021-06-24 15:39:18 -0700362 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700363 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
Frederick Mayle69a0c992022-05-26 20:38:39 +0000364 iovs, niovs, altPoll,
365 ancillaryFds);
Steven Moreland798e0d12021-07-14 23:19:25 +0000366 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800367 LOG_RPC_DETAIL("Failed to write %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700368 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000369 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000370 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000371 }
372
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000373 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000374}
375
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000376status_t RpcState::rpcRec(
377 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
378 const char* what, iovec* iovs, int niovs,
379 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
380 if (status_t status =
381 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
382 iovs, niovs, std::nullopt,
383 ancillaryFds);
Steven Morelandee3f4662021-05-22 01:07:33 +0000384 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800385 LOG_RPC_DETAIL("Failed to read %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700386 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandae58f432021-08-05 17:53:16 -0700387 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000388 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000389 }
390
Colin Cross9adfeaf2022-01-21 17:22:09 -0800391 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000392 LOG_RPC_DETAIL("Received %s (part %d of %d) on RpcTransport %p: %s",
393 what, i + 1, niovs, connection->rpcTransport.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000394 android::base::HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
395 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000396 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000397}
398
Steven Morelandbf57bce2021-07-26 15:26:12 -0700399status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
400 const sp<RpcSession>& session, uint32_t* version) {
401 RpcNewSessionResponse response;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000402 iovec iov{&response, sizeof(response)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000403 if (status_t status = rpcRec(connection, session, "new session response", &iov, 1, nullptr);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700404 status != OK) {
405 return status;
406 }
407 *version = response.version;
408 return OK;
409}
410
Steven Moreland5ae62562021-06-10 03:21:42 +0000411status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
412 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000413 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000414 .msg = RPC_CONNECTION_INIT_OKAY,
415 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000416 iovec iov{&init, sizeof(init)};
Devin Moore695368f2022-06-03 22:29:14 +0000417 return rpcSend(connection, session, "connection init", &iov, 1, std::nullopt);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000418}
419
Steven Moreland5ae62562021-06-10 03:21:42 +0000420status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
421 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000422 RpcOutgoingConnectionInit init;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000423 iovec iov{&init, sizeof(init)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000424 if (status_t status = rpcRec(connection, session, "connection init", &iov, 1, nullptr);
425 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000426 return status;
427
428 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
429 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
430 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
431 init.msg);
432 return BAD_VALUE;
433 }
434 return OK;
435}
436
Steven Moreland5ae62562021-06-10 03:21:42 +0000437sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
438 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000439 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000440 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000441 Parcel reply;
442
Steven Moreland5623d1a2021-09-10 15:45:34 -0700443 status_t status =
444 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000445 if (status != OK) {
446 ALOGE("Error getting root object: %s", statusToString(status).c_str());
447 return nullptr;
448 }
449
450 return reply.readStrongBinder();
451}
452
Steven Moreland5ae62562021-06-10 03:21:42 +0000453status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
454 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000455 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000456 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000457 Parcel reply;
458
Steven Moreland5623d1a2021-09-10 15:45:34 -0700459 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
460 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000461 if (status != OK) {
462 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
463 return status;
464 }
465
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000466 int32_t maxThreads;
467 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000468 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000469 if (maxThreads <= 0) {
470 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000471 return BAD_VALUE;
472 }
473
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000474 *maxThreadsOut = maxThreads;
475 return OK;
476}
477
Steven Moreland5ae62562021-06-10 03:21:42 +0000478status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700479 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000480 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000481 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000482 Parcel reply;
483
Steven Moreland5623d1a2021-09-10 15:45:34 -0700484 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
485 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000486 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000487 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000488 return status;
489 }
490
Steven Moreland826367f2021-09-10 14:05:31 -0700491 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000492}
493
Steven Moreland5ae62562021-06-10 03:21:42 +0000494status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
495 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
496 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000497 std::string errorMsg;
498 if (status_t status = validateParcel(session, data, &errorMsg); status != OK) {
499 ALOGE("Refusing to send RPC on binder %p code %" PRIu32 ": Parcel %p failed validation: %s",
500 binder.get(), code, &data, errorMsg.c_str());
501 return status;
Steven Morelandf5174272021-05-25 00:39:28 +0000502 }
Steven Moreland5623d1a2021-09-10 15:45:34 -0700503 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000504 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
505
Steven Moreland5ae62562021-06-10 03:21:42 +0000506 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000507}
508
Steven Moreland5ae62562021-06-10 03:21:42 +0000509status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700510 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000511 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000512 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
513 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
514
Steven Moreland5553ac42020-11-11 02:14:45 +0000515 uint64_t asyncNumber = 0;
516
Steven Moreland5623d1a2021-09-10 15:45:34 -0700517 if (address != 0) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000518 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000519 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
520 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700521 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
522 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000523
524 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000525 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000526 if (!nodeProgressAsyncNumber(&it->second)) {
527 _l.unlock();
528 (void)session->shutdownAndWait(false);
529 return DEAD_OBJECT;
530 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000531 }
532 }
533
Frederick Mayle69a0c992022-05-26 20:38:39 +0000534 auto* rpcFields = data.maybeRpcFields();
535 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
536
537 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
538 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +0000539
Frederick Mayle778c0902022-05-27 01:14:57 +0000540 uint32_t bodySize;
541 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(sizeof(RpcWireTransaction), data.dataSize(),
Frederick Mayledc07cf82022-05-26 20:30:12 +0000542 &bodySize) ||
543 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
544 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +0000545 "Too much data %zu", data.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +0000546 RpcWireHeader command{
547 .command = RPC_COMMAND_TRANSACT,
Frederick Mayle778c0902022-05-27 01:14:57 +0000548 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +0000549 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700550
Steven Moreland5553ac42020-11-11 02:14:45 +0000551 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700552 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000553 .code = code,
554 .flags = flags,
555 .asyncNumber = asyncNumber,
Frederick Mayledc07cf82022-05-26 20:30:12 +0000556 // bodySize didn't overflow => this cast is safe
557 .parcelDataSize = static_cast<uint32_t>(data.dataSize()),
Steven Moreland5553ac42020-11-11 02:14:45 +0000558 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000559
Steven Moreland43921d52021-09-27 17:15:56 -0700560 constexpr size_t kWaitMaxUs = 1000000;
561 constexpr size_t kWaitLogUs = 10000;
562 size_t waitUs = 0;
563
564 // Oneway calls have no sync point, so if many are sent before, whether this
565 // is a twoway or oneway transaction, they may have filled up the socket.
Devin Moore695368f2022-06-03 22:29:14 +0000566 // So, make sure we drain them before polling
Steven Moreland43921d52021-09-27 17:15:56 -0700567
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000568 iovec iovs[]{
569 {&command, sizeof(RpcWireHeader)},
570 {&transaction, sizeof(RpcWireTransaction)},
571 {const_cast<uint8_t*>(data.data()), data.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +0000572 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000573 };
Frederick Mayle69a0c992022-05-26 20:38:39 +0000574 if (status_t status = rpcSend(
575 connection, session, "transaction", iovs, arraysize(iovs),
576 [&] {
577 if (waitUs > kWaitLogUs) {
578 ALOGE("Cannot send command, trying to process pending refcounts. Waiting "
579 "%zuus. Too many oneway calls?",
580 waitUs);
581 }
Devin Moore695368f2022-06-03 22:29:14 +0000582
Frederick Mayle69a0c992022-05-26 20:38:39 +0000583 if (waitUs > 0) {
584 usleep(waitUs);
585 waitUs = std::min(kWaitMaxUs, waitUs * 2);
586 } else {
587 waitUs = 1;
588 }
Devin Moore695368f2022-06-03 22:29:14 +0000589
Frederick Mayle69a0c992022-05-26 20:38:39 +0000590 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
591 },
592 rpcFields->mFds.get());
Steven Moreland43921d52021-09-27 17:15:56 -0700593 status != OK) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000594 // TODO(b/167966510): need to undo onBinderLeaving - we know the
595 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000596 return status;
Steven Moreland43921d52021-09-27 17:15:56 -0700597 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000598
599 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700600 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
601 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000602
603 // Do not wait on result.
Steven Moreland43921d52021-09-27 17:15:56 -0700604 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000605 }
606
607 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
608
Steven Moreland5ae62562021-06-10 03:21:42 +0000609 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000610}
611
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000612static void cleanup_reply_data(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
613 size_t objectsCount) {
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000614 delete[] const_cast<uint8_t*>(data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000615 (void)dataSize;
616 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000617 (void)objectsCount;
Steven Moreland5553ac42020-11-11 02:14:45 +0000618}
619
Steven Moreland5ae62562021-06-10 03:21:42 +0000620status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
621 const sp<RpcSession>& session, Parcel* reply) {
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000622 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000623 RpcWireHeader command;
624 while (true) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000625 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000626 if (status_t status = rpcRec(connection, session, "command header (for reply)", &iov, 1,
627 enableAncillaryFds(session->getFileDescriptorTransportMode())
628 ? &ancillaryFds
629 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000630 status != OK)
631 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000632
633 if (command.command == RPC_COMMAND_REPLY) break;
634
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000635 if (status_t status = processCommand(connection, session, command, CommandType::ANY,
636 std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000637 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000638 return status;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000639
640 // Reset to avoid spurious use-after-move warning from clang-tidy.
641 ancillaryFds = decltype(ancillaryFds)();
Steven Moreland5553ac42020-11-11 02:14:45 +0000642 }
643
Frederick Mayledc07cf82022-05-26 20:30:12 +0000644 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
645
646 if (command.bodySize < rpcReplyWireSize) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000647 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
648 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000649 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000650 return BAD_VALUE;
651 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000652
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000653 RpcWireReply rpcReply;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000654 memset(&rpcReply, 0, sizeof(RpcWireReply)); // zero because of potential short read
655
656 CommandData data(command.bodySize - rpcReplyWireSize);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000657 if (!data.valid()) return NO_MEMORY;
658
659 iovec iovs[]{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000660 {&rpcReply, rpcReplyWireSize},
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000661 {data.data(), data.size()},
662 };
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000663 if (status_t status = rpcRec(connection, session, "reply body", iovs, arraysize(iovs), nullptr);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000664 status != OK)
665 return status;
Frederick Mayle69a0c992022-05-26 20:38:39 +0000666
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000667 if (rpcReply.status != OK) return rpcReply.status;
668
Frederick Mayledc07cf82022-05-26 20:30:12 +0000669 Span<const uint8_t> parcelSpan = {data.data(), data.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000670 Span<const uint32_t> objectTableSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000671 if (session->getProtocolVersion().value() >=
672 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000673 std::optional<Span<const uint8_t>> objectTableBytes =
674 parcelSpan.splitOff(rpcReply.parcelDataSize);
675 if (!objectTableBytes.has_value()) {
676 ALOGE("Parcel size larger than available bytes: %" PRId32 " vs %zu. Terminating!",
677 rpcReply.parcelDataSize, parcelSpan.byteSize());
678 (void)session->shutdownAndWait(false);
679 return BAD_VALUE;
680 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000681 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000682 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000683 if (!maybeSpan.has_value()) {
684 ALOGE("Bad object table size inferred from RpcWireReply. Saw bodySize=%" PRId32
685 " sizeofHeader=%zu parcelSize=%" PRId32 " objectTableBytesSize=%zu. Terminating!",
686 command.bodySize, rpcReplyWireSize, rpcReply.parcelDataSize,
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000687 objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000688 return BAD_VALUE;
689 }
690 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000691 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000692
Frederick Mayledc07cf82022-05-26 20:30:12 +0000693 data.release();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000694 return reply->rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
695 objectTableSpan.data, objectTableSpan.size,
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000696 std::move(ancillaryFds), cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000697}
698
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000699status_t RpcState::sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection,
700 const sp<RpcSession>& session, uint64_t addr,
701 size_t target) {
702 RpcDecStrong body = {
703 .address = RpcWireAddress::fromRaw(addr),
704 };
705
Steven Moreland5553ac42020-11-11 02:14:45 +0000706 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000707 RpcMutexLockGuard _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000708 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
709 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700710 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
711 "Sending dec strong on unknown address %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000712
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000713 LOG_ALWAYS_FATAL_IF(it->second.timesRecd < target, "Can't dec count of %zu to %zu.",
714 it->second.timesRecd, target);
715
716 // typically this happens when multiple threads send dec refs at the
717 // same time - the transactions will get combined automatically
718 if (it->second.timesRecd == target) return OK;
719
720 body.amount = it->second.timesRecd - target;
721 it->second.timesRecd = target;
722
Steven Moreland31bde7a2021-06-04 00:57:36 +0000723 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
724 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000725 }
726
727 RpcWireHeader cmd = {
728 .command = RPC_COMMAND_DEC_STRONG,
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000729 .bodySize = sizeof(RpcDecStrong),
Steven Moreland5553ac42020-11-11 02:14:45 +0000730 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000731 iovec iovs[]{{&cmd, sizeof(cmd)}, {&body, sizeof(body)}};
Devin Moore695368f2022-06-03 22:29:14 +0000732 return rpcSend(connection, session, "dec ref", iovs, arraysize(iovs), std::nullopt);
Steven Moreland5553ac42020-11-11 02:14:45 +0000733}
734
Steven Moreland5ae62562021-06-10 03:21:42 +0000735status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
736 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700737 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000738
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000739 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
Steven Moreland5553ac42020-11-11 02:14:45 +0000740 RpcWireHeader command;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000741 iovec iov{&command, sizeof(command)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000742 if (status_t status =
743 rpcRec(connection, session, "command header (for server)", &iov, 1,
744 enableAncillaryFds(session->getFileDescriptorTransportMode()) ? &ancillaryFds
745 : nullptr);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000746 status != OK)
747 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000748
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000749 return processCommand(connection, session, command, type, std::move(ancillaryFds));
Steven Moreland52eee942021-06-03 00:59:28 +0000750}
751
Steven Moreland5ae62562021-06-10 03:21:42 +0000752status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
753 const sp<RpcSession>& session, CommandType type) {
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000754 while (true) {
Andrei Homescu1975aaa2022-03-19 02:34:57 +0000755 status_t status = connection->rpcTransport->pollRead();
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000756 if (status == WOULD_BLOCK) break;
757 if (status != OK) return status;
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000758
759 status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000760 if (status != OK) return status;
761 }
762 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000763}
764
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000765status_t RpcState::processCommand(
766 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
767 const RpcWireHeader& command, CommandType type,
768 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland32150282021-11-12 22:54:53 +0000769#ifdef BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000770 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
771 IPCThreadState::SpGuard spGuard{
772 .address = __builtin_frame_address(0),
Steven Morelande42ffd02022-07-06 21:46:23 +0000773 .context = "processing binder RPC command (where RpcServer::setPerSessionRootObject is "
774 "used to distinguish callers)",
Steven Morelandd7302072021-05-15 01:32:04 +0000775 };
776 const IPCThreadState::SpGuard* origGuard;
777 if (kernelBinderState != nullptr) {
778 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
779 }
Steven Moreland32150282021-11-12 22:54:53 +0000780
781 base::ScopeGuard guardUnguard = [&]() {
Steven Morelandd7302072021-05-15 01:32:04 +0000782 if (kernelBinderState != nullptr) {
783 kernelBinderState->restoreGetCallingSpGuard(origGuard);
784 }
785 };
Steven Moreland32150282021-11-12 22:54:53 +0000786#endif // BINDER_WITH_KERNEL_IPC
Steven Morelandd7302072021-05-15 01:32:04 +0000787
Steven Moreland5553ac42020-11-11 02:14:45 +0000788 switch (command.command) {
789 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000790 if (type != CommandType::ANY) return BAD_TYPE;
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000791 return processTransact(connection, session, command, std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000792 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000793 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000794 }
795
796 // We should always know the version of the opposing side, and since the
797 // RPC-binder-level wire protocol is not self synchronizing, we have no way
798 // to understand where the current command ends and the next one begins. We
799 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000800 // to kill us, so ending the session for misbehaving client.
801 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000802 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000803 return DEAD_OBJECT;
804}
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000805status_t RpcState::processTransact(
806 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
807 const RpcWireHeader& command,
808 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000809 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
810
Steven Morelanddbe71832021-05-12 23:31:00 +0000811 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000812 if (!transactionData.valid()) {
813 return NO_MEMORY;
814 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000815 iovec iov{transactionData.data(), transactionData.size()};
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000816 if (status_t status = rpcRec(connection, session, "transaction body", &iov, 1, nullptr);
817 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000818 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000819
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000820 return processTransactInternal(connection, session, std::move(transactionData),
821 std::move(ancillaryFds));
Steven Moreland5553ac42020-11-11 02:14:45 +0000822}
823
Frederick Mayle53b6ffe2022-07-15 20:14:01 +0000824static void do_nothing_to_transact_data(const uint8_t* data, size_t dataSize,
Steven Moreland438cce82021-04-02 18:04:08 +0000825 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland438cce82021-04-02 18:04:08 +0000826 (void)data;
827 (void)dataSize;
828 (void)objects;
829 (void)objectsCount;
830}
831
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000832status_t RpcState::processTransactInternal(
833 const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
834 CommandData transactionData,
835 std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
Steven Morelandada72bd2021-06-09 23:29:13 +0000836 // for 'recursive' calls to this, we have already read and processed the
837 // binder from the transaction data and taken reference counts into account,
838 // so it is cached here.
Steven Moreland3903bf02021-09-27 16:05:24 -0700839 sp<IBinder> target;
Steven Morelandada72bd2021-06-09 23:29:13 +0000840processTransactInternalTailCall:
841
Steven Moreland5553ac42020-11-11 02:14:45 +0000842 if (transactionData.size() < sizeof(RpcWireTransaction)) {
843 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
844 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000845 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000846 return BAD_VALUE;
847 }
848 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
849
Steven Moreland5623d1a2021-09-10 15:45:34 -0700850 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000851 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000852
853 status_t replyStatus = OK;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700854 if (addr != 0) {
Steven Moreland3903bf02021-09-27 16:05:24 -0700855 if (!target) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000856 replyStatus = onBinderEntering(session, addr, &target);
Steven Morelandf5174272021-05-25 00:39:28 +0000857 }
858
Steven Moreland7227c8a2021-06-02 00:24:32 +0000859 if (replyStatus != OK) {
860 // do nothing
861 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000862 // This can happen if the binder is remote in this process, and
863 // another thread has called the last decStrong on this binder.
864 // However, for local binders, it indicates a misbehaving client
865 // (any binder which is being transacted on should be holding a
866 // strong ref count), so in either case, terminating the
867 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700868 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
869 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000870 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000871 replyStatus = BAD_VALUE;
872 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700873 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
874 ". Terminating!",
875 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000876 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000877 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000878 } else if (oneway) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000879 RpcMutexUniqueLock _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000880 auto it = mNodeForAddress.find(addr);
881 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700882 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000883 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000884 } else if (transaction->asyncNumber != it->second.asyncNumber) {
885 // we need to process some other asynchronous transaction
886 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000887 it->second.asyncTodo.push(BinderNode::AsyncTodo{
888 .ref = target,
889 .data = std::move(transactionData),
890 .asyncNumber = transaction->asyncNumber,
891 });
Steven Morelandd45be622021-06-04 02:19:37 +0000892
893 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700894 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
895 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000896
897 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
898 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
899 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
900
901 if (numPending >= kArbitraryOnewayCallWarnLevel) {
902 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
903 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
904 _l.unlock();
905 (void)session->shutdownAndWait(false);
906 return FAILED_TRANSACTION;
907 }
908
909 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
910 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
911 target.get(), numPending);
912 }
913 }
Steven Morelandf5174272021-05-25 00:39:28 +0000914 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000915 }
916 }
917 }
918
Steven Moreland5553ac42020-11-11 02:14:45 +0000919 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000920 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000921
922 if (replyStatus == OK) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000923 Span<const uint8_t> parcelSpan = {transaction->data,
924 transactionData.size() -
925 offsetof(RpcWireTransaction, data)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000926 Span<const uint32_t> objectTableSpan;
927 if (session->getProtocolVersion().value() >
Frederick Mayledc07cf82022-05-26 20:30:12 +0000928 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000929 std::optional<Span<const uint8_t>> objectTableBytes =
930 parcelSpan.splitOff(transaction->parcelDataSize);
931 if (!objectTableBytes.has_value()) {
932 ALOGE("Parcel size (%" PRId32 ") greater than available bytes (%zu). Terminating!",
933 transaction->parcelDataSize, parcelSpan.byteSize());
934 (void)session->shutdownAndWait(false);
935 return BAD_VALUE;
936 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000937 std::optional<Span<const uint32_t>> maybeSpan =
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000938 objectTableBytes->reinterpret<const uint32_t>();
Frederick Mayle69a0c992022-05-26 20:38:39 +0000939 if (!maybeSpan.has_value()) {
940 ALOGE("Bad object table size inferred from RpcWireTransaction. Saw bodySize=%zu "
941 "sizeofHeader=%zu parcelSize=%" PRId32
942 " objectTableBytesSize=%zu. Terminating!",
943 transactionData.size(), sizeof(RpcWireTransaction),
Frederick Mayle16a12ae2022-07-15 00:04:33 +0000944 transaction->parcelDataSize, objectTableBytes->size);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000945 return BAD_VALUE;
946 }
947 objectTableSpan = *maybeSpan;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000948 }
949
Steven Morelandeff77c12021-04-15 00:37:19 +0000950 Parcel data;
951 // transaction->data is owned by this function. Parcel borrows this data and
952 // only holds onto it for the duration of this function call. Parcel will be
953 // deleted before the 'transactionData' object.
Frederick Mayledc07cf82022-05-26 20:30:12 +0000954
Frederick Mayleffe9ac22022-06-30 02:07:36 +0000955 replyStatus =
956 data.rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
957 objectTableSpan.data, objectTableSpan.size,
958 std::move(ancillaryFds), do_nothing_to_transact_data);
959 // Reset to avoid spurious use-after-move warning from clang-tidy.
960 ancillaryFds = std::remove_reference<decltype(ancillaryFds)>::type();
Steven Morelandeff77c12021-04-15 00:37:19 +0000961
Frederick Mayle69a0c992022-05-26 20:38:39 +0000962 if (replyStatus == OK) {
963 if (target) {
964 bool origAllowNested = connection->allowNested;
965 connection->allowNested = !oneway;
Steven Morelandc7d40132021-06-10 03:42:11 +0000966
Frederick Mayle69a0c992022-05-26 20:38:39 +0000967 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000968
Frederick Mayle69a0c992022-05-26 20:38:39 +0000969 connection->allowNested = origAllowNested;
970 } else {
971 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000972
Frederick Mayle69a0c992022-05-26 20:38:39 +0000973 switch (transaction->code) {
974 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
975 replyStatus = reply.writeInt32(session->getMaxIncomingThreads());
976 break;
977 }
978 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
979 // for client connections, this should always report the value
980 // originally returned from the server, so this is asserting
981 // that it exists
982 replyStatus = reply.writeByteVector(session->mId);
983 break;
984 }
985 default: {
986 sp<RpcServer> server = session->server();
987 if (server) {
988 switch (transaction->code) {
989 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
990 sp<IBinder> root = session->mSessionSpecificRootObject
991 ?: server->getRootObject();
992 replyStatus = reply.writeStrongBinder(root);
993 break;
994 }
995 default: {
996 replyStatus = UNKNOWN_TRANSACTION;
997 }
Steven Moreland103424e2021-06-02 18:16:19 +0000998 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000999 } else {
1000 ALOGE("Special command sent, but no server object attached.");
Steven Moreland103424e2021-06-02 18:16:19 +00001001 }
Steven Morelandf137de92021-04-24 01:54:26 +00001002 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001003 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001004 }
1005 }
1006 }
1007
Steven Morelandc7d40132021-06-10 03:42:11 +00001008 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001009 if (replyStatus != OK) {
1010 ALOGW("Oneway call failed with error: %d", replyStatus);
1011 }
1012
Steven Moreland5623d1a2021-09-10 15:45:34 -07001013 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
1014 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001015
1016 // Check to see if there is another asynchronous transaction to process.
1017 // This behavior differs from binder behavior, since in the binder
1018 // driver, asynchronous transactions will be processed after existing
1019 // pending binder transactions on the queue. The downside of this is
1020 // that asynchronous transactions can be drowned out by synchronous
1021 // transactions. However, we have no easy way to queue these
1022 // transactions after the synchronous transactions we may want to read
1023 // from the wire. So, in socket binder here, we have the opposite
1024 // downside: asynchronous transactions may drown out synchronous
1025 // transactions.
1026 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001027 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001028 auto it = mNodeForAddress.find(addr);
1029 // last refcount dropped after this transaction happened
1030 if (it == mNodeForAddress.end()) return OK;
1031
Steven Morelandc9d7b532021-06-04 20:57:41 +00001032 if (!nodeProgressAsyncNumber(&it->second)) {
1033 _l.unlock();
1034 (void)session->shutdownAndWait(false);
1035 return DEAD_OBJECT;
1036 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001037
1038 if (it->second.asyncTodo.size() == 0) return OK;
1039 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001040 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
1041 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001042
1043 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +00001044 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +00001045 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +00001046 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
1047
Steven Morelandada72bd2021-06-09 23:29:13 +00001048 // reset up arguments
1049 transactionData = std::move(todo.data);
Steven Moreland3903bf02021-09-27 16:05:24 -07001050 LOG_ALWAYS_FATAL_IF(target != todo.ref,
1051 "async list should be associated with a binder");
Steven Morelandf5174272021-05-25 00:39:28 +00001052
Steven Moreland5553ac42020-11-11 02:14:45 +00001053 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +00001054 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +00001055 }
1056 }
Steven Morelandd8083312021-09-22 13:37:10 -07001057
1058 // done processing all the async commands on this binder that we can, so
1059 // write decstrongs on the binder
1060 if (addr != 0 && replyStatus == OK) {
1061 return flushExcessBinderRefs(session, addr, target);
1062 }
1063
Steven Moreland5553ac42020-11-11 02:14:45 +00001064 return OK;
1065 }
1066
Steven Moreland6709cf42021-09-30 15:21:54 -07001067 // Binder refs are flushed for oneway calls only after all calls which are
1068 // built up are executed. Otherwise, they fill up the binder buffer.
1069 if (addr != 0 && replyStatus == OK) {
1070 replyStatus = flushExcessBinderRefs(session, addr, target);
1071 }
1072
Frederick Mayle69a0c992022-05-26 20:38:39 +00001073 std::string errorMsg;
1074 if (status_t status = validateParcel(session, reply, &errorMsg); status != OK) {
1075 ALOGE("Reply Parcel failed validation: %s", errorMsg.c_str());
1076 // Forward the error to the client of the transaction.
1077 reply.freeData();
1078 reply.markForRpc(session);
1079 replyStatus = status;
1080 }
1081
1082 auto* rpcFields = reply.maybeRpcFields();
1083 LOG_ALWAYS_FATAL_IF(rpcFields == nullptr);
1084
Frederick Mayledc07cf82022-05-26 20:30:12 +00001085 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
1086
Frederick Mayle69a0c992022-05-26 20:38:39 +00001087 Span<const uint32_t> objectTableSpan = Span<const uint32_t>{rpcFields->mObjectPositions.data(),
1088 rpcFields->mObjectPositions.size()};
Frederick Mayledc07cf82022-05-26 20:30:12 +00001089
Frederick Mayle778c0902022-05-27 01:14:57 +00001090 uint32_t bodySize;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001091 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(rpcReplyWireSize, reply.dataSize(), &bodySize) ||
1092 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
1093 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +00001094 "Too much data for reply %zu", reply.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +00001095 RpcWireHeader cmdReply{
1096 .command = RPC_COMMAND_REPLY,
Frederick Mayle778c0902022-05-27 01:14:57 +00001097 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +00001098 };
Steven Moreland5553ac42020-11-11 02:14:45 +00001099 RpcWireReply rpcReply{
1100 .status = replyStatus,
Frederick Mayledc07cf82022-05-26 20:30:12 +00001101 // NOTE: Not necessarily written to socket depending on session
1102 // version.
1103 // NOTE: bodySize didn't overflow => this cast is safe
1104 .parcelDataSize = static_cast<uint32_t>(reply.dataSize()),
1105 .reserved = {0, 0, 0},
Steven Moreland5553ac42020-11-11 02:14:45 +00001106 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001107 iovec iovs[]{
1108 {&cmdReply, sizeof(RpcWireHeader)},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001109 {&rpcReply, rpcReplyWireSize},
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001110 {const_cast<uint8_t*>(reply.data()), reply.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +00001111 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001112 };
Frederick Mayle69a0c992022-05-26 20:38:39 +00001113 return rpcSend(connection, session, "reply", iovs, arraysize(iovs), std::nullopt,
1114 rpcFields->mFds.get());
Steven Moreland5553ac42020-11-11 02:14:45 +00001115}
1116
Steven Moreland5ae62562021-06-10 03:21:42 +00001117status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
1118 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001119 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
1120
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001121 if (command.bodySize != sizeof(RpcDecStrong)) {
1122 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcDecStrong. Terminating!",
1123 sizeof(RpcDecStrong), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001124 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001125 return BAD_VALUE;
1126 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001127
Frederick Mayleb86cda42022-06-09 23:17:45 +00001128 RpcDecStrong body;
1129 iovec iov{&body, sizeof(RpcDecStrong)};
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001130 if (status_t status = rpcRec(connection, session, "dec ref body", &iov, 1, nullptr);
1131 status != OK)
Frederick Mayleb86cda42022-06-09 23:17:45 +00001132 return status;
1133
1134 uint64_t addr = RpcWireAddress::toRaw(body.address);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +00001135 RpcMutexUniqueLock _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +00001136 auto it = mNodeForAddress.find(addr);
1137 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001138 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001139 return OK;
1140 }
1141
1142 sp<IBinder> target = it->second.binder.promote();
1143 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001144 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
1145 ". Terminating!",
1146 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001147 _l.unlock();
1148 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001149 return BAD_VALUE;
1150 }
1151
Frederick Mayleb86cda42022-06-09 23:17:45 +00001152 if (it->second.timesSent < body.amount) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001153 ALOGE("Record of sending binder %zu times, but requested decStrong for %" PRIu64 " of %u",
Frederick Mayleb86cda42022-06-09 23:17:45 +00001154 it->second.timesSent, addr, body.amount);
Steven Moreland5553ac42020-11-11 02:14:45 +00001155 return OK;
1156 }
1157
Steven Moreland5623d1a2021-09-10 15:45:34 -07001158 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
1159 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001160
Frederick Mayleb86cda42022-06-09 23:17:45 +00001161 LOG_RPC_DETAIL("Processing dec strong of %" PRIu64 " by %u from %zu", addr, body.amount,
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001162 it->second.timesSent);
1163
Frederick Mayleb86cda42022-06-09 23:17:45 +00001164 it->second.timesSent -= body.amount;
Steven Moreland31bde7a2021-06-04 00:57:36 +00001165 sp<IBinder> tempHold = tryEraseNode(it);
1166 _l.unlock();
1167 tempHold = nullptr; // destructor may make binder calls on this session
1168
1169 return OK;
1170}
1171
Frederick Mayle69a0c992022-05-26 20:38:39 +00001172status_t RpcState::validateParcel(const sp<RpcSession>& session, const Parcel& parcel,
1173 std::string* errorMsg) {
1174 auto* rpcFields = parcel.maybeRpcFields();
1175 if (rpcFields == nullptr) {
1176 *errorMsg = "Parcel not crafted for RPC call";
1177 return BAD_TYPE;
1178 }
1179
1180 if (rpcFields->mSession != session) {
1181 *errorMsg = "Parcel's session doesn't match";
1182 return BAD_TYPE;
1183 }
1184
1185 uint32_t protocolVersion = session->getProtocolVersion().value();
1186 if (protocolVersion < RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE &&
1187 !rpcFields->mObjectPositions.empty()) {
1188 *errorMsg = StringPrintf("Parcel has attached objects but the session's protocol version "
1189 "(%" PRIu32 ") is too old, must be at least %" PRIu32,
1190 protocolVersion,
1191 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE);
1192 return BAD_VALUE;
1193 }
1194
1195 if (rpcFields->mFds && !rpcFields->mFds->empty()) {
1196 switch (session->getFileDescriptorTransportMode()) {
1197 case RpcSession::FileDescriptorTransportMode::NONE:
1198 *errorMsg =
1199 "Parcel has file descriptors, but no file descriptor transport is enabled";
1200 return FDS_NOT_ALLOWED;
1201 case RpcSession::FileDescriptorTransportMode::UNIX: {
1202 constexpr size_t kMaxFdsPerMsg = 253;
1203 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
1204 *errorMsg = StringPrintf("Too many file descriptors in Parcel for unix "
1205 "domain socket: %zu (max is %zu)",
1206 rpcFields->mFds->size(), kMaxFdsPerMsg);
1207 return BAD_VALUE;
1208 }
Andrei Homescu1c18a802022-08-17 04:59:01 +00001209 break;
1210 }
1211 case RpcSession::FileDescriptorTransportMode::TRUSTY: {
1212 // Keep this in sync with trusty_ipc.h!!!
1213 // We could import that file here on Trusty, but it's not
1214 // available on Android
1215 constexpr size_t kMaxFdsPerMsg = 8;
1216 if (rpcFields->mFds->size() > kMaxFdsPerMsg) {
1217 *errorMsg = StringPrintf("Too many file descriptors in Parcel for Trusty "
1218 "IPC connection: %zu (max is %zu)",
1219 rpcFields->mFds->size(), kMaxFdsPerMsg);
1220 return BAD_VALUE;
1221 }
1222 break;
Frederick Mayle69a0c992022-05-26 20:38:39 +00001223 }
1224 }
1225 }
1226
1227 return OK;
1228}
1229
Steven Moreland5623d1a2021-09-10 15:45:34 -07001230sp<IBinder> RpcState::tryEraseNode(std::map<uint64_t, BinderNode>::iterator& it) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001231 sp<IBinder> ref;
1232
Steven Moreland5553ac42020-11-11 02:14:45 +00001233 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001234 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +00001235
1236 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +00001237 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
1238 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +00001239 mNodeForAddress.erase(it);
1240 }
1241 }
1242
Steven Moreland31bde7a2021-06-04 00:57:36 +00001243 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +00001244}
1245
Steven Morelandc9d7b532021-06-04 20:57:41 +00001246bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +00001247 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
1248 // a single binder
1249 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
1250 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +00001251 return false;
1252 }
1253 node->asyncNumber++;
1254 return true;
1255}
1256
Steven Moreland5553ac42020-11-11 02:14:45 +00001257} // namespace android