blob: 2a8e9c1d8b908db448a288ea6923a1664c57a3f2 [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"
30
Steven Morelandb8176792021-06-22 20:29:21 +000031#include <random>
32
Steven Moreland5553ac42020-11-11 02:14:45 +000033#include <inttypes.h>
34
35namespace android {
36
Steven Morelandd7302072021-05-15 01:32:04 +000037using base::ScopeGuard;
38
Devin Moore08256432021-07-02 13:03:49 -070039#if RPC_FLAKE_PRONE
Steven Morelandb8176792021-06-22 20:29:21 +000040void rpcMaybeWaitToFlake() {
Devin Moore08256432021-07-02 13:03:49 -070041 [[clang::no_destroy]] static std::random_device r;
42 [[clang::no_destroy]] static std::mutex m;
Steven Morelandb8176792021-06-22 20:29:21 +000043 unsigned num;
44 {
45 std::lock_guard<std::mutex> lock(m);
46 num = r();
47 }
48 if (num % 10 == 0) usleep(num % 1000);
49}
50#endif
51
Steven Moreland5553ac42020-11-11 02:14:45 +000052RpcState::RpcState() {}
53RpcState::~RpcState() {}
54
Steven Morelandbdb53ab2021-05-05 17:57:41 +000055status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5623d1a2021-09-10 15:45:34 -070056 uint64_t* outAddress) {
Steven Moreland5553ac42020-11-11 02:14:45 +000057 bool isRemote = binder->remoteBinder();
58 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
59
Steven Moreland99157622021-09-13 16:27:34 -070060 if (isRpc && binder->remoteBinder()->getPrivateAccessor().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000061 // We need to be able to send instructions over the socket for how to
62 // connect to a different server, and we also need to let the host
63 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000064 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000065 return INVALID_OPERATION;
66 }
67
68 if (isRemote && !isRpc) {
69 // Without additional work, this would have the effect of using this
70 // process to proxy calls from the socket over to the other process, and
71 // it would make those calls look like they come from us (not over the
72 // sockets). In order to make this work transparently like binder, we
73 // would instead need to send instructions over the socket for how to
74 // connect to the host process, and we also need to let the host process
75 // know this was happening.
76 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
77 return INVALID_OPERATION;
78 }
79
80 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000081 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +000082
83 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
84 // in RpcState
85 for (auto& [addr, node] : mNodeForAddress) {
86 if (binder == node.binder) {
87 if (isRpc) {
Steven Moreland5623d1a2021-09-10 15:45:34 -070088 // check integrity of data structure
Steven Moreland99157622021-09-13 16:27:34 -070089 uint64_t actualAddr = binder->remoteBinder()->getPrivateAccessor().rpcAddress();
Steven Moreland5623d1a2021-09-10 15:45:34 -070090 LOG_ALWAYS_FATAL_IF(addr != actualAddr, "Address mismatch %" PRIu64 " vs %" PRIu64,
91 addr, actualAddr);
Steven Moreland5553ac42020-11-11 02:14:45 +000092 }
93 node.timesSent++;
94 node.sentRef = binder; // might already be set
95 *outAddress = addr;
96 return OK;
97 }
98 }
99 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
100
Steven Moreland91538242021-06-10 23:35:35 +0000101 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +0000102
Steven Moreland5623d1a2021-09-10 15:45:34 -0700103 // arbitrary limit for maximum number of nodes in a process (otherwise we
104 // might run out of addresses)
105 if (mNodeForAddress.size() > 100000) {
106 return NO_MEMORY;
107 }
108
109 while (true) {
110 RpcWireAddress address{
111 .options = RPC_WIRE_ADDRESS_OPTION_CREATED,
112 .address = mNextId,
113 };
114 if (forServer) {
115 address.options |= RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
116 }
117
118 // avoid ubsan abort
119 if (mNextId >= std::numeric_limits<uint32_t>::max()) {
120 mNextId = 0;
121 } else {
122 mNextId++;
123 }
124
125 auto&& [it, inserted] = mNodeForAddress.insert({RpcWireAddress::toRaw(address),
Steven Moreland91538242021-06-10 23:35:35 +0000126 BinderNode{
127 .binder = binder,
Steven Moreland91538242021-06-10 23:35:35 +0000128 .sentRef = binder,
Andrei Homescu5a036f32022-03-08 22:54:40 +0000129 .timesSent = 1,
Steven Moreland91538242021-06-10 23:35:35 +0000130 }});
131 if (inserted) {
132 *outAddress = it->first;
133 return OK;
134 }
Steven Moreland91538242021-06-10 23:35:35 +0000135 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000136}
137
Steven Moreland5623d1a2021-09-10 15:45:34 -0700138status_t RpcState::onBinderEntering(const sp<RpcSession>& session, uint64_t address,
Steven Moreland7227c8a2021-06-02 00:24:32 +0000139 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000140 // ensure that: if we want to use addresses for something else in the future (for
141 // instance, allowing transitive binder sends), that we don't accidentally
142 // send those addresses to old server. Accidentally ignoring this in that
143 // case and considering the binder to be recognized could cause this
144 // process to accidentally proxy transactions for that binder. Of course,
145 // if we communicate with a binder, it could always be proxying
146 // information. However, we want to make sure that isn't done on accident
147 // by a client.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700148 RpcWireAddress addr = RpcWireAddress::fromRaw(address);
149 constexpr uint32_t kKnownOptions =
150 RPC_WIRE_ADDRESS_OPTION_CREATED | RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
151 if (addr.options & ~kKnownOptions) {
152 ALOGE("Address is of an unknown type, rejecting: %" PRIu64, address);
Steven Moreland91538242021-06-10 23:35:35 +0000153 return BAD_VALUE;
154 }
155
Steven Morelandd8083312021-09-22 13:37:10 -0700156 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000157 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000158
159 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000160 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000161
162 // implicitly have strong RPC refcount, since we received this binder
163 it->second.timesRecd++;
Steven Morelandd8083312021-09-22 13:37:10 -0700164 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000165 }
166
Steven Moreland91538242021-06-10 23:35:35 +0000167 // we don't know about this binder, so the other side of the connection
168 // should have created it.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700169 if ((addr.options & RPC_WIRE_ADDRESS_OPTION_FOR_SERVER) == !!session->server()) {
170 ALOGE("Server received unrecognized address which we should own the creation of %" PRIu64,
171 address);
Steven Moreland91538242021-06-10 23:35:35 +0000172 return BAD_VALUE;
173 }
174
Steven Moreland5553ac42020-11-11 02:14:45 +0000175 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
176 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
177
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000178 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000179 // device global binders in the RPC world).
Steven Moreland99157622021-09-13 16:27:34 -0700180 it->second.binder = *out = BpBinder::PrivateAccessor::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000181 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000182 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000183}
184
Steven Morelandd8083312021-09-22 13:37:10 -0700185status_t RpcState::flushExcessBinderRefs(const sp<RpcSession>& session, uint64_t address,
186 const sp<IBinder>& binder) {
Steven Morelande96ed0e2021-09-27 17:43:53 -0700187 // We can flush all references when the binder is destroyed. No need to send
188 // extra reference counting packets now.
189 if (binder->remoteBinder()) return OK;
190
Steven Morelandd8083312021-09-22 13:37:10 -0700191 std::unique_lock<std::mutex> _l(mNodeMutex);
192 if (mTerminated) return DEAD_OBJECT;
193
194 auto it = mNodeForAddress.find(address);
195
196 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Can't be deleted while we hold sp<>");
197 LOG_ALWAYS_FATAL_IF(it->second.binder != binder,
198 "Caller of flushExcessBinderRefs using inconsistent arguments");
199
Steven Morelande96ed0e2021-09-27 17:43:53 -0700200 LOG_ALWAYS_FATAL_IF(it->second.timesSent <= 0, "Local binder must have been sent %p",
201 binder.get());
Steven Morelandd8083312021-09-22 13:37:10 -0700202
Steven Morelande96ed0e2021-09-27 17:43:53 -0700203 // For a local binder, we only need to know that we sent it. Now that we
204 // have an sp<> for this call, we don't need anything more. If the other
205 // process is done with this binder, it needs to know we received the
206 // refcount associated with this call, so we can acknowledge that we
207 // received it. Once (or if) it has no other refcounts, it would reply with
208 // its own decStrong so that it could be removed from this session.
209 if (it->second.timesRecd != 0) {
Steven Morelandd8083312021-09-22 13:37:10 -0700210 _l.unlock();
211
Steven Morelande96ed0e2021-09-27 17:43:53 -0700212 return session->sendDecStrongToTarget(address, 0);
Steven Morelandd8083312021-09-22 13:37:10 -0700213 }
214
215 return OK;
216}
217
Steven Moreland5553ac42020-11-11 02:14:45 +0000218size_t RpcState::countBinders() {
219 std::lock_guard<std::mutex> _l(mNodeMutex);
220 return mNodeForAddress.size();
221}
222
223void RpcState::dump() {
224 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000225 dumpLocked();
226}
227
Steven Morelandc9d7b532021-06-04 20:57:41 +0000228void RpcState::clear() {
Steven Moreland583a14a2021-06-04 02:04:58 +0000229 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000230
231 if (mTerminated) {
232 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
233 "New state should be impossible after terminating!");
234 return;
235 }
236
237 if (SHOULD_LOG_RPC_DETAIL) {
238 ALOGE("RpcState::clear()");
239 dumpLocked();
240 }
241
242 // if the destructor of a binder object makes another RPC call, then calling
243 // decStrong could deadlock. So, we must hold onto these binders until
244 // mNodeMutex is no longer taken.
245 std::vector<sp<IBinder>> tempHoldBinder;
246
247 mTerminated = true;
248 for (auto& [address, node] : mNodeForAddress) {
249 sp<IBinder> binder = node.binder.promote();
250 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
251
252 if (node.sentRef != nullptr) {
253 tempHoldBinder.push_back(node.sentRef);
254 }
255 }
256
257 mNodeForAddress.clear();
258
259 _l.unlock();
260 tempHoldBinder.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000261}
262
263void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000264 ALOGE("DUMP OF RpcState %p", this);
265 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
266 for (const auto& [address, node] : mNodeForAddress) {
267 sp<IBinder> binder = node.binder.promote();
268
269 const char* desc;
270 if (binder) {
271 if (binder->remoteBinder()) {
272 if (binder->remoteBinder()->isRpcBinder()) {
273 desc = "(rpc binder proxy)";
274 } else {
275 desc = "(binder proxy)";
276 }
277 } else {
278 desc = "(local binder)";
279 }
280 } else {
281 desc = "(null)";
282 }
283
Steven Moreland5623d1a2021-09-10 15:45:34 -0700284 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a: %" PRIu64 " type: %s",
285 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address, desc);
Steven Moreland5553ac42020-11-11 02:14:45 +0000286 }
287 ALOGE("END DUMP OF RpcState");
288}
289
Steven Moreland5553ac42020-11-11 02:14:45 +0000290
Steven Morelanddbe71832021-05-12 23:31:00 +0000291RpcState::CommandData::CommandData(size_t size) : mSize(size) {
292 // The maximum size for regular binder is 1MB for all concurrent
293 // transactions. A very small proportion of transactions are even
294 // larger than a page, but we need to avoid allocating too much
295 // data on behalf of an arbitrary client, or we could risk being in
296 // a position where a single additional allocation could run out of
297 // memory.
298 //
299 // Note, this limit may not reflect the total amount of data allocated for a
300 // transaction (in some cases, additional fixed size amounts are added),
301 // though for rough consistency, we should avoid cases where this data type
302 // is used for multiple dynamic allocations for a single transaction.
303 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
304 if (size == 0) return;
305 if (size > kMaxTransactionAllocation) {
306 ALOGW("Transaction requested too much data allocation %zu", size);
307 return;
308 }
309 mData.reset(new (std::nothrow) uint8_t[size]);
310}
311
Steven Moreland5ae62562021-06-10 03:21:42 +0000312status_t RpcState::rpcSend(const sp<RpcSession::RpcConnection>& connection,
Colin Cross9adfeaf2022-01-21 17:22:09 -0800313 const sp<RpcSession>& session, const char* what, iovec* iovs, int niovs,
314 const std::function<status_t()>& altPoll) {
315 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000316 LOG_RPC_DETAIL("Sending %s (part %d of %d) on RpcTransport %p: %s",
317 what, i + 1, niovs, connection->rpcTransport.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000318 android::base::HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000319 }
320
Yifan Hong702115c2021-06-24 15:39:18 -0700321 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700322 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000323 iovs, niovs, altPoll);
Steven Moreland798e0d12021-07-14 23:19:25 +0000324 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800325 LOG_RPC_DETAIL("Failed to write %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700326 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000327 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000328 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000329 }
330
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000331 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000332}
333
Steven Moreland5ae62562021-06-10 03:21:42 +0000334status_t RpcState::rpcRec(const sp<RpcSession::RpcConnection>& connection,
Colin Cross9adfeaf2022-01-21 17:22:09 -0800335 const sp<RpcSession>& session, const char* what, iovec* iovs, int niovs) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000336 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700337 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000338 iovs, niovs, {});
Steven Morelandee3f4662021-05-22 01:07:33 +0000339 status != OK) {
Colin Cross9adfeaf2022-01-21 17:22:09 -0800340 LOG_RPC_DETAIL("Failed to read %s (%d iovs) on RpcTransport %p, error: %s", what, niovs,
Yifan Hong702115c2021-06-24 15:39:18 -0700341 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandae58f432021-08-05 17:53:16 -0700342 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000343 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000344 }
345
Colin Cross9adfeaf2022-01-21 17:22:09 -0800346 for (int i = 0; i < niovs; i++) {
Andrei Homescu0a692352022-03-29 06:04:26 +0000347 LOG_RPC_DETAIL("Received %s (part %d of %d) on RpcTransport %p: %s",
348 what, i + 1, niovs, connection->rpcTransport.get(),
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000349 android::base::HexString(iovs[i].iov_base, iovs[i].iov_len).c_str());
350 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000351 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000352}
353
Steven Morelandbf57bce2021-07-26 15:26:12 -0700354status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
355 const sp<RpcSession>& session, uint32_t* version) {
356 RpcNewSessionResponse response;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000357 iovec iov{&response, sizeof(response)};
358 if (status_t status = rpcRec(connection, session, "new session response", &iov, 1);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700359 status != OK) {
360 return status;
361 }
362 *version = response.version;
363 return OK;
364}
365
Steven Moreland5ae62562021-06-10 03:21:42 +0000366status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
367 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000368 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000369 .msg = RPC_CONNECTION_INIT_OKAY,
370 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000371 iovec iov{&init, sizeof(init)};
372 return rpcSend(connection, session, "connection init", &iov, 1);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000373}
374
Steven Moreland5ae62562021-06-10 03:21:42 +0000375status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
376 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000377 RpcOutgoingConnectionInit init;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000378 iovec iov{&init, sizeof(init)};
379 if (status_t status = rpcRec(connection, session, "connection init", &iov, 1); status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000380 return status;
381
382 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
383 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
384 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
385 init.msg);
386 return BAD_VALUE;
387 }
388 return OK;
389}
390
Steven Moreland5ae62562021-06-10 03:21:42 +0000391sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
392 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000393 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000394 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000395 Parcel reply;
396
Steven Moreland5623d1a2021-09-10 15:45:34 -0700397 status_t status =
398 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000399 if (status != OK) {
400 ALOGE("Error getting root object: %s", statusToString(status).c_str());
401 return nullptr;
402 }
403
404 return reply.readStrongBinder();
405}
406
Steven Moreland5ae62562021-06-10 03:21:42 +0000407status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
408 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000409 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000410 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000411 Parcel reply;
412
Steven Moreland5623d1a2021-09-10 15:45:34 -0700413 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
414 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000415 if (status != OK) {
416 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
417 return status;
418 }
419
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000420 int32_t maxThreads;
421 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000422 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000423 if (maxThreads <= 0) {
424 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000425 return BAD_VALUE;
426 }
427
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000428 *maxThreadsOut = maxThreads;
429 return OK;
430}
431
Steven Moreland5ae62562021-06-10 03:21:42 +0000432status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700433 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000434 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000435 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000436 Parcel reply;
437
Steven Moreland5623d1a2021-09-10 15:45:34 -0700438 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
439 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000440 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000441 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000442 return status;
443 }
444
Steven Moreland826367f2021-09-10 14:05:31 -0700445 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000446}
447
Steven Moreland5ae62562021-06-10 03:21:42 +0000448status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
449 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
450 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000451 if (!data.isForRpc()) {
Steven Morelandcaf14b22021-09-27 18:18:35 -0700452 ALOGE("Refusing to send RPC with parcel not crafted for RPC call on binder %p code "
453 "%" PRIu32,
454 binder.get(), code);
Steven Morelandf5174272021-05-25 00:39:28 +0000455 return BAD_TYPE;
456 }
457
458 if (data.objectsCount() != 0) {
Steven Morelandcaf14b22021-09-27 18:18:35 -0700459 ALOGE("Parcel at %p has attached objects but is being used in an RPC call on binder %p "
460 "code %" PRIu32,
461 &data, binder.get(), code);
Steven Morelandf5174272021-05-25 00:39:28 +0000462 return BAD_TYPE;
463 }
464
Steven Moreland5623d1a2021-09-10 15:45:34 -0700465 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000466 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
467
Steven Moreland5ae62562021-06-10 03:21:42 +0000468 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000469}
470
Steven Moreland5ae62562021-06-10 03:21:42 +0000471status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700472 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000473 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000474 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
475 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
476
Steven Moreland5553ac42020-11-11 02:14:45 +0000477 uint64_t asyncNumber = 0;
478
Steven Moreland5623d1a2021-09-10 15:45:34 -0700479 if (address != 0) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000480 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000481 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
482 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700483 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
484 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000485
486 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000487 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000488 if (!nodeProgressAsyncNumber(&it->second)) {
489 _l.unlock();
490 (void)session->shutdownAndWait(false);
491 return DEAD_OBJECT;
492 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000493 }
494 }
495
Frederick Mayle778c0902022-05-27 01:14:57 +0000496 uint32_t bodySize;
497 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(sizeof(RpcWireTransaction), data.dataSize(),
498 &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +0000499 "Too much data %zu", data.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +0000500 RpcWireHeader command{
501 .command = RPC_COMMAND_TRANSACT,
Frederick Mayle778c0902022-05-27 01:14:57 +0000502 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +0000503 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700504
Steven Moreland5553ac42020-11-11 02:14:45 +0000505 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700506 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000507 .code = code,
508 .flags = flags,
509 .asyncNumber = asyncNumber,
510 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000511
Steven Moreland43921d52021-09-27 17:15:56 -0700512 constexpr size_t kWaitMaxUs = 1000000;
513 constexpr size_t kWaitLogUs = 10000;
514 size_t waitUs = 0;
515
516 // Oneway calls have no sync point, so if many are sent before, whether this
517 // is a twoway or oneway transaction, they may have filled up the socket.
518 // So, make sure we drain them before polling.
519 std::function<status_t()> drainRefs = [&] {
520 if (waitUs > kWaitLogUs) {
521 ALOGE("Cannot send command, trying to process pending refcounts. Waiting %zuus. Too "
522 "many oneway calls?",
523 waitUs);
524 }
525
526 if (waitUs > 0) {
527 usleep(waitUs);
528 waitUs = std::min(kWaitMaxUs, waitUs * 2);
529 } else {
530 waitUs = 1;
531 }
532
533 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
534 };
535
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000536 iovec iovs[]{
537 {&command, sizeof(RpcWireHeader)},
538 {&transaction, sizeof(RpcWireTransaction)},
539 {const_cast<uint8_t*>(data.data()), data.dataSize()},
540 };
541 if (status_t status =
542 rpcSend(connection, session, "transaction", iovs, arraysize(iovs), drainRefs);
Steven Moreland43921d52021-09-27 17:15:56 -0700543 status != OK) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000544 // TODO(b/167966510): need to undo onBinderLeaving - we know the
545 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000546 return status;
Steven Moreland43921d52021-09-27 17:15:56 -0700547 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000548
549 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700550 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
551 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000552
553 // Do not wait on result.
Steven Moreland43921d52021-09-27 17:15:56 -0700554 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000555 }
556
557 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
558
Steven Moreland5ae62562021-06-10 03:21:42 +0000559 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000560}
561
Steven Moreland438cce82021-04-02 18:04:08 +0000562static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
563 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000564 (void)p;
565 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
566 (void)dataSize;
567 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Yifan Hong239a2ca2021-06-24 16:05:16 -0700568 LOG_ALWAYS_FATAL_IF(objectsCount != 0, "%zu objects remaining", objectsCount);
Steven Moreland5553ac42020-11-11 02:14:45 +0000569}
570
Steven Moreland5ae62562021-06-10 03:21:42 +0000571status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
572 const sp<RpcSession>& session, Parcel* reply) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000573 RpcWireHeader command;
574 while (true) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000575 iovec iov{&command, sizeof(command)};
576 if (status_t status = rpcRec(connection, session, "command header (for reply)", &iov, 1);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000577 status != OK)
578 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000579
580 if (command.command == RPC_COMMAND_REPLY) break;
581
Steven Moreland19fc9f72021-06-10 03:57:30 +0000582 if (status_t status = processCommand(connection, session, command, CommandType::ANY);
Steven Moreland52eee942021-06-03 00:59:28 +0000583 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000584 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000585 }
586
Steven Morelanddbe71832021-05-12 23:31:00 +0000587 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000588 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000589
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000590 iovec iov{data.data(), command.bodySize};
591 if (status_t status = rpcRec(connection, session, "reply body", &iov, 1); status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000592 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000593
594 if (command.bodySize < sizeof(RpcWireReply)) {
595 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
596 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000597 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000598 return BAD_VALUE;
599 }
Steven Morelande8393342021-05-05 23:27:53 +0000600 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000601 if (rpcReply->status != OK) return rpcReply->status;
602
Steven Morelande8393342021-05-05 23:27:53 +0000603 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000604 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000605 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000606
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000607 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000608
609 return OK;
610}
611
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000612status_t RpcState::sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection,
613 const sp<RpcSession>& session, uint64_t addr,
614 size_t target) {
615 RpcDecStrong body = {
616 .address = RpcWireAddress::fromRaw(addr),
617 };
618
Steven Moreland5553ac42020-11-11 02:14:45 +0000619 {
620 std::lock_guard<std::mutex> _l(mNodeMutex);
621 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
622 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700623 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
624 "Sending dec strong on unknown address %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000625
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000626 LOG_ALWAYS_FATAL_IF(it->second.timesRecd < target, "Can't dec count of %zu to %zu.",
627 it->second.timesRecd, target);
628
629 // typically this happens when multiple threads send dec refs at the
630 // same time - the transactions will get combined automatically
631 if (it->second.timesRecd == target) return OK;
632
633 body.amount = it->second.timesRecd - target;
634 it->second.timesRecd = target;
635
Steven Moreland31bde7a2021-06-04 00:57:36 +0000636 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
637 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000638 }
639
640 RpcWireHeader cmd = {
641 .command = RPC_COMMAND_DEC_STRONG,
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000642 .bodySize = sizeof(RpcDecStrong),
Steven Moreland5553ac42020-11-11 02:14:45 +0000643 };
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000644 iovec iovs[]{{&cmd, sizeof(cmd)}, {&body, sizeof(body)}};
645 return rpcSend(connection, session, "dec ref", iovs, arraysize(iovs));
Steven Moreland5553ac42020-11-11 02:14:45 +0000646}
647
Steven Moreland5ae62562021-06-10 03:21:42 +0000648status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
649 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700650 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000651
652 RpcWireHeader command;
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000653 iovec iov{&command, sizeof(command)};
654 if (status_t status = rpcRec(connection, session, "command header (for server)", &iov, 1);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000655 status != OK)
656 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000657
Steven Moreland19fc9f72021-06-10 03:57:30 +0000658 return processCommand(connection, session, command, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000659}
660
Steven Moreland5ae62562021-06-10 03:21:42 +0000661status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
662 const sp<RpcSession>& session, CommandType type) {
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000663 while (true) {
Andrei Homescu1975aaa2022-03-19 02:34:57 +0000664 status_t status = connection->rpcTransport->pollRead();
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000665 if (status == WOULD_BLOCK) break;
666 if (status != OK) return status;
Andrei Homescu5ad71b52022-03-11 03:49:12 +0000667
668 status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000669 if (status != OK) return status;
670 }
671 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000672}
673
Steven Moreland19fc9f72021-06-10 03:57:30 +0000674status_t RpcState::processCommand(const sp<RpcSession::RpcConnection>& connection,
675 const sp<RpcSession>& session, const RpcWireHeader& command,
676 CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000677 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
678 IPCThreadState::SpGuard spGuard{
679 .address = __builtin_frame_address(0),
680 .context = "processing binder RPC command",
681 };
682 const IPCThreadState::SpGuard* origGuard;
683 if (kernelBinderState != nullptr) {
684 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
685 }
686 ScopeGuard guardUnguard = [&]() {
687 if (kernelBinderState != nullptr) {
688 kernelBinderState->restoreGetCallingSpGuard(origGuard);
689 }
690 };
691
Steven Moreland5553ac42020-11-11 02:14:45 +0000692 switch (command.command) {
693 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000694 if (type != CommandType::ANY) return BAD_TYPE;
Steven Moreland5ae62562021-06-10 03:21:42 +0000695 return processTransact(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000696 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000697 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000698 }
699
700 // We should always know the version of the opposing side, and since the
701 // RPC-binder-level wire protocol is not self synchronizing, we have no way
702 // to understand where the current command ends and the next one begins. We
703 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000704 // to kill us, so ending the session for misbehaving client.
705 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000706 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000707 return DEAD_OBJECT;
708}
Steven Moreland5ae62562021-06-10 03:21:42 +0000709status_t RpcState::processTransact(const sp<RpcSession::RpcConnection>& connection,
710 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000711 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
712
Steven Morelanddbe71832021-05-12 23:31:00 +0000713 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000714 if (!transactionData.valid()) {
715 return NO_MEMORY;
716 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000717 iovec iov{transactionData.data(), transactionData.size()};
718 if (status_t status = rpcRec(connection, session, "transaction body", &iov, 1); status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000719 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000720
Steven Moreland5ae62562021-06-10 03:21:42 +0000721 return processTransactInternal(connection, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000722}
723
Steven Moreland438cce82021-04-02 18:04:08 +0000724static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
725 const binder_size_t* objects, size_t objectsCount) {
726 (void)p;
727 (void)data;
728 (void)dataSize;
729 (void)objects;
730 (void)objectsCount;
731}
732
Steven Moreland5ae62562021-06-10 03:21:42 +0000733status_t RpcState::processTransactInternal(const sp<RpcSession::RpcConnection>& connection,
734 const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000735 CommandData transactionData) {
736 // for 'recursive' calls to this, we have already read and processed the
737 // binder from the transaction data and taken reference counts into account,
738 // so it is cached here.
Steven Moreland3903bf02021-09-27 16:05:24 -0700739 sp<IBinder> target;
Steven Morelandada72bd2021-06-09 23:29:13 +0000740processTransactInternalTailCall:
741
Steven Moreland5553ac42020-11-11 02:14:45 +0000742 if (transactionData.size() < sizeof(RpcWireTransaction)) {
743 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
744 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000745 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000746 return BAD_VALUE;
747 }
748 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
749
Steven Moreland5623d1a2021-09-10 15:45:34 -0700750 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000751 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000752
753 status_t replyStatus = OK;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700754 if (addr != 0) {
Steven Moreland3903bf02021-09-27 16:05:24 -0700755 if (!target) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000756 replyStatus = onBinderEntering(session, addr, &target);
Steven Morelandf5174272021-05-25 00:39:28 +0000757 }
758
Steven Moreland7227c8a2021-06-02 00:24:32 +0000759 if (replyStatus != OK) {
760 // do nothing
761 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000762 // This can happen if the binder is remote in this process, and
763 // another thread has called the last decStrong on this binder.
764 // However, for local binders, it indicates a misbehaving client
765 // (any binder which is being transacted on should be holding a
766 // strong ref count), so in either case, terminating the
767 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700768 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
769 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000770 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000771 replyStatus = BAD_VALUE;
772 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700773 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
774 ". Terminating!",
775 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000776 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000777 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000778 } else if (oneway) {
Steven Morelandd45be622021-06-04 02:19:37 +0000779 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000780 auto it = mNodeForAddress.find(addr);
781 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700782 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000783 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000784 } else if (transaction->asyncNumber != it->second.asyncNumber) {
785 // we need to process some other asynchronous transaction
786 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000787 it->second.asyncTodo.push(BinderNode::AsyncTodo{
788 .ref = target,
789 .data = std::move(transactionData),
790 .asyncNumber = transaction->asyncNumber,
791 });
Steven Morelandd45be622021-06-04 02:19:37 +0000792
793 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700794 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
795 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000796
797 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
798 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
799 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
800
801 if (numPending >= kArbitraryOnewayCallWarnLevel) {
802 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
803 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
804 _l.unlock();
805 (void)session->shutdownAndWait(false);
806 return FAILED_TRANSACTION;
807 }
808
809 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
810 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
811 target.get(), numPending);
812 }
813 }
Steven Morelandf5174272021-05-25 00:39:28 +0000814 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000815 }
816 }
817 }
818
Steven Moreland5553ac42020-11-11 02:14:45 +0000819 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000820 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000821
822 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000823 Parcel data;
824 // transaction->data is owned by this function. Parcel borrows this data and
825 // only holds onto it for the duration of this function call. Parcel will be
826 // deleted before the 'transactionData' object.
827 data.ipcSetDataReference(transaction->data,
828 transactionData.size() - offsetof(RpcWireTransaction, data),
829 nullptr /*object*/, 0 /*objectCount*/,
830 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000831 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000832
Steven Moreland5553ac42020-11-11 02:14:45 +0000833 if (target) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000834 bool origAllowNested = connection->allowNested;
835 connection->allowNested = !oneway;
836
Steven Moreland5553ac42020-11-11 02:14:45 +0000837 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000838
839 connection->allowNested = origAllowNested;
Steven Moreland5553ac42020-11-11 02:14:45 +0000840 } else {
841 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000842
Steven Moreland103424e2021-06-02 18:16:19 +0000843 switch (transaction->code) {
844 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
Yifan Hong10423062021-10-08 16:26:32 -0700845 replyStatus = reply.writeInt32(session->getMaxIncomingThreads());
Steven Moreland103424e2021-06-02 18:16:19 +0000846 break;
847 }
848 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
849 // for client connections, this should always report the value
Steven Moreland01a6bad2021-06-11 00:59:20 +0000850 // originally returned from the server, so this is asserting
851 // that it exists
Steven Moreland826367f2021-09-10 14:05:31 -0700852 replyStatus = reply.writeByteVector(session->mId);
Steven Moreland103424e2021-06-02 18:16:19 +0000853 break;
854 }
855 default: {
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000856 sp<RpcServer> server = session->server();
Steven Moreland103424e2021-06-02 18:16:19 +0000857 if (server) {
858 switch (transaction->code) {
859 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
Steven Moreland51c44a92021-10-14 16:50:35 -0700860 sp<IBinder> root = session->mSessionSpecificRootObject
861 ?: server->getRootObject();
862 replyStatus = reply.writeStrongBinder(root);
Steven Moreland103424e2021-06-02 18:16:19 +0000863 break;
864 }
865 default: {
866 replyStatus = UNKNOWN_TRANSACTION;
867 }
868 }
869 } else {
870 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000871 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000872 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000873 }
874 }
875 }
876
Steven Morelandc7d40132021-06-10 03:42:11 +0000877 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000878 if (replyStatus != OK) {
879 ALOGW("Oneway call failed with error: %d", replyStatus);
880 }
881
Steven Moreland5623d1a2021-09-10 15:45:34 -0700882 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
883 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000884
885 // Check to see if there is another asynchronous transaction to process.
886 // This behavior differs from binder behavior, since in the binder
887 // driver, asynchronous transactions will be processed after existing
888 // pending binder transactions on the queue. The downside of this is
889 // that asynchronous transactions can be drowned out by synchronous
890 // transactions. However, we have no easy way to queue these
891 // transactions after the synchronous transactions we may want to read
892 // from the wire. So, in socket binder here, we have the opposite
893 // downside: asynchronous transactions may drown out synchronous
894 // transactions.
895 {
896 std::unique_lock<std::mutex> _l(mNodeMutex);
897 auto it = mNodeForAddress.find(addr);
898 // last refcount dropped after this transaction happened
899 if (it == mNodeForAddress.end()) return OK;
900
Steven Morelandc9d7b532021-06-04 20:57:41 +0000901 if (!nodeProgressAsyncNumber(&it->second)) {
902 _l.unlock();
903 (void)session->shutdownAndWait(false);
904 return DEAD_OBJECT;
905 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000906
907 if (it->second.asyncTodo.size() == 0) return OK;
908 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700909 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
910 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000911
912 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000913 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000914 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000915 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
916
Steven Morelandada72bd2021-06-09 23:29:13 +0000917 // reset up arguments
918 transactionData = std::move(todo.data);
Steven Moreland3903bf02021-09-27 16:05:24 -0700919 LOG_ALWAYS_FATAL_IF(target != todo.ref,
920 "async list should be associated with a binder");
Steven Morelandf5174272021-05-25 00:39:28 +0000921
Steven Moreland5553ac42020-11-11 02:14:45 +0000922 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000923 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000924 }
925 }
Steven Morelandd8083312021-09-22 13:37:10 -0700926
927 // done processing all the async commands on this binder that we can, so
928 // write decstrongs on the binder
929 if (addr != 0 && replyStatus == OK) {
930 return flushExcessBinderRefs(session, addr, target);
931 }
932
Steven Moreland5553ac42020-11-11 02:14:45 +0000933 return OK;
934 }
935
Steven Moreland6709cf42021-09-30 15:21:54 -0700936 // Binder refs are flushed for oneway calls only after all calls which are
937 // built up are executed. Otherwise, they fill up the binder buffer.
938 if (addr != 0 && replyStatus == OK) {
939 replyStatus = flushExcessBinderRefs(session, addr, target);
940 }
941
Frederick Mayle778c0902022-05-27 01:14:57 +0000942 uint32_t bodySize;
943 LOG_ALWAYS_FATAL_IF(__builtin_add_overflow(sizeof(RpcWireReply), reply.dataSize(), &bodySize),
Steven Moreland77c30112021-06-02 20:45:46 +0000944 "Too much data for reply %zu", reply.dataSize());
Steven Moreland77c30112021-06-02 20:45:46 +0000945 RpcWireHeader cmdReply{
946 .command = RPC_COMMAND_REPLY,
Frederick Mayle778c0902022-05-27 01:14:57 +0000947 .bodySize = bodySize,
Steven Moreland77c30112021-06-02 20:45:46 +0000948 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000949 RpcWireReply rpcReply{
950 .status = replyStatus,
951 };
952
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000953 iovec iovs[]{
954 {&cmdReply, sizeof(RpcWireHeader)},
955 {&rpcReply, sizeof(RpcWireReply)},
956 {const_cast<uint8_t*>(reply.data()), reply.dataSize()},
957 };
958 return rpcSend(connection, session, "reply", iovs, arraysize(iovs));
Steven Moreland5553ac42020-11-11 02:14:45 +0000959}
960
Steven Moreland5ae62562021-06-10 03:21:42 +0000961status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
962 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000963 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
964
Steven Morelanddbe71832021-05-12 23:31:00 +0000965 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000966 if (!commandData.valid()) {
967 return NO_MEMORY;
968 }
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000969 iovec iov{commandData.data(), commandData.size()};
970 if (status_t status = rpcRec(connection, session, "dec ref body", &iov, 1); status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000971 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000972
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000973 if (command.bodySize != sizeof(RpcDecStrong)) {
974 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcDecStrong. Terminating!",
975 sizeof(RpcDecStrong), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000976 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000977 return BAD_VALUE;
978 }
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000979 RpcDecStrong* body = reinterpret_cast<RpcDecStrong*>(commandData.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000980
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000981 uint64_t addr = RpcWireAddress::toRaw(body->address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000982 std::unique_lock<std::mutex> _l(mNodeMutex);
983 auto it = mNodeForAddress.find(addr);
984 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700985 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000986 return OK;
987 }
988
989 sp<IBinder> target = it->second.binder.promote();
990 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700991 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
992 ". Terminating!",
993 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000994 _l.unlock();
995 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000996 return BAD_VALUE;
997 }
998
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000999 if (it->second.timesSent < body->amount) {
1000 ALOGE("Record of sending binder %zu times, but requested decStrong for %" PRIu64 " of %u",
1001 it->second.timesSent, addr, body->amount);
Steven Moreland5553ac42020-11-11 02:14:45 +00001002 return OK;
1003 }
1004
Steven Moreland5623d1a2021-09-10 15:45:34 -07001005 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
1006 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001007
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001008 LOG_RPC_DETAIL("Processing dec strong of %" PRIu64 " by %u from %zu", addr, body->amount,
1009 it->second.timesSent);
1010
1011 it->second.timesSent -= body->amount;
Steven Moreland31bde7a2021-06-04 00:57:36 +00001012 sp<IBinder> tempHold = tryEraseNode(it);
1013 _l.unlock();
1014 tempHold = nullptr; // destructor may make binder calls on this session
1015
1016 return OK;
1017}
1018
Steven Moreland5623d1a2021-09-10 15:45:34 -07001019sp<IBinder> RpcState::tryEraseNode(std::map<uint64_t, BinderNode>::iterator& it) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001020 sp<IBinder> ref;
1021
Steven Moreland5553ac42020-11-11 02:14:45 +00001022 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001023 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +00001024
1025 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +00001026 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
1027 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +00001028 mNodeForAddress.erase(it);
1029 }
1030 }
1031
Steven Moreland31bde7a2021-06-04 00:57:36 +00001032 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +00001033}
1034
Steven Morelandc9d7b532021-06-04 20:57:41 +00001035bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +00001036 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
1037 // a single binder
1038 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
1039 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +00001040 return false;
1041 }
1042 node->asyncNumber++;
1043 return true;
1044}
1045
Steven Moreland5553ac42020-11-11 02:14:45 +00001046} // namespace android