blob: 09b3d686263501738cadc8b3241036759e88e03e [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>
Steven Morelandd7302072021-05-15 01:32:04 +000022#include <android-base/scopeguard.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000023#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000024#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000025#include <binder/RpcServer.h>
26
27#include "Debug.h"
28#include "RpcWireFormat.h"
29
Steven Morelandb8176792021-06-22 20:29:21 +000030#include <random>
31
Steven Moreland5553ac42020-11-11 02:14:45 +000032#include <inttypes.h>
33
34namespace android {
35
Steven Morelandd7302072021-05-15 01:32:04 +000036using base::ScopeGuard;
37
Devin Moore08256432021-07-02 13:03:49 -070038#if RPC_FLAKE_PRONE
Steven Morelandb8176792021-06-22 20:29:21 +000039void rpcMaybeWaitToFlake() {
Devin Moore08256432021-07-02 13:03:49 -070040 [[clang::no_destroy]] static std::random_device r;
41 [[clang::no_destroy]] static std::mutex m;
Steven Morelandb8176792021-06-22 20:29:21 +000042 unsigned num;
43 {
44 std::lock_guard<std::mutex> lock(m);
45 num = r();
46 }
47 if (num % 10 == 0) usleep(num % 1000);
48}
49#endif
50
Steven Moreland5553ac42020-11-11 02:14:45 +000051RpcState::RpcState() {}
52RpcState::~RpcState() {}
53
Steven Morelandbdb53ab2021-05-05 17:57:41 +000054status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5623d1a2021-09-10 15:45:34 -070055 uint64_t* outAddress) {
Steven Moreland5553ac42020-11-11 02:14:45 +000056 bool isRemote = binder->remoteBinder();
57 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
58
Steven Moreland99157622021-09-13 16:27:34 -070059 if (isRpc && binder->remoteBinder()->getPrivateAccessor().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000060 // We need to be able to send instructions over the socket for how to
61 // connect to a different server, and we also need to let the host
62 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000063 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000064 return INVALID_OPERATION;
65 }
66
67 if (isRemote && !isRpc) {
68 // Without additional work, this would have the effect of using this
69 // process to proxy calls from the socket over to the other process, and
70 // it would make those calls look like they come from us (not over the
71 // sockets). In order to make this work transparently like binder, we
72 // would instead need to send instructions over the socket for how to
73 // connect to the host process, and we also need to let the host process
74 // know this was happening.
75 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
76 return INVALID_OPERATION;
77 }
78
79 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000080 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +000081
82 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
83 // in RpcState
84 for (auto& [addr, node] : mNodeForAddress) {
85 if (binder == node.binder) {
86 if (isRpc) {
Steven Moreland5623d1a2021-09-10 15:45:34 -070087 // check integrity of data structure
Steven Moreland99157622021-09-13 16:27:34 -070088 uint64_t actualAddr = binder->remoteBinder()->getPrivateAccessor().rpcAddress();
Steven Moreland5623d1a2021-09-10 15:45:34 -070089 LOG_ALWAYS_FATAL_IF(addr != actualAddr, "Address mismatch %" PRIu64 " vs %" PRIu64,
90 addr, actualAddr);
Steven Moreland5553ac42020-11-11 02:14:45 +000091 }
92 node.timesSent++;
93 node.sentRef = binder; // might already be set
94 *outAddress = addr;
95 return OK;
96 }
97 }
98 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
99
Steven Moreland91538242021-06-10 23:35:35 +0000100 bool forServer = session->server() != nullptr;
Steven Moreland5553ac42020-11-11 02:14:45 +0000101
Steven Moreland5623d1a2021-09-10 15:45:34 -0700102 // arbitrary limit for maximum number of nodes in a process (otherwise we
103 // might run out of addresses)
104 if (mNodeForAddress.size() > 100000) {
105 return NO_MEMORY;
106 }
107
108 while (true) {
109 RpcWireAddress address{
110 .options = RPC_WIRE_ADDRESS_OPTION_CREATED,
111 .address = mNextId,
112 };
113 if (forServer) {
114 address.options |= RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
115 }
116
117 // avoid ubsan abort
118 if (mNextId >= std::numeric_limits<uint32_t>::max()) {
119 mNextId = 0;
120 } else {
121 mNextId++;
122 }
123
124 auto&& [it, inserted] = mNodeForAddress.insert({RpcWireAddress::toRaw(address),
Steven Moreland91538242021-06-10 23:35:35 +0000125 BinderNode{
126 .binder = binder,
127 .timesSent = 1,
128 .sentRef = binder,
129 }});
130 if (inserted) {
131 *outAddress = it->first;
132 return OK;
133 }
Steven Moreland91538242021-06-10 23:35:35 +0000134 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000135}
136
Steven Moreland5623d1a2021-09-10 15:45:34 -0700137status_t RpcState::onBinderEntering(const sp<RpcSession>& session, uint64_t address,
Steven Moreland7227c8a2021-06-02 00:24:32 +0000138 sp<IBinder>* out) {
Steven Moreland91538242021-06-10 23:35:35 +0000139 // ensure that: if we want to use addresses for something else in the future (for
140 // instance, allowing transitive binder sends), that we don't accidentally
141 // send those addresses to old server. Accidentally ignoring this in that
142 // case and considering the binder to be recognized could cause this
143 // process to accidentally proxy transactions for that binder. Of course,
144 // if we communicate with a binder, it could always be proxying
145 // information. However, we want to make sure that isn't done on accident
146 // by a client.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700147 RpcWireAddress addr = RpcWireAddress::fromRaw(address);
148 constexpr uint32_t kKnownOptions =
149 RPC_WIRE_ADDRESS_OPTION_CREATED | RPC_WIRE_ADDRESS_OPTION_FOR_SERVER;
150 if (addr.options & ~kKnownOptions) {
151 ALOGE("Address is of an unknown type, rejecting: %" PRIu64, address);
Steven Moreland91538242021-06-10 23:35:35 +0000152 return BAD_VALUE;
153 }
154
Steven Morelandd8083312021-09-22 13:37:10 -0700155 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000156 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000157
158 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000159 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000160
161 // implicitly have strong RPC refcount, since we received this binder
162 it->second.timesRecd++;
Steven Morelandd8083312021-09-22 13:37:10 -0700163 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000164 }
165
Steven Moreland91538242021-06-10 23:35:35 +0000166 // we don't know about this binder, so the other side of the connection
167 // should have created it.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700168 if ((addr.options & RPC_WIRE_ADDRESS_OPTION_FOR_SERVER) == !!session->server()) {
169 ALOGE("Server received unrecognized address which we should own the creation of %" PRIu64,
170 address);
Steven Moreland91538242021-06-10 23:35:35 +0000171 return BAD_VALUE;
172 }
173
Steven Moreland5553ac42020-11-11 02:14:45 +0000174 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
175 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
176
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000177 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000178 // device global binders in the RPC world).
Steven Moreland99157622021-09-13 16:27:34 -0700179 it->second.binder = *out = BpBinder::PrivateAccessor::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000180 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000181 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000182}
183
Steven Morelandd8083312021-09-22 13:37:10 -0700184status_t RpcState::flushExcessBinderRefs(const sp<RpcSession>& session, uint64_t address,
185 const sp<IBinder>& binder) {
Steven Morelande96ed0e2021-09-27 17:43:53 -0700186 // We can flush all references when the binder is destroyed. No need to send
187 // extra reference counting packets now.
188 if (binder->remoteBinder()) return OK;
189
Steven Morelandd8083312021-09-22 13:37:10 -0700190 std::unique_lock<std::mutex> _l(mNodeMutex);
191 if (mTerminated) return DEAD_OBJECT;
192
193 auto it = mNodeForAddress.find(address);
194
195 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Can't be deleted while we hold sp<>");
196 LOG_ALWAYS_FATAL_IF(it->second.binder != binder,
197 "Caller of flushExcessBinderRefs using inconsistent arguments");
198
Steven Morelande96ed0e2021-09-27 17:43:53 -0700199 LOG_ALWAYS_FATAL_IF(it->second.timesSent <= 0, "Local binder must have been sent %p",
200 binder.get());
Steven Morelandd8083312021-09-22 13:37:10 -0700201
Steven Morelande96ed0e2021-09-27 17:43:53 -0700202 // For a local binder, we only need to know that we sent it. Now that we
203 // have an sp<> for this call, we don't need anything more. If the other
204 // process is done with this binder, it needs to know we received the
205 // refcount associated with this call, so we can acknowledge that we
206 // received it. Once (or if) it has no other refcounts, it would reply with
207 // its own decStrong so that it could be removed from this session.
208 if (it->second.timesRecd != 0) {
Steven Morelandd8083312021-09-22 13:37:10 -0700209 _l.unlock();
210
Steven Morelande96ed0e2021-09-27 17:43:53 -0700211 return session->sendDecStrongToTarget(address, 0);
Steven Morelandd8083312021-09-22 13:37:10 -0700212 }
213
214 return OK;
215}
216
Steven Moreland5553ac42020-11-11 02:14:45 +0000217size_t RpcState::countBinders() {
218 std::lock_guard<std::mutex> _l(mNodeMutex);
219 return mNodeForAddress.size();
220}
221
222void RpcState::dump() {
223 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000224 dumpLocked();
225}
226
Steven Morelandc9d7b532021-06-04 20:57:41 +0000227void RpcState::clear() {
Steven Moreland583a14a2021-06-04 02:04:58 +0000228 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000229
230 if (mTerminated) {
231 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
232 "New state should be impossible after terminating!");
233 return;
234 }
235
236 if (SHOULD_LOG_RPC_DETAIL) {
237 ALOGE("RpcState::clear()");
238 dumpLocked();
239 }
240
241 // if the destructor of a binder object makes another RPC call, then calling
242 // decStrong could deadlock. So, we must hold onto these binders until
243 // mNodeMutex is no longer taken.
244 std::vector<sp<IBinder>> tempHoldBinder;
245
246 mTerminated = true;
247 for (auto& [address, node] : mNodeForAddress) {
248 sp<IBinder> binder = node.binder.promote();
249 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
250
251 if (node.sentRef != nullptr) {
252 tempHoldBinder.push_back(node.sentRef);
253 }
254 }
255
256 mNodeForAddress.clear();
257
258 _l.unlock();
259 tempHoldBinder.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000260}
261
262void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000263 ALOGE("DUMP OF RpcState %p", this);
264 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
265 for (const auto& [address, node] : mNodeForAddress) {
266 sp<IBinder> binder = node.binder.promote();
267
268 const char* desc;
269 if (binder) {
270 if (binder->remoteBinder()) {
271 if (binder->remoteBinder()->isRpcBinder()) {
272 desc = "(rpc binder proxy)";
273 } else {
274 desc = "(binder proxy)";
275 }
276 } else {
277 desc = "(local binder)";
278 }
279 } else {
280 desc = "(null)";
281 }
282
Steven Moreland5623d1a2021-09-10 15:45:34 -0700283 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a: %" PRIu64 " type: %s",
284 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address, desc);
Steven Moreland5553ac42020-11-11 02:14:45 +0000285 }
286 ALOGE("END DUMP OF RpcState");
287}
288
Steven Moreland5553ac42020-11-11 02:14:45 +0000289
Steven Morelanddbe71832021-05-12 23:31:00 +0000290RpcState::CommandData::CommandData(size_t size) : mSize(size) {
291 // The maximum size for regular binder is 1MB for all concurrent
292 // transactions. A very small proportion of transactions are even
293 // larger than a page, but we need to avoid allocating too much
294 // data on behalf of an arbitrary client, or we could risk being in
295 // a position where a single additional allocation could run out of
296 // memory.
297 //
298 // Note, this limit may not reflect the total amount of data allocated for a
299 // transaction (in some cases, additional fixed size amounts are added),
300 // though for rough consistency, we should avoid cases where this data type
301 // is used for multiple dynamic allocations for a single transaction.
302 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
303 if (size == 0) return;
304 if (size > kMaxTransactionAllocation) {
305 ALOGW("Transaction requested too much data allocation %zu", size);
306 return;
307 }
308 mData.reset(new (std::nothrow) uint8_t[size]);
309}
310
Steven Moreland5ae62562021-06-10 03:21:42 +0000311status_t RpcState::rpcSend(const sp<RpcSession::RpcConnection>& connection,
312 const sp<RpcSession>& session, const char* what, const void* data,
Steven Moreland43921d52021-09-27 17:15:56 -0700313 size_t size, const std::function<status_t()>& altPoll) {
Yifan Hong702115c2021-06-24 15:39:18 -0700314 LOG_RPC_DETAIL("Sending %s on RpcTransport %p: %s", what, connection->rpcTransport.get(),
Steven Moreland62129012021-07-29 12:14:44 -0700315 android::base::HexString(data, size).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000316
317 if (size > std::numeric_limits<ssize_t>::max()) {
318 ALOGE("Cannot send %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000319 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000320 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000321 }
322
Yifan Hong702115c2021-06-24 15:39:18 -0700323 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700324 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
Steven Moreland43921d52021-09-27 17:15:56 -0700325 data, size, altPoll);
Steven Moreland798e0d12021-07-14 23:19:25 +0000326 status != OK) {
Yifan Hong702115c2021-06-24 15:39:18 -0700327 LOG_RPC_DETAIL("Failed to write %s (%zu bytes) on RpcTransport %p, error: %s", what, size,
328 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000329 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000330 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000331 }
332
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000333 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000334}
335
Steven Moreland5ae62562021-06-10 03:21:42 +0000336status_t RpcState::rpcRec(const sp<RpcSession::RpcConnection>& connection,
337 const sp<RpcSession>& session, const char* what, void* data,
338 size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000339 if (size > std::numeric_limits<ssize_t>::max()) {
340 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000341 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000342 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000343 }
344
Steven Moreland5ae62562021-06-10 03:21:42 +0000345 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700346 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
Steven Moreland43921d52021-09-27 17:15:56 -0700347 data, size, {});
Steven Morelandee3f4662021-05-22 01:07:33 +0000348 status != OK) {
Yifan Hong702115c2021-06-24 15:39:18 -0700349 LOG_RPC_DETAIL("Failed to read %s (%zu bytes) on RpcTransport %p, error: %s", what, size,
350 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandae58f432021-08-05 17:53:16 -0700351 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000352 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000353 }
354
Yifan Hong702115c2021-06-24 15:39:18 -0700355 LOG_RPC_DETAIL("Received %s on RpcTransport %p: %s", what, connection->rpcTransport.get(),
Steven Moreland62129012021-07-29 12:14:44 -0700356 android::base::HexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000357 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000358}
359
Steven Morelandbf57bce2021-07-26 15:26:12 -0700360status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
361 const sp<RpcSession>& session, uint32_t* version) {
362 RpcNewSessionResponse response;
363 if (status_t status =
364 rpcRec(connection, session, "new session response", &response, sizeof(response));
365 status != OK) {
366 return status;
367 }
368 *version = response.version;
369 return OK;
370}
371
Steven Moreland5ae62562021-06-10 03:21:42 +0000372status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
373 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000374 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000375 .msg = RPC_CONNECTION_INIT_OKAY,
376 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000377 return rpcSend(connection, session, "connection init", &init, sizeof(init));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000378}
379
Steven Moreland5ae62562021-06-10 03:21:42 +0000380status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
381 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000382 RpcOutgoingConnectionInit init;
Steven Moreland5ae62562021-06-10 03:21:42 +0000383 if (status_t status = rpcRec(connection, session, "connection init", &init, sizeof(init));
384 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000385 return status;
386
387 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
388 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
389 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
390 init.msg);
391 return BAD_VALUE;
392 }
393 return OK;
394}
395
Steven Moreland5ae62562021-06-10 03:21:42 +0000396sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
397 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000398 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000399 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000400 Parcel reply;
401
Steven Moreland5623d1a2021-09-10 15:45:34 -0700402 status_t status =
403 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000404 if (status != OK) {
405 ALOGE("Error getting root object: %s", statusToString(status).c_str());
406 return nullptr;
407 }
408
409 return reply.readStrongBinder();
410}
411
Steven Moreland5ae62562021-06-10 03:21:42 +0000412status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
413 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000414 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000415 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000416 Parcel reply;
417
Steven Moreland5623d1a2021-09-10 15:45:34 -0700418 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
419 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000420 if (status != OK) {
421 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
422 return status;
423 }
424
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000425 int32_t maxThreads;
426 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000427 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000428 if (maxThreads <= 0) {
429 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000430 return BAD_VALUE;
431 }
432
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000433 *maxThreadsOut = maxThreads;
434 return OK;
435}
436
Steven Moreland5ae62562021-06-10 03:21:42 +0000437status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700438 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000439 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000440 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000441 Parcel reply;
442
Steven Moreland5623d1a2021-09-10 15:45:34 -0700443 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
444 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000445 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000446 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000447 return status;
448 }
449
Steven Moreland826367f2021-09-10 14:05:31 -0700450 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000451}
452
Steven Moreland5ae62562021-06-10 03:21:42 +0000453status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
454 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
455 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000456 if (!data.isForRpc()) {
Steven Morelandcaf14b22021-09-27 18:18:35 -0700457 ALOGE("Refusing to send RPC with parcel not crafted for RPC call on binder %p code "
458 "%" PRIu32,
459 binder.get(), code);
Steven Morelandf5174272021-05-25 00:39:28 +0000460 return BAD_TYPE;
461 }
462
463 if (data.objectsCount() != 0) {
Steven Morelandcaf14b22021-09-27 18:18:35 -0700464 ALOGE("Parcel at %p has attached objects but is being used in an RPC call on binder %p "
465 "code %" PRIu32,
466 &data, binder.get(), code);
Steven Morelandf5174272021-05-25 00:39:28 +0000467 return BAD_TYPE;
468 }
469
Steven Moreland5623d1a2021-09-10 15:45:34 -0700470 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000471 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
472
Steven Moreland5ae62562021-06-10 03:21:42 +0000473 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000474}
475
Steven Moreland5ae62562021-06-10 03:21:42 +0000476status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700477 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000478 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000479 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
480 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
481
Steven Moreland5553ac42020-11-11 02:14:45 +0000482 uint64_t asyncNumber = 0;
483
Steven Moreland5623d1a2021-09-10 15:45:34 -0700484 if (address != 0) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000485 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000486 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
487 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700488 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
489 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000490
491 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000492 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000493 if (!nodeProgressAsyncNumber(&it->second)) {
494 _l.unlock();
495 (void)session->shutdownAndWait(false);
496 return DEAD_OBJECT;
497 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000498 }
499 }
500
Steven Moreland77c30112021-06-02 20:45:46 +0000501 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
502 sizeof(RpcWireTransaction) <
503 data.dataSize(),
504 "Too much data %zu", data.dataSize());
505
506 RpcWireHeader command{
507 .command = RPC_COMMAND_TRANSACT,
508 .bodySize = static_cast<uint32_t>(sizeof(RpcWireTransaction) + data.dataSize()),
509 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700510
Steven Moreland5553ac42020-11-11 02:14:45 +0000511 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700512 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000513 .code = code,
514 .flags = flags,
515 .asyncNumber = asyncNumber,
516 };
Steven Moreland77c30112021-06-02 20:45:46 +0000517 CommandData transactionData(sizeof(RpcWireHeader) + sizeof(RpcWireTransaction) +
518 data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000519 if (!transactionData.valid()) {
520 return NO_MEMORY;
521 }
522
Steven Moreland77c30112021-06-02 20:45:46 +0000523 memcpy(transactionData.data() + 0, &command, sizeof(RpcWireHeader));
524 memcpy(transactionData.data() + sizeof(RpcWireHeader), &transaction,
525 sizeof(RpcWireTransaction));
526 memcpy(transactionData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireTransaction), data.data(),
527 data.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000528
Steven Moreland43921d52021-09-27 17:15:56 -0700529 constexpr size_t kWaitMaxUs = 1000000;
530 constexpr size_t kWaitLogUs = 10000;
531 size_t waitUs = 0;
532
533 // Oneway calls have no sync point, so if many are sent before, whether this
534 // is a twoway or oneway transaction, they may have filled up the socket.
535 // So, make sure we drain them before polling.
536 std::function<status_t()> drainRefs = [&] {
537 if (waitUs > kWaitLogUs) {
538 ALOGE("Cannot send command, trying to process pending refcounts. Waiting %zuus. Too "
539 "many oneway calls?",
540 waitUs);
541 }
542
543 if (waitUs > 0) {
544 usleep(waitUs);
545 waitUs = std::min(kWaitMaxUs, waitUs * 2);
546 } else {
547 waitUs = 1;
548 }
549
550 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
551 };
552
Steven Moreland5ae62562021-06-10 03:21:42 +0000553 if (status_t status = rpcSend(connection, session, "transaction", transactionData.data(),
Steven Moreland43921d52021-09-27 17:15:56 -0700554 transactionData.size(), drainRefs);
555 status != OK) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000556 // TODO(b/167966510): need to undo onBinderLeaving - we know the
557 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000558 return status;
Steven Moreland43921d52021-09-27 17:15:56 -0700559 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000560
561 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700562 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
563 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000564
565 // Do not wait on result.
Steven Moreland43921d52021-09-27 17:15:56 -0700566 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000567 }
568
569 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
570
Steven Moreland5ae62562021-06-10 03:21:42 +0000571 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000572}
573
Steven Moreland438cce82021-04-02 18:04:08 +0000574static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
575 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000576 (void)p;
577 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
578 (void)dataSize;
579 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Yifan Hong239a2ca2021-06-24 16:05:16 -0700580 LOG_ALWAYS_FATAL_IF(objectsCount != 0, "%zu objects remaining", objectsCount);
Steven Moreland5553ac42020-11-11 02:14:45 +0000581}
582
Steven Moreland5ae62562021-06-10 03:21:42 +0000583status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
584 const sp<RpcSession>& session, Parcel* reply) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000585 RpcWireHeader command;
586 while (true) {
Steven Morelandae58f432021-08-05 17:53:16 -0700587 if (status_t status = rpcRec(connection, session, "command header (for reply)", &command,
588 sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000589 status != OK)
590 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000591
592 if (command.command == RPC_COMMAND_REPLY) break;
593
Steven Moreland19fc9f72021-06-10 03:57:30 +0000594 if (status_t status = processCommand(connection, session, command, CommandType::ANY);
Steven Moreland52eee942021-06-03 00:59:28 +0000595 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000596 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000597 }
598
Steven Morelanddbe71832021-05-12 23:31:00 +0000599 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000600 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000601
Steven Moreland5ae62562021-06-10 03:21:42 +0000602 if (status_t status = rpcRec(connection, session, "reply body", data.data(), command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000603 status != OK)
604 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000605
606 if (command.bodySize < sizeof(RpcWireReply)) {
607 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
608 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000609 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000610 return BAD_VALUE;
611 }
Steven Morelande8393342021-05-05 23:27:53 +0000612 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000613 if (rpcReply->status != OK) return rpcReply->status;
614
Steven Morelande8393342021-05-05 23:27:53 +0000615 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000616 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000617 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000618
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000619 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000620
621 return OK;
622}
623
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000624status_t RpcState::sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection,
625 const sp<RpcSession>& session, uint64_t addr,
626 size_t target) {
627 RpcDecStrong body = {
628 .address = RpcWireAddress::fromRaw(addr),
629 };
630
Steven Moreland5553ac42020-11-11 02:14:45 +0000631 {
632 std::lock_guard<std::mutex> _l(mNodeMutex);
633 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
634 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700635 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
636 "Sending dec strong on unknown address %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000637
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000638 LOG_ALWAYS_FATAL_IF(it->second.timesRecd < target, "Can't dec count of %zu to %zu.",
639 it->second.timesRecd, target);
640
641 // typically this happens when multiple threads send dec refs at the
642 // same time - the transactions will get combined automatically
643 if (it->second.timesRecd == target) return OK;
644
645 body.amount = it->second.timesRecd - target;
646 it->second.timesRecd = target;
647
Steven Moreland31bde7a2021-06-04 00:57:36 +0000648 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
649 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000650 }
651
652 RpcWireHeader cmd = {
653 .command = RPC_COMMAND_DEC_STRONG,
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000654 .bodySize = sizeof(RpcDecStrong),
Steven Moreland5553ac42020-11-11 02:14:45 +0000655 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000656 if (status_t status = rpcSend(connection, session, "dec ref header", &cmd, sizeof(cmd));
657 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000658 return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000659
660 return rpcSend(connection, session, "dec ref body", &body, sizeof(body));
Steven Moreland5553ac42020-11-11 02:14:45 +0000661}
662
Steven Moreland5ae62562021-06-10 03:21:42 +0000663status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
664 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700665 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000666
667 RpcWireHeader command;
Steven Morelandae58f432021-08-05 17:53:16 -0700668 if (status_t status = rpcRec(connection, session, "command header (for server)", &command,
669 sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000670 status != OK)
671 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000672
Steven Moreland19fc9f72021-06-10 03:57:30 +0000673 return processCommand(connection, session, command, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000674}
675
Steven Moreland5ae62562021-06-10 03:21:42 +0000676status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
677 const sp<RpcSession>& session, CommandType type) {
Steven Moreland52eee942021-06-03 00:59:28 +0000678 uint8_t buf;
Yifan Hong218c4072021-08-04 14:59:10 -0700679 while (connection->rpcTransport->peek(&buf, sizeof(buf)).value_or(0) > 0) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000680 status_t status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000681 if (status != OK) return status;
682 }
683 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000684}
685
Steven Moreland19fc9f72021-06-10 03:57:30 +0000686status_t RpcState::processCommand(const sp<RpcSession::RpcConnection>& connection,
687 const sp<RpcSession>& session, const RpcWireHeader& command,
688 CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000689 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
690 IPCThreadState::SpGuard spGuard{
691 .address = __builtin_frame_address(0),
692 .context = "processing binder RPC command",
693 };
694 const IPCThreadState::SpGuard* origGuard;
695 if (kernelBinderState != nullptr) {
696 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
697 }
698 ScopeGuard guardUnguard = [&]() {
699 if (kernelBinderState != nullptr) {
700 kernelBinderState->restoreGetCallingSpGuard(origGuard);
701 }
702 };
703
Steven Moreland5553ac42020-11-11 02:14:45 +0000704 switch (command.command) {
705 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000706 if (type != CommandType::ANY) return BAD_TYPE;
Steven Moreland5ae62562021-06-10 03:21:42 +0000707 return processTransact(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000708 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000709 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000710 }
711
712 // We should always know the version of the opposing side, and since the
713 // RPC-binder-level wire protocol is not self synchronizing, we have no way
714 // to understand where the current command ends and the next one begins. We
715 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000716 // to kill us, so ending the session for misbehaving client.
717 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000718 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000719 return DEAD_OBJECT;
720}
Steven Moreland5ae62562021-06-10 03:21:42 +0000721status_t RpcState::processTransact(const sp<RpcSession::RpcConnection>& connection,
722 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000723 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
724
Steven Morelanddbe71832021-05-12 23:31:00 +0000725 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000726 if (!transactionData.valid()) {
727 return NO_MEMORY;
728 }
Steven Moreland5ae62562021-06-10 03:21:42 +0000729 if (status_t status = rpcRec(connection, session, "transaction body", transactionData.data(),
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000730 transactionData.size());
731 status != OK)
732 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000733
Steven Moreland5ae62562021-06-10 03:21:42 +0000734 return processTransactInternal(connection, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000735}
736
Steven Moreland438cce82021-04-02 18:04:08 +0000737static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
738 const binder_size_t* objects, size_t objectsCount) {
739 (void)p;
740 (void)data;
741 (void)dataSize;
742 (void)objects;
743 (void)objectsCount;
744}
745
Steven Moreland5ae62562021-06-10 03:21:42 +0000746status_t RpcState::processTransactInternal(const sp<RpcSession::RpcConnection>& connection,
747 const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000748 CommandData transactionData) {
749 // for 'recursive' calls to this, we have already read and processed the
750 // binder from the transaction data and taken reference counts into account,
751 // so it is cached here.
Steven Moreland3903bf02021-09-27 16:05:24 -0700752 sp<IBinder> target;
Steven Morelandada72bd2021-06-09 23:29:13 +0000753processTransactInternalTailCall:
754
Steven Moreland5553ac42020-11-11 02:14:45 +0000755 if (transactionData.size() < sizeof(RpcWireTransaction)) {
756 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
757 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000758 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000759 return BAD_VALUE;
760 }
761 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
762
Steven Moreland5623d1a2021-09-10 15:45:34 -0700763 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000764 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000765
766 status_t replyStatus = OK;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700767 if (addr != 0) {
Steven Moreland3903bf02021-09-27 16:05:24 -0700768 if (!target) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000769 replyStatus = onBinderEntering(session, addr, &target);
Steven Morelandf5174272021-05-25 00:39:28 +0000770 }
771
Steven Moreland7227c8a2021-06-02 00:24:32 +0000772 if (replyStatus != OK) {
773 // do nothing
774 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000775 // This can happen if the binder is remote in this process, and
776 // another thread has called the last decStrong on this binder.
777 // However, for local binders, it indicates a misbehaving client
778 // (any binder which is being transacted on should be holding a
779 // strong ref count), so in either case, terminating the
780 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700781 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
782 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000783 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000784 replyStatus = BAD_VALUE;
785 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700786 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
787 ". Terminating!",
788 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000789 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000790 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000791 } else if (oneway) {
Steven Morelandd45be622021-06-04 02:19:37 +0000792 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000793 auto it = mNodeForAddress.find(addr);
794 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700795 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000796 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000797 } else if (transaction->asyncNumber != it->second.asyncNumber) {
798 // we need to process some other asynchronous transaction
799 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000800 it->second.asyncTodo.push(BinderNode::AsyncTodo{
801 .ref = target,
802 .data = std::move(transactionData),
803 .asyncNumber = transaction->asyncNumber,
804 });
Steven Morelandd45be622021-06-04 02:19:37 +0000805
806 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700807 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
808 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000809
810 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
811 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
812 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
813
814 if (numPending >= kArbitraryOnewayCallWarnLevel) {
815 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
816 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
817 _l.unlock();
818 (void)session->shutdownAndWait(false);
819 return FAILED_TRANSACTION;
820 }
821
822 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
823 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
824 target.get(), numPending);
825 }
826 }
Steven Morelandf5174272021-05-25 00:39:28 +0000827 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000828 }
829 }
830 }
831
Steven Moreland5553ac42020-11-11 02:14:45 +0000832 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000833 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000834
835 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000836 Parcel data;
837 // transaction->data is owned by this function. Parcel borrows this data and
838 // only holds onto it for the duration of this function call. Parcel will be
839 // deleted before the 'transactionData' object.
840 data.ipcSetDataReference(transaction->data,
841 transactionData.size() - offsetof(RpcWireTransaction, data),
842 nullptr /*object*/, 0 /*objectCount*/,
843 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000844 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000845
Steven Moreland5553ac42020-11-11 02:14:45 +0000846 if (target) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000847 bool origAllowNested = connection->allowNested;
848 connection->allowNested = !oneway;
849
Steven Moreland5553ac42020-11-11 02:14:45 +0000850 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000851
852 connection->allowNested = origAllowNested;
Steven Moreland5553ac42020-11-11 02:14:45 +0000853 } else {
854 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000855
Steven Moreland103424e2021-06-02 18:16:19 +0000856 switch (transaction->code) {
857 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
Yifan Hong10423062021-10-08 16:26:32 -0700858 replyStatus = reply.writeInt32(session->getMaxIncomingThreads());
Steven Moreland103424e2021-06-02 18:16:19 +0000859 break;
860 }
861 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
862 // for client connections, this should always report the value
Steven Moreland01a6bad2021-06-11 00:59:20 +0000863 // originally returned from the server, so this is asserting
864 // that it exists
Steven Moreland826367f2021-09-10 14:05:31 -0700865 replyStatus = reply.writeByteVector(session->mId);
Steven Moreland103424e2021-06-02 18:16:19 +0000866 break;
867 }
868 default: {
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000869 sp<RpcServer> server = session->server();
Steven Moreland103424e2021-06-02 18:16:19 +0000870 if (server) {
871 switch (transaction->code) {
872 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
Steven Moreland51c44a92021-10-14 16:50:35 -0700873 sp<IBinder> root = session->mSessionSpecificRootObject
874 ?: server->getRootObject();
875 replyStatus = reply.writeStrongBinder(root);
Steven Moreland103424e2021-06-02 18:16:19 +0000876 break;
877 }
878 default: {
879 replyStatus = UNKNOWN_TRANSACTION;
880 }
881 }
882 } else {
883 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000884 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000885 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000886 }
887 }
888 }
889
Steven Morelandc7d40132021-06-10 03:42:11 +0000890 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000891 if (replyStatus != OK) {
892 ALOGW("Oneway call failed with error: %d", replyStatus);
893 }
894
Steven Moreland5623d1a2021-09-10 15:45:34 -0700895 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
896 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000897
898 // Check to see if there is another asynchronous transaction to process.
899 // This behavior differs from binder behavior, since in the binder
900 // driver, asynchronous transactions will be processed after existing
901 // pending binder transactions on the queue. The downside of this is
902 // that asynchronous transactions can be drowned out by synchronous
903 // transactions. However, we have no easy way to queue these
904 // transactions after the synchronous transactions we may want to read
905 // from the wire. So, in socket binder here, we have the opposite
906 // downside: asynchronous transactions may drown out synchronous
907 // transactions.
908 {
909 std::unique_lock<std::mutex> _l(mNodeMutex);
910 auto it = mNodeForAddress.find(addr);
911 // last refcount dropped after this transaction happened
912 if (it == mNodeForAddress.end()) return OK;
913
Steven Morelandc9d7b532021-06-04 20:57:41 +0000914 if (!nodeProgressAsyncNumber(&it->second)) {
915 _l.unlock();
916 (void)session->shutdownAndWait(false);
917 return DEAD_OBJECT;
918 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000919
920 if (it->second.asyncTodo.size() == 0) return OK;
921 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700922 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
923 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000924
925 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000926 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000927 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000928 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
929
Steven Morelandada72bd2021-06-09 23:29:13 +0000930 // reset up arguments
931 transactionData = std::move(todo.data);
Steven Moreland3903bf02021-09-27 16:05:24 -0700932 LOG_ALWAYS_FATAL_IF(target != todo.ref,
933 "async list should be associated with a binder");
Steven Morelandf5174272021-05-25 00:39:28 +0000934
Steven Moreland5553ac42020-11-11 02:14:45 +0000935 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000936 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000937 }
938 }
Steven Morelandd8083312021-09-22 13:37:10 -0700939
940 // done processing all the async commands on this binder that we can, so
941 // write decstrongs on the binder
942 if (addr != 0 && replyStatus == OK) {
943 return flushExcessBinderRefs(session, addr, target);
944 }
945
Steven Moreland5553ac42020-11-11 02:14:45 +0000946 return OK;
947 }
948
Steven Moreland6709cf42021-09-30 15:21:54 -0700949 // Binder refs are flushed for oneway calls only after all calls which are
950 // built up are executed. Otherwise, they fill up the binder buffer.
951 if (addr != 0 && replyStatus == OK) {
952 replyStatus = flushExcessBinderRefs(session, addr, target);
953 }
954
Steven Moreland77c30112021-06-02 20:45:46 +0000955 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
956 sizeof(RpcWireReply) <
957 reply.dataSize(),
958 "Too much data for reply %zu", reply.dataSize());
959
960 RpcWireHeader cmdReply{
961 .command = RPC_COMMAND_REPLY,
962 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
963 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000964 RpcWireReply rpcReply{
965 .status = replyStatus,
966 };
967
Steven Moreland77c30112021-06-02 20:45:46 +0000968 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000969 if (!replyData.valid()) {
970 return NO_MEMORY;
971 }
Steven Moreland77c30112021-06-02 20:45:46 +0000972 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
973 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
974 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
975 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000976
Steven Moreland5ae62562021-06-10 03:21:42 +0000977 return rpcSend(connection, session, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000978}
979
Steven Moreland5ae62562021-06-10 03:21:42 +0000980status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
981 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000982 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
983
Steven Morelanddbe71832021-05-12 23:31:00 +0000984 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000985 if (!commandData.valid()) {
986 return NO_MEMORY;
987 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000988 if (status_t status =
Steven Moreland5ae62562021-06-10 03:21:42 +0000989 rpcRec(connection, session, "dec ref body", commandData.data(), commandData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000990 status != OK)
991 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000992
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000993 if (command.bodySize != sizeof(RpcDecStrong)) {
994 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcDecStrong. Terminating!",
995 sizeof(RpcDecStrong), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000996 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000997 return BAD_VALUE;
998 }
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000999 RpcDecStrong* body = reinterpret_cast<RpcDecStrong*>(commandData.data());
Steven Moreland5553ac42020-11-11 02:14:45 +00001000
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001001 uint64_t addr = RpcWireAddress::toRaw(body->address);
Steven Moreland5553ac42020-11-11 02:14:45 +00001002 std::unique_lock<std::mutex> _l(mNodeMutex);
1003 auto it = mNodeForAddress.find(addr);
1004 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001005 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001006 return OK;
1007 }
1008
1009 sp<IBinder> target = it->second.binder.promote();
1010 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -07001011 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
1012 ". Terminating!",
1013 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +00001014 _l.unlock();
1015 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +00001016 return BAD_VALUE;
1017 }
1018
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001019 if (it->second.timesSent < body->amount) {
1020 ALOGE("Record of sending binder %zu times, but requested decStrong for %" PRIu64 " of %u",
1021 it->second.timesSent, addr, body->amount);
Steven Moreland5553ac42020-11-11 02:14:45 +00001022 return OK;
1023 }
1024
Steven Moreland5623d1a2021-09-10 15:45:34 -07001025 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
1026 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +00001027
Steven Morelandfd1e8a02021-07-21 23:30:29 +00001028 LOG_RPC_DETAIL("Processing dec strong of %" PRIu64 " by %u from %zu", addr, body->amount,
1029 it->second.timesSent);
1030
1031 it->second.timesSent -= body->amount;
Steven Moreland31bde7a2021-06-04 00:57:36 +00001032 sp<IBinder> tempHold = tryEraseNode(it);
1033 _l.unlock();
1034 tempHold = nullptr; // destructor may make binder calls on this session
1035
1036 return OK;
1037}
1038
Steven Moreland5623d1a2021-09-10 15:45:34 -07001039sp<IBinder> RpcState::tryEraseNode(std::map<uint64_t, BinderNode>::iterator& it) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001040 sp<IBinder> ref;
1041
Steven Moreland5553ac42020-11-11 02:14:45 +00001042 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +00001043 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +00001044
1045 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +00001046 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
1047 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +00001048 mNodeForAddress.erase(it);
1049 }
1050 }
1051
Steven Moreland31bde7a2021-06-04 00:57:36 +00001052 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +00001053}
1054
Steven Morelandc9d7b532021-06-04 20:57:41 +00001055bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +00001056 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
1057 // a single binder
1058 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
1059 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +00001060 return false;
1061 }
1062 node->asyncNumber++;
1063 return true;
1064}
1065
Steven Moreland5553ac42020-11-11 02:14:45 +00001066} // namespace android