blob: 419df86a4ca4bbe3f0b3ab9165e1b33ad911d484 [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>
Steven Moreland5553ac42020-11-11 02:14:45 +000024#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000025#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000026#include <binder/RpcServer.h>
27
28#include "Debug.h"
29#include "RpcWireFormat.h"
Frederick Mayledc07cf82022-05-26 20:30:12 +000030#include "Utils.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000031
Steven Morelandb8176792021-06-22 20:29:21 +000032#include <random>
33
Steven Moreland5553ac42020-11-11 02:14:45 +000034#include <inttypes.h>
35
36namespace android {
37
Steven Morelandd7302072021-05-15 01:32:04 +000038using base::ScopeGuard;
39
Devin Moore08256432021-07-02 13:03:49 -070040#if RPC_FLAKE_PRONE
Steven Morelandb8176792021-06-22 20:29:21 +000041void rpcMaybeWaitToFlake() {
Devin Moore08256432021-07-02 13:03:49 -070042 [[clang::no_destroy]] static std::random_device r;
43 [[clang::no_destroy]] static std::mutex m;
Steven Morelandb8176792021-06-22 20:29:21 +000044 unsigned num;
45 {
46 std::lock_guard<std::mutex> lock(m);
47 num = r();
48 }
49 if (num % 10 == 0) usleep(num % 1000);
50}
51#endif
52
Steven Moreland5553ac42020-11-11 02:14:45 +000053RpcState::RpcState() {}
54RpcState::~RpcState() {}
55
Steven Morelandbdb53ab2021-05-05 17:57:41 +000056status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5623d1a2021-09-10 15:45:34 -070057 uint64_t* outAddress) {
Steven Moreland5553ac42020-11-11 02:14:45 +000058 bool isRemote = binder->remoteBinder();
59 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
60
Steven Moreland99157622021-09-13 16:27:34 -070061 if (isRpc && binder->remoteBinder()->getPrivateAccessor().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000062 // We need to be able to send instructions over the socket for how to
63 // connect to a different server, and we also need to let the host
64 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000065 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000066 return INVALID_OPERATION;
67 }
68
69 if (isRemote && !isRpc) {
70 // Without additional work, this would have the effect of using this
71 // process to proxy calls from the socket over to the other process, and
72 // it would make those calls look like they come from us (not over the
73 // sockets). In order to make this work transparently like binder, we
74 // would instead need to send instructions over the socket for how to
75 // connect to the host process, and we also need to let the host process
76 // know this was happening.
77 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
78 return INVALID_OPERATION;
79 }
80
81 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000082 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +000083
84 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
85 // in RpcState
86 for (auto& [addr, node] : mNodeForAddress) {
87 if (binder == node.binder) {
88 if (isRpc) {
Steven Moreland5623d1a2021-09-10 15:45:34 -070089 // check integrity of data structure
Steven Moreland99157622021-09-13 16:27:34 -070090 uint64_t actualAddr = binder->remoteBinder()->getPrivateAccessor().rpcAddress();
Steven Moreland5623d1a2021-09-10 15:45:34 -070091 LOG_ALWAYS_FATAL_IF(addr != actualAddr, "Address mismatch %" PRIu64 " vs %" PRIu64,
92 addr, actualAddr);
Steven Moreland5553ac42020-11-11 02:14:45 +000093 }
94 node.timesSent++;
95 node.sentRef = binder; // might already be set
96 *outAddress = addr;
97 return OK;
98 }
99 }
100 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
101
Steven Moreland91538242021-06-10 23:35:35 +0000102 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +0000103
Steven Moreland5623d1a2021-09-10 15:45:34 -0700104 // arbitrary limit for maximum number of nodes in a process (otherwise we
105 // might run out of addresses)
106 if (mNodeForAddress.size() > 100000) {
107 return NO_MEMORY;
108 }
109
110 while (true) {
111 RpcWireAddress address{
112 .options = RPC_WIRE_ADDRESS_OPTION_CREATED,
113 .address = mNextId,
114 };
115 if (forServer) {
116 address.options |= RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
117 }
118
119 // avoid ubsan abort
120 if (mNextId >= std::numeric_limits<uint32_t>::max()) {
121 mNextId = 0;
122 } else {
123 mNextId++;
124 }
125
126 auto&& [it, inserted] = mNodeForAddress.insert({RpcWireAddress::toRaw(address),
Steven Moreland91538242021-06-10 23:35:35 +0000127 BinderNode{
128 .binder = binder,
Steven Moreland91538242021-06-10 23:35:35 +0000129 .sentRef = binder,
Andrei Homescu5a036f32022-03-08 22:54:40 +0000130 .timesSent = 1,
Steven Moreland91538242021-06-10 23:35:35 +0000131 }});
132 if (inserted) {
133 *outAddress = it->first;
134 return OK;
135 }
Steven Moreland91538242021-06-10 23:35:35 +0000136 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000137}
138
Steven Moreland5623d1a2021-09-10 15:45:34 -0700139status_t RpcState::onBinderEntering(const sp<RpcSession>& session, uint64_t address,
Steven Moreland7227c8a2021-06-02 00:24:32 +0000140 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000141 // ensure that: if we want to use addresses for something else in the future (for
142 // instance, allowing transitive binder sends), that we don't accidentally
143 // send those addresses to old server. Accidentally ignoring this in that
144 // case and considering the binder to be recognized could cause this
145 // process to accidentally proxy transactions for that binder. Of course,
146 // if we communicate with a binder, it could always be proxying
147 // information. However, we want to make sure that isn't done on accident
148 // by a client.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700149 RpcWireAddress addr = RpcWireAddress::fromRaw(address);
150 constexpr uint32_t kKnownOptions =
151 RPC_WIRE_ADDRESS_OPTION_CREATED | RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
152 if (addr.options & ~kKnownOptions) {
153 ALOGE("Address is of an unknown type, rejecting: %" PRIu64, address);
Steven Moreland91538242021-06-10 23:35:35 +0000154 return BAD_VALUE;
155 }
156
Steven Morelandd8083312021-09-22 13:37:10 -0700157 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000158 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000159
160 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000161 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000162
163 // implicitly have strong RPC refcount, since we received this binder
164 it->second.timesRecd++;
Steven Morelandd8083312021-09-22 13:37:10 -0700165 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000166 }
167
Steven Moreland91538242021-06-10 23:35:35 +0000168 // we don't know about this binder, so the other side of the connection
169 // should have created it.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700170 if ((addr.options & RPC_WIRE_ADDRESS_OPTION_FOR_SERVER) == !!session->server()) {
171 ALOGE("Server received unrecognized address which we should own the creation of %" PRIu64,
172 address);
Steven Moreland91538242021-06-10 23:35:35 +0000173 return BAD_VALUE;
174 }
175
Steven Moreland5553ac42020-11-11 02:14:45 +0000176 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
177 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
178
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000179 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000180 // device global binders in the RPC world).
Steven Moreland99157622021-09-13 16:27:34 -0700181 it->second.binder = *out = BpBinder::PrivateAccessor::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000182 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000183 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000184}
185
Steven Morelandd8083312021-09-22 13:37:10 -0700186status_t RpcState::flushExcessBinderRefs(const sp<RpcSession>& session, uint64_t address,
187 const sp<IBinder>& binder) {
Steven Morelande96ed0e2021-09-27 17:43:53 -0700188 // We can flush all references when the binder is destroyed. No need to send
189 // extra reference counting packets now.
190 if (binder->remoteBinder()) return OK;
191
Steven Morelandd8083312021-09-22 13:37:10 -0700192 std::unique_lock<std::mutex> _l(mNodeMutex);
193 if (mTerminated) return DEAD_OBJECT;
194
195 auto it = mNodeForAddress.find(address);
196
197 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Can't be deleted while we hold sp<>");
198 LOG_ALWAYS_FATAL_IF(it->second.binder != binder,
199 "Caller of flushExcessBinderRefs using inconsistent arguments");
200
Steven Morelande96ed0e2021-09-27 17:43:53 -0700201 LOG_ALWAYS_FATAL_IF(it->second.timesSent <= 0, "Local binder must have been sent %p",
202 binder.get());
Steven Morelandd8083312021-09-22 13:37:10 -0700203
Steven Morelande96ed0e2021-09-27 17:43:53 -0700204 // For a local binder, we only need to know that we sent it. Now that we
205 // have an sp<> for this call, we don't need anything more. If the other
206 // process is done with this binder, it needs to know we received the
207 // refcount associated with this call, so we can acknowledge that we
208 // received it. Once (or if) it has no other refcounts, it would reply with
209 // its own decStrong so that it could be removed from this session.
210 if (it->second.timesRecd != 0) {
Steven Morelandd8083312021-09-22 13:37:10 -0700211 _l.unlock();
212
Steven Morelande96ed0e2021-09-27 17:43:53 -0700213 return session->sendDecStrongToTarget(address, 0);
Steven Morelandd8083312021-09-22 13:37:10 -0700214 }
215
216 return OK;
217}
218
Steven Moreland5553ac42020-11-11 02:14:45 +0000219size_t RpcState::countBinders() {
220 std::lock_guard<std::mutex> _l(mNodeMutex);
221 return mNodeForAddress.size();
222}
223
224void RpcState::dump() {
225 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000226 dumpLocked();
227}
228
Steven Morelandc9d7b532021-06-04 20:57:41 +0000229void RpcState::clear() {
Steven Moreland583a14a2021-06-04 02:04:58 +0000230 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000231
232 if (mTerminated) {
233 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
234 "New state should be impossible after terminating!");
235 return;
236 }
237
238 if (SHOULD_LOG_RPC_DETAIL) {
239 ALOGE("RpcState::clear()");
240 dumpLocked();
241 }
242
243 // if the destructor of a binder object makes another RPC call, then calling
244 // decStrong could deadlock. So, we must hold onto these binders until
245 // mNodeMutex is no longer taken.
246 std::vector<sp<IBinder>> tempHoldBinder;
247
248 mTerminated = true;
249 for (auto& [address, node] : mNodeForAddress) {
250 sp<IBinder> binder = node.binder.promote();
251 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
252
253 if (node.sentRef != nullptr) {
254 tempHoldBinder.push_back(node.sentRef);
255 }
256 }
257
258 mNodeForAddress.clear();
259
260 _l.unlock();
261 tempHoldBinder.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000262}
263
264void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000265 ALOGE("DUMP OF RpcState %p", this);
266 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
267 for (const auto& [address, node] : mNodeForAddress) {
268 sp<IBinder> binder = node.binder.promote();
269
270 const char* desc;
271 if (binder) {
272 if (binder->remoteBinder()) {
273 if (binder->remoteBinder()->isRpcBinder()) {
274 desc = "(rpc binder proxy)";
275 } else {
276 desc = "(binder proxy)";
277 }
278 } else {
279 desc = "(local binder)";
280 }
281 } else {
282 desc = "(null)";
283 }
284
Steven Moreland5623d1a2021-09-10 15:45:34 -0700285 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a: %" PRIu64 " type: %s",
286 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address, desc);
Steven Moreland5553ac42020-11-11 02:14:45 +0000287 }
288 ALOGE("END DUMP OF RpcState");
289}
290
Steven Moreland5553ac42020-11-11 02:14:45 +0000291
Steven Morelanddbe71832021-05-12 23:31:00 +0000292RpcState::CommandData::CommandData(size_t size) : mSize(size) {
293 // The maximum size for regular binder is 1MB for all concurrent
294 // transactions. A very small proportion of transactions are even
295 // larger than a page, but we need to avoid allocating too much
296 // data on behalf of an arbitrary client, or we could risk being in
297 // a position where a single additional allocation could run out of
298 // memory.
299 //
300 // Note, this limit may not reflect the total amount of data allocated for a
301 // transaction (in some cases, additional fixed size amounts are added),
302 // though for rough consistency, we should avoid cases where this data type
303 // is used for multiple dynamic allocations for a single transaction.
304 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
305 if (size == 0) return;
306 if (size > kMaxTransactionAllocation) {
307 ALOGW("Transaction requested too much data allocation %zu", size);
308 return;
309 }
310 mData.reset(new (std::nothrow) uint8_t[size]);
311}
312
Steven Moreland5ae62562021-06-10 03:21:42 +0000313status_t RpcState::rpcSend(const sp<RpcSession::RpcConnection>& connection,
Colin Cross9adfeaf2022-01-21 17:22:09 -0800314 const sp<RpcSession>& session, const char* what, iovec* iovs, int niovs,
Devin Moore695368f2022-06-03 22:29:14 +0000315 const std::optional<android::base::function_ref<status_t()>>& altPoll) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800316 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000317 LOG_RPC_DETAIL("Sending %s (part %d of %d) on RpcTransport %p: %s",
318 what, i + 1, niovs, connection->rpcTransport.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000319 android::base::HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000320 }
321
Yifan Hong702115c2021-06-24 15:39:18 -0700322 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700323 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000324 iovs, niovs, altPoll);
Steven Moreland798e0d12021-07-14 23:19:25 +0000325 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800326 LOG_RPC_DETAIL("Failed to write %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700327 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000328 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000329 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000330 }
331
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000332 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000333}
334
Steven Moreland5ae62562021-06-10 03:21:42 +0000335status_t RpcState::rpcRec(const sp<RpcSession::RpcConnection>& connection,
Colin Cross9adfeaf2022-01-21 17:22:09 -0800336 const sp<RpcSession>& session, const char* what, iovec* iovs, int niovs) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000337 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700338 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
Devin Moore695368f2022-06-03 22:29:14 +0000339 iovs, niovs, std::nullopt);
Steven Morelandee3f4662021-05-22 01:07:33 +0000340 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800341 LOG_RPC_DETAIL("Failed to read %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700342 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandae58f432021-08-05 17:53:16 -0700343 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000344 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000345 }
346
Colin Cross9adfeaf2022-01-21 17:22:09 -0800347 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000348 LOG_RPC_DETAIL("Received %s (part %d of %d) on RpcTransport %p: %s",
349 what, i + 1, niovs, connection->rpcTransport.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000350 android::base::HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
351 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000352 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000353}
354
Steven Morelandbf57bce2021-07-26 15:26:12 -0700355status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
356 const sp<RpcSession>& session, uint32_t* version) {
357 RpcNewSessionResponse response;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000358 iovec iov{&response, sizeof(response)};
359 if (status_t status = rpcRec(connection, session, "new session response", &iov, 1);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700360 status != OK) {
361 return status;
362 }
363 *version = response.version;
364 return OK;
365}
366
Steven Moreland5ae62562021-06-10 03:21:42 +0000367status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
368 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000369 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000370 .msg = RPC_CONNECTION_INIT_OKAY,
371 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000372 iovec iov{&init, sizeof(init)};
Devin Moore695368f2022-06-03 22:29:14 +0000373 return rpcSend(connection, session, "connection init", &iov, 1, std::nullopt);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000374}
375
Steven Moreland5ae62562021-06-10 03:21:42 +0000376status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
377 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000378 RpcOutgoingConnectionInit init;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000379 iovec iov{&init, sizeof(init)};
380 if (status_t status = rpcRec(connection, session, "connection init", &iov, 1); status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000381 return status;
382
383 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
384 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
385 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
386 init.msg);
387 return BAD_VALUE;
388 }
389 return OK;
390}
391
Steven Moreland5ae62562021-06-10 03:21:42 +0000392sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
393 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000394 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000395 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000396 Parcel reply;
397
Steven Moreland5623d1a2021-09-10 15:45:34 -0700398 status_t status =
399 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000400 if (status != OK) {
401 ALOGE("Error getting root object: %s", statusToString(status).c_str());
402 return nullptr;
403 }
404
405 return reply.readStrongBinder();
406}
407
Steven Moreland5ae62562021-06-10 03:21:42 +0000408status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
409 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000410 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000411 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000412 Parcel reply;
413
Steven Moreland5623d1a2021-09-10 15:45:34 -0700414 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
415 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000416 if (status != OK) {
417 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
418 return status;
419 }
420
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000421 int32_t maxThreads;
422 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000423 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000424 if (maxThreads <= 0) {
425 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000426 return BAD_VALUE;
427 }
428
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000429 *maxThreadsOut = maxThreads;
430 return OK;
431}
432
Steven Moreland5ae62562021-06-10 03:21:42 +0000433status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700434 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000435 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000436 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000437 Parcel reply;
438
Steven Moreland5623d1a2021-09-10 15:45:34 -0700439 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
440 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000441 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000442 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000443 return status;
444 }
445
Steven Moreland826367f2021-09-10 14:05:31 -0700446 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000447}
448
Steven Moreland5ae62562021-06-10 03:21:42 +0000449status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
450 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
451 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000452 if (!data.isForRpc()) {
Steven Morelandcaf14b22021-09-27 18:18:35 -0700453 ALOGE("Refusing to send RPC with parcel not crafted for RPC call on binder %p code "
454 "%" PRIu32,
455 binder.get(), code);
Steven Morelandf5174272021-05-25 00:39:28 +0000456 return BAD_TYPE;
457 }
458
459 if (data.objectsCount() != 0) {
Steven Morelandcaf14b22021-09-27 18:18:35 -0700460 ALOGE("Parcel at %p has attached objects but is being used in an RPC call on binder %p "
461 "code %" PRIu32,
462 &data, binder.get(), code);
Steven Morelandf5174272021-05-25 00:39:28 +0000463 return BAD_TYPE;
464 }
465
Steven Moreland5623d1a2021-09-10 15:45:34 -0700466 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000467 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
468
Steven Moreland5ae62562021-06-10 03:21:42 +0000469 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000470}
471
Steven Moreland5ae62562021-06-10 03:21:42 +0000472status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700473 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000474 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000475 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
476 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
477
Steven Moreland5553ac42020-11-11 02:14:45 +0000478 uint64_t asyncNumber = 0;
479
Steven Moreland5623d1a2021-09-10 15:45:34 -0700480 if (address != 0) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000481 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000482 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
483 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700484 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
485 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000486
487 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000488 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000489 if (!nodeProgressAsyncNumber(&it->second)) {
490 _l.unlock();
491 (void)session->shutdownAndWait(false);
492 return DEAD_OBJECT;
493 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000494 }
495 }
496
Frederick Mayledc07cf82022-05-26 20:30:12 +0000497 // objectTable always empty for now. Will be populated from `data` soon.
498 std::vector<uint32_t> objectTable;
499 Span<const uint32_t> objectTableSpan = {objectTable.data(), objectTable.size()};
500
Frederick Mayle778c0902022-05-27 01:14:57 +0000501 uint32_t bodySize;
502 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(sizeof(RpcWireTransaction), data.dataSize(),
Frederick Mayledc07cf82022-05-26 20:30:12 +0000503 &bodySize) ||
504 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
505 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +0000506 "Too much data %zu", data.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +0000507 RpcWireHeader command{
508 .command = RPC_COMMAND_TRANSACT,
Frederick Mayle778c0902022-05-27 01:14:57 +0000509 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +0000510 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700511
Steven Moreland5553ac42020-11-11 02:14:45 +0000512 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700513 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000514 .code = code,
515 .flags = flags,
516 .asyncNumber = asyncNumber,
Frederick Mayledc07cf82022-05-26 20:30:12 +0000517 // bodySize didn't overflow => this cast is safe
518 .parcelDataSize = static_cast<uint32_t>(data.dataSize()),
Steven Moreland5553ac42020-11-11 02:14:45 +0000519 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000520
Steven Moreland43921d52021-09-27 17:15:56 -0700521 constexpr size_t kWaitMaxUs = 1000000;
522 constexpr size_t kWaitLogUs = 10000;
523 size_t waitUs = 0;
524
525 // Oneway calls have no sync point, so if many are sent before, whether this
526 // is a twoway or oneway transaction, they may have filled up the socket.
Devin Moore695368f2022-06-03 22:29:14 +0000527 // So, make sure we drain them before polling
Steven Moreland43921d52021-09-27 17:15:56 -0700528
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000529 iovec iovs[]{
530 {&command, sizeof(RpcWireHeader)},
531 {&transaction, sizeof(RpcWireTransaction)},
532 {const_cast<uint8_t*>(data.data()), data.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +0000533 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000534 };
Devin Moore695368f2022-06-03 22:29:14 +0000535 if (status_t status = rpcSend(connection, session, "transaction", iovs, arraysize(iovs),
536 [&] {
537 if (waitUs > kWaitLogUs) {
538 ALOGE("Cannot send command, trying to process pending "
539 "refcounts. Waiting %zuus. Too "
540 "many oneway calls?",
541 waitUs);
542 }
543
544 if (waitUs > 0) {
545 usleep(waitUs);
546 waitUs = std::min(kWaitMaxUs, waitUs * 2);
547 } else {
548 waitUs = 1;
549 }
550
551 return drainCommands(connection, session,
552 CommandType::CONTROL_ONLY);
553 });
Steven Moreland43921d52021-09-27 17:15:56 -0700554 status != OK) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000555 // TODO(b/167966510): need to undo onBinderLeaving - we know the
556 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000557 return status;
Steven Moreland43921d52021-09-27 17:15:56 -0700558 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000559
560 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700561 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
562 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000563
564 // Do not wait on result.
Steven Moreland43921d52021-09-27 17:15:56 -0700565 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000566 }
567
568 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
569
Steven Moreland5ae62562021-06-10 03:21:42 +0000570 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000571}
572
Steven Moreland438cce82021-04-02 18:04:08 +0000573static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
574 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000575 (void)p;
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000576 delete[] const_cast<uint8_t*>(data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000577 (void)dataSize;
578 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Yifan Hong239a2ca2021-06-24 16:05:16 -0700579 LOG_ALWAYS_FATAL_IF(objectsCount != 0, "%zu objects remaining", objectsCount);
Steven Moreland5553ac42020-11-11 02:14:45 +0000580}
581
Steven Moreland5ae62562021-06-10 03:21:42 +0000582status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
583 const sp<RpcSession>& session, Parcel* reply) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000584 RpcWireHeader command;
585 while (true) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000586 iovec iov{&command, sizeof(command)};
587 if (status_t status = rpcRec(connection, session, "command header (for reply)", &iov, 1);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000588 status != OK)
589 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000590
591 if (command.command == RPC_COMMAND_REPLY) break;
592
Steven Moreland19fc9f72021-06-10 03:57:30 +0000593 if (status_t status = processCommand(connection, session, command, CommandType::ANY);
Steven Moreland52eee942021-06-03 00:59:28 +0000594 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000595 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000596 }
597
Frederick Mayledc07cf82022-05-26 20:30:12 +0000598 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
599
600 if (command.bodySize < rpcReplyWireSize) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000601 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
602 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000603 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000604 return BAD_VALUE;
605 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000606
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000607 RpcWireReply rpcReply;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000608 memset(&rpcReply, 0, sizeof(RpcWireReply)); // zero because of potential short read
609
610 CommandData data(command.bodySize - rpcReplyWireSize);
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000611 if (!data.valid()) return NO_MEMORY;
612
613 iovec iovs[]{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000614 {&rpcReply, rpcReplyWireSize},
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000615 {data.data(), data.size()},
616 };
617 if (status_t status = rpcRec(connection, session, "reply body", iovs, arraysize(iovs));
618 status != OK)
619 return status;
620 if (rpcReply.status != OK) return rpcReply.status;
621
Frederick Mayledc07cf82022-05-26 20:30:12 +0000622 Span<const uint8_t> parcelSpan = {data.data(), data.size()};
623 if (session->getProtocolVersion().value() >=
624 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
625 Span<const uint8_t> objectTableBytes = parcelSpan.splitOff(rpcReply.parcelDataSize);
626 LOG_ALWAYS_FATAL_IF(objectTableBytes.size > 0, "Non-empty object table not supported yet.");
627 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000628
Frederick Mayledc07cf82022-05-26 20:30:12 +0000629 data.release();
630 reply->rpcSetDataReference(session, parcelSpan.data, parcelSpan.size, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000631 return OK;
632}
633
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000634status_t RpcState::sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection,
635 const sp<RpcSession>& session, uint64_t addr,
636 size_t target) {
637 RpcDecStrong body = {
638 .address = RpcWireAddress::fromRaw(addr),
639 };
640
Steven Moreland5553ac42020-11-11 02:14:45 +0000641 {
642 std::lock_guard<std::mutex> _l(mNodeMutex);
643 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
644 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700645 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
646 "Sending dec strong on unknown address %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000647
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000648 LOG_ALWAYS_FATAL_IF(it->second.timesRecd < target, "Can't dec count of %zu to %zu.",
649 it->second.timesRecd, target);
650
651 // typically this happens when multiple threads send dec refs at the
652 // same time - the transactions will get combined automatically
653 if (it->second.timesRecd == target) return OK;
654
655 body.amount = it->second.timesRecd - target;
656 it->second.timesRecd = target;
657
Steven Moreland31bde7a2021-06-04 00:57:36 +0000658 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
659 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000660 }
661
662 RpcWireHeader cmd = {
663 .command = RPC_COMMAND_DEC_STRONG,
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000664 .bodySize = sizeof(RpcDecStrong),
Steven Moreland5553ac42020-11-11 02:14:45 +0000665 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000666 iovec iovs[]{{&cmd, sizeof(cmd)}, {&body, sizeof(body)}};
Devin Moore695368f2022-06-03 22:29:14 +0000667 return rpcSend(connection, session, "dec ref", iovs, arraysize(iovs), std::nullopt);
Steven Moreland5553ac42020-11-11 02:14:45 +0000668}
669
Steven Moreland5ae62562021-06-10 03:21:42 +0000670status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
671 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700672 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000673
674 RpcWireHeader command;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000675 iovec iov{&command, sizeof(command)};
676 if (status_t status = rpcRec(connection, session, "command header (for server)", &iov, 1);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000677 status != OK)
678 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000679
Steven Moreland19fc9f72021-06-10 03:57:30 +0000680 return processCommand(connection, session, command, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000681}
682
Steven Moreland5ae62562021-06-10 03:21:42 +0000683status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
684 const sp<RpcSession>& session, CommandType type) {
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000685 while (true) {
Andrei Homescu1975aaa2022-03-19 02:34:57 +0000686 status_t status = connection->rpcTransport->pollRead();
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000687 if (status == WOULD_BLOCK) break;
688 if (status != OK) return status;
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000689
690 status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000691 if (status != OK) return status;
692 }
693 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000694}
695
Steven Moreland19fc9f72021-06-10 03:57:30 +0000696status_t RpcState::processCommand(const sp<RpcSession::RpcConnection>& connection,
697 const sp<RpcSession>& session, const RpcWireHeader& command,
698 CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000699 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
700 IPCThreadState::SpGuard spGuard{
701 .address = __builtin_frame_address(0),
702 .context = "processing binder RPC command",
703 };
704 const IPCThreadState::SpGuard* origGuard;
705 if (kernelBinderState != nullptr) {
706 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
707 }
708 ScopeGuard guardUnguard = [&]() {
709 if (kernelBinderState != nullptr) {
710 kernelBinderState->restoreGetCallingSpGuard(origGuard);
711 }
712 };
713
Steven Moreland5553ac42020-11-11 02:14:45 +0000714 switch (command.command) {
715 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000716 if (type != CommandType::ANY) return BAD_TYPE;
Steven Moreland5ae62562021-06-10 03:21:42 +0000717 return processTransact(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000718 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000719 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000720 }
721
722 // We should always know the version of the opposing side, and since the
723 // RPC-binder-level wire protocol is not self synchronizing, we have no way
724 // to understand where the current command ends and the next one begins. We
725 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000726 // to kill us, so ending the session for misbehaving client.
727 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000728 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000729 return DEAD_OBJECT;
730}
Steven Moreland5ae62562021-06-10 03:21:42 +0000731status_t RpcState::processTransact(const sp<RpcSession::RpcConnection>& connection,
732 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000733 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
734
Steven Morelanddbe71832021-05-12 23:31:00 +0000735 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000736 if (!transactionData.valid()) {
737 return NO_MEMORY;
738 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000739 iovec iov{transactionData.data(), transactionData.size()};
740 if (status_t status = rpcRec(connection, session, "transaction body", &iov, 1); status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000741 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000742
Steven Moreland5ae62562021-06-10 03:21:42 +0000743 return processTransactInternal(connection, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000744}
745
Steven Moreland438cce82021-04-02 18:04:08 +0000746static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
747 const binder_size_t* objects, size_t objectsCount) {
748 (void)p;
749 (void)data;
750 (void)dataSize;
751 (void)objects;
752 (void)objectsCount;
753}
754
Steven Moreland5ae62562021-06-10 03:21:42 +0000755status_t RpcState::processTransactInternal(const sp<RpcSession::RpcConnection>& connection,
756 const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000757 CommandData transactionData) {
758 // for 'recursive' calls to this, we have already read and processed the
759 // binder from the transaction data and taken reference counts into account,
760 // so it is cached here.
Steven Moreland3903bf02021-09-27 16:05:24 -0700761 sp<IBinder> target;
Steven Morelandada72bd2021-06-09 23:29:13 +0000762processTransactInternalTailCall:
763
Steven Moreland5553ac42020-11-11 02:14:45 +0000764 if (transactionData.size() < sizeof(RpcWireTransaction)) {
765 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
766 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000767 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000768 return BAD_VALUE;
769 }
770 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
771
Steven Moreland5623d1a2021-09-10 15:45:34 -0700772 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000773 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000774
775 status_t replyStatus = OK;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700776 if (addr != 0) {
Steven Moreland3903bf02021-09-27 16:05:24 -0700777 if (!target) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000778 replyStatus = onBinderEntering(session, addr, &target);
Steven Morelandf5174272021-05-25 00:39:28 +0000779 }
780
Steven Moreland7227c8a2021-06-02 00:24:32 +0000781 if (replyStatus != OK) {
782 // do nothing
783 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000784 // This can happen if the binder is remote in this process, and
785 // another thread has called the last decStrong on this binder.
786 // However, for local binders, it indicates a misbehaving client
787 // (any binder which is being transacted on should be holding a
788 // strong ref count), so in either case, terminating the
789 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700790 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
791 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000792 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000793 replyStatus = BAD_VALUE;
794 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700795 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
796 ". Terminating!",
797 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000798 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000799 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000800 } else if (oneway) {
Steven Morelandd45be622021-06-04 02:19:37 +0000801 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000802 auto it = mNodeForAddress.find(addr);
803 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700804 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000805 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000806 } else if (transaction->asyncNumber != it->second.asyncNumber) {
807 // we need to process some other asynchronous transaction
808 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000809 it->second.asyncTodo.push(BinderNode::AsyncTodo{
810 .ref = target,
811 .data = std::move(transactionData),
812 .asyncNumber = transaction->asyncNumber,
813 });
Steven Morelandd45be622021-06-04 02:19:37 +0000814
815 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700816 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
817 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000818
819 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
820 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
821 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
822
823 if (numPending >= kArbitraryOnewayCallWarnLevel) {
824 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
825 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
826 _l.unlock();
827 (void)session->shutdownAndWait(false);
828 return FAILED_TRANSACTION;
829 }
830
831 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
832 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
833 target.get(), numPending);
834 }
835 }
Steven Morelandf5174272021-05-25 00:39:28 +0000836 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000837 }
838 }
839 }
840
Steven Moreland5553ac42020-11-11 02:14:45 +0000841 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000842 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000843
844 if (replyStatus == OK) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000845 Span<const uint8_t> parcelSpan = {transaction->data,
846 transactionData.size() -
847 offsetof(RpcWireTransaction, data)};
848 if (session->getProtocolVersion().value() >=
849 RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_SIZE) {
850 Span<const uint8_t> objectTableBytes = parcelSpan.splitOff(transaction->parcelDataSize);
851 LOG_ALWAYS_FATAL_IF(objectTableBytes.size > 0,
852 "Non-empty object table not supported yet.");
853 }
854
Steven Morelandeff77c12021-04-15 00:37:19 +0000855 Parcel data;
856 // transaction->data is owned by this function. Parcel borrows this data and
857 // only holds onto it for the duration of this function call. Parcel will be
858 // deleted before the 'transactionData' object.
Frederick Mayledc07cf82022-05-26 20:30:12 +0000859
860 data.rpcSetDataReference(session, parcelSpan.data, parcelSpan.size,
Steven Morelandeff77c12021-04-15 00:37:19 +0000861 do_nothing_to_transact_data);
Steven Morelandeff77c12021-04-15 00:37:19 +0000862
Steven Moreland5553ac42020-11-11 02:14:45 +0000863 if (target) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000864 bool origAllowNested = connection->allowNested;
865 connection->allowNested = !oneway;
866
Steven Moreland5553ac42020-11-11 02:14:45 +0000867 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000868
869 connection->allowNested = origAllowNested;
Steven Moreland5553ac42020-11-11 02:14:45 +0000870 } else {
871 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000872
Steven Moreland103424e2021-06-02 18:16:19 +0000873 switch (transaction->code) {
874 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
Yifan Hong10423062021-10-08 16:26:32 -0700875 replyStatus = reply.writeInt32(session->getMaxIncomingThreads());
Steven Moreland103424e2021-06-02 18:16:19 +0000876 break;
877 }
878 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
879 // for client connections, this should always report the value
Steven Moreland01a6bad2021-06-11 00:59:20 +0000880 // originally returned from the server, so this is asserting
881 // that it exists
Steven Moreland826367f2021-09-10 14:05:31 -0700882 replyStatus = reply.writeByteVector(session->mId);
Steven Moreland103424e2021-06-02 18:16:19 +0000883 break;
884 }
885 default: {
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000886 sp<RpcServer> server = session->server();
Steven Moreland103424e2021-06-02 18:16:19 +0000887 if (server) {
888 switch (transaction->code) {
889 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
Steven Moreland51c44a92021-10-14 16:50:35 -0700890 sp<IBinder> root = session->mSessionSpecificRootObject
891 ?: server->getRootObject();
892 replyStatus = reply.writeStrongBinder(root);
Steven Moreland103424e2021-06-02 18:16:19 +0000893 break;
894 }
895 default: {
896 replyStatus = UNKNOWN_TRANSACTION;
897 }
898 }
899 } else {
900 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000901 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000902 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000903 }
904 }
905 }
906
Steven Morelandc7d40132021-06-10 03:42:11 +0000907 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000908 if (replyStatus != OK) {
909 ALOGW("Oneway call failed with error: %d", replyStatus);
910 }
911
Steven Moreland5623d1a2021-09-10 15:45:34 -0700912 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
913 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000914
915 // Check to see if there is another asynchronous transaction to process.
916 // This behavior differs from binder behavior, since in the binder
917 // driver, asynchronous transactions will be processed after existing
918 // pending binder transactions on the queue. The downside of this is
919 // that asynchronous transactions can be drowned out by synchronous
920 // transactions. However, we have no easy way to queue these
921 // transactions after the synchronous transactions we may want to read
922 // from the wire. So, in socket binder here, we have the opposite
923 // downside: asynchronous transactions may drown out synchronous
924 // transactions.
925 {
926 std::unique_lock<std::mutex> _l(mNodeMutex);
927 auto it = mNodeForAddress.find(addr);
928 // last refcount dropped after this transaction happened
929 if (it == mNodeForAddress.end()) return OK;
930
Steven Morelandc9d7b532021-06-04 20:57:41 +0000931 if (!nodeProgressAsyncNumber(&it->second)) {
932 _l.unlock();
933 (void)session->shutdownAndWait(false);
934 return DEAD_OBJECT;
935 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000936
937 if (it->second.asyncTodo.size() == 0) return OK;
938 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700939 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
940 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000941
942 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000943 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000944 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000945 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
946
Steven Morelandada72bd2021-06-09 23:29:13 +0000947 // reset up arguments
948 transactionData = std::move(todo.data);
Steven Moreland3903bf02021-09-27 16:05:24 -0700949 LOG_ALWAYS_FATAL_IF(target != todo.ref,
950 "async list should be associated with a binder");
Steven Morelandf5174272021-05-25 00:39:28 +0000951
Steven Moreland5553ac42020-11-11 02:14:45 +0000952 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000953 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000954 }
955 }
Steven Morelandd8083312021-09-22 13:37:10 -0700956
957 // done processing all the async commands on this binder that we can, so
958 // write decstrongs on the binder
959 if (addr != 0 && replyStatus == OK) {
960 return flushExcessBinderRefs(session, addr, target);
961 }
962
Steven Moreland5553ac42020-11-11 02:14:45 +0000963 return OK;
964 }
965
Steven Moreland6709cf42021-09-30 15:21:54 -0700966 // Binder refs are flushed for oneway calls only after all calls which are
967 // built up are executed. Otherwise, they fill up the binder buffer.
968 if (addr != 0 && replyStatus == OK) {
969 replyStatus = flushExcessBinderRefs(session, addr, target);
970 }
971
Frederick Mayledc07cf82022-05-26 20:30:12 +0000972 const size_t rpcReplyWireSize = RpcWireReply::wireSize(session->getProtocolVersion().value());
973
974 // objectTable always empty for now. Will be populated from `reply` soon.
975 std::vector<uint32_t> objectTable;
976 Span<const uint32_t> objectTableSpan = {objectTable.data(), objectTable.size()};
977
Frederick Mayle778c0902022-05-27 01:14:57 +0000978 uint32_t bodySize;
Frederick Mayledc07cf82022-05-26 20:30:12 +0000979 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(rpcReplyWireSize, reply.dataSize(), &bodySize) ||
980 __builtin_add_overflow(objectTableSpan.byteSize(), bodySize,
981 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +0000982 "Too much data for reply %zu", reply.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +0000983 RpcWireHeader cmdReply{
984 .command = RPC_COMMAND_REPLY,
Frederick Mayle778c0902022-05-27 01:14:57 +0000985 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +0000986 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000987 RpcWireReply rpcReply{
988 .status = replyStatus,
Frederick Mayledc07cf82022-05-26 20:30:12 +0000989 // NOTE: Not necessarily written to socket depending on session
990 // version.
991 // NOTE: bodySize didn't overflow => this cast is safe
992 .parcelDataSize = static_cast<uint32_t>(reply.dataSize()),
993 .reserved = {0, 0, 0},
Steven Moreland5553ac42020-11-11 02:14:45 +0000994 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000995 iovec iovs[]{
996 {&cmdReply, sizeof(RpcWireHeader)},
Frederick Mayledc07cf82022-05-26 20:30:12 +0000997 {&rpcReply, rpcReplyWireSize},
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000998 {const_cast<uint8_t*>(reply.data()), reply.dataSize()},
Frederick Mayledc07cf82022-05-26 20:30:12 +0000999 objectTableSpan.toIovec(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001000 };
Devin Moore695368f2022-06-03 22:29:14 +00001001 return rpcSend(connection, session, "reply", iovs, arraysize(iovs), std::nullopt);
Steven Moreland5553ac42020-11-11 02:14:45 +00001002}
1003
Steven Moreland5ae62562021-06-10 03:21:42 +00001004status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
1005 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001006 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
1007
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001008 if (command.bodySize != sizeof(RpcDecStrong)) {
1009 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcDecStrong. Terminating!",
1010 sizeof(RpcDecStrong), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001011 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001012 return BAD_VALUE;
1013 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001014
Frederick Mayleb86cda42022-06-09 23:17:45 +00001015 RpcDecStrong body;
1016 iovec iov{&body, sizeof(RpcDecStrong)};
1017 if (status_t status = rpcRec(connection, session, "dec ref body", &iov, 1); status != OK)
1018 return status;
1019
1020 uint64_t addr = RpcWireAddress::toRaw(body.address);
Steven Moreland5553ac42020-11-11 02:14:45 +00001021 std::unique_lock<std::mutex> _l(mNodeMutex);
1022 auto it = mNodeForAddress.find(addr);
1023 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001024 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001025 return OK;
1026 }
1027
1028 sp<IBinder> target = it->second.binder.promote();
1029 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001030 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
1031 ". Terminating!",
1032 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001033 _l.unlock();
1034 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001035 return BAD_VALUE;
1036 }
1037
Frederick Mayleb86cda42022-06-09 23:17:45 +00001038 if (it->second.timesSent < body.amount) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001039 ALOGE("Record of sending binder %zu times, but requested decStrong for %" PRIu64 " of %u",
Frederick Mayleb86cda42022-06-09 23:17:45 +00001040 it->second.timesSent, addr, body.amount);
Steven Moreland5553ac42020-11-11 02:14:45 +00001041 return OK;
1042 }
1043
Steven Moreland5623d1a2021-09-10 15:45:34 -07001044 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
1045 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001046
Frederick Mayleb86cda42022-06-09 23:17:45 +00001047 LOG_RPC_DETAIL("Processing dec strong of %" PRIu64 " by %u from %zu", addr, body.amount,
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001048 it->second.timesSent);
1049
Frederick Mayleb86cda42022-06-09 23:17:45 +00001050 it->second.timesSent -= body.amount;
Steven Moreland31bde7a2021-06-04 00:57:36 +00001051 sp<IBinder> tempHold = tryEraseNode(it);
1052 _l.unlock();
1053 tempHold = nullptr; // destructor may make binder calls on this session
1054
1055 return OK;
1056}
1057
Steven Moreland5623d1a2021-09-10 15:45:34 -07001058sp<IBinder> RpcState::tryEraseNode(std::map<uint64_t, BinderNode>::iterator& it) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001059 sp<IBinder> ref;
1060
Steven Moreland5553ac42020-11-11 02:14:45 +00001061 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001062 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +00001063
1064 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +00001065 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
1066 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +00001067 mNodeForAddress.erase(it);
1068 }
1069 }
1070
Steven Moreland31bde7a2021-06-04 00:57:36 +00001071 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +00001072}
1073
Steven Morelandc9d7b532021-06-04 20:57:41 +00001074bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +00001075 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
1076 // a single binder
1077 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
1078 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +00001079 return false;
1080 }
1081 node->asyncNumber++;
1082 return true;
1083}
1084
Steven Moreland5553ac42020-11-11 02:14:45 +00001085} // namespace android