blob: 1838e81dd6d7566550eaa5e0b5c730394d2d9a4c [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 Moreland5553ac42020-11-11 02:14:45 +0000155 std::unique_lock<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++;
163
164 _l.unlock();
165
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000166 // if this is a local binder, then we want to get rid of all refcounts
167 // (tell the other process it can drop the binder when it wants to - we
168 // have a local sp<>, so we will drop it when we want to as well). if
169 // this is a remote binder, then we need to hold onto one refcount until
170 // it is dropped in BpBinder::onLastStrongRef
171 size_t targetRecd = (*out)->localBinder() ? 0 : 1;
172
Steven Moreland5553ac42020-11-11 02:14:45 +0000173 // We have timesRecd RPC refcounts, but we only need to hold on to one
174 // when we keep the object. All additional dec strongs are sent
175 // immediately, we wait to send the last one in BpBinder::onLastDecStrong.
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000176 return session->sendDecStrongToTarget(address, targetRecd);
Steven Moreland5553ac42020-11-11 02:14:45 +0000177 }
178
Steven Moreland91538242021-06-10 23:35:35 +0000179 // we don't know about this binder, so the other side of the connection
180 // should have created it.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700181 if ((addr.options & RPC_WIRE_ADDRESS_OPTION_FOR_SERVER) == !!session->server()) {
182 ALOGE("Server received unrecognized address which we should own the creation of %" PRIu64,
183 address);
Steven Moreland91538242021-06-10 23:35:35 +0000184 return BAD_VALUE;
185 }
186
Steven Moreland5553ac42020-11-11 02:14:45 +0000187 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
188 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
189
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000190 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000191 // device global binders in the RPC world).
Steven Moreland99157622021-09-13 16:27:34 -0700192 it->second.binder = *out = BpBinder::PrivateAccessor::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000193 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000194 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000195}
196
197size_t RpcState::countBinders() {
198 std::lock_guard<std::mutex> _l(mNodeMutex);
199 return mNodeForAddress.size();
200}
201
202void RpcState::dump() {
203 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000204 dumpLocked();
205}
206
Steven Morelandc9d7b532021-06-04 20:57:41 +0000207void RpcState::clear() {
Steven Moreland583a14a2021-06-04 02:04:58 +0000208 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000209
210 if (mTerminated) {
211 LOG_ALWAYS_FATAL_IF(!mNodeForAddress.empty(),
212 "New state should be impossible after terminating!");
213 return;
214 }
215
216 if (SHOULD_LOG_RPC_DETAIL) {
217 ALOGE("RpcState::clear()");
218 dumpLocked();
219 }
220
221 // if the destructor of a binder object makes another RPC call, then calling
222 // decStrong could deadlock. So, we must hold onto these binders until
223 // mNodeMutex is no longer taken.
224 std::vector<sp<IBinder>> tempHoldBinder;
225
226 mTerminated = true;
227 for (auto& [address, node] : mNodeForAddress) {
228 sp<IBinder> binder = node.binder.promote();
229 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
230
231 if (node.sentRef != nullptr) {
232 tempHoldBinder.push_back(node.sentRef);
233 }
234 }
235
236 mNodeForAddress.clear();
237
238 _l.unlock();
239 tempHoldBinder.clear(); // explicit
Steven Moreland583a14a2021-06-04 02:04:58 +0000240}
241
242void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000243 ALOGE("DUMP OF RpcState %p", this);
244 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
245 for (const auto& [address, node] : mNodeForAddress) {
246 sp<IBinder> binder = node.binder.promote();
247
248 const char* desc;
249 if (binder) {
250 if (binder->remoteBinder()) {
251 if (binder->remoteBinder()->isRpcBinder()) {
252 desc = "(rpc binder proxy)";
253 } else {
254 desc = "(binder proxy)";
255 }
256 } else {
257 desc = "(local binder)";
258 }
259 } else {
260 desc = "(null)";
261 }
262
Steven Moreland5623d1a2021-09-10 15:45:34 -0700263 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a: %" PRIu64 " type: %s",
264 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address, desc);
Steven Moreland5553ac42020-11-11 02:14:45 +0000265 }
266 ALOGE("END DUMP OF RpcState");
267}
268
Steven Moreland5553ac42020-11-11 02:14:45 +0000269
Steven Morelanddbe71832021-05-12 23:31:00 +0000270RpcState::CommandData::CommandData(size_t size) : mSize(size) {
271 // The maximum size for regular binder is 1MB for all concurrent
272 // transactions. A very small proportion of transactions are even
273 // larger than a page, but we need to avoid allocating too much
274 // data on behalf of an arbitrary client, or we could risk being in
275 // a position where a single additional allocation could run out of
276 // memory.
277 //
278 // Note, this limit may not reflect the total amount of data allocated for a
279 // transaction (in some cases, additional fixed size amounts are added),
280 // though for rough consistency, we should avoid cases where this data type
281 // is used for multiple dynamic allocations for a single transaction.
282 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
283 if (size == 0) return;
284 if (size > kMaxTransactionAllocation) {
285 ALOGW("Transaction requested too much data allocation %zu", size);
286 return;
287 }
288 mData.reset(new (std::nothrow) uint8_t[size]);
289}
290
Steven Moreland5ae62562021-06-10 03:21:42 +0000291status_t RpcState::rpcSend(const sp<RpcSession::RpcConnection>& connection,
292 const sp<RpcSession>& session, const char* what, const void* data,
293 size_t size) {
Yifan Hong702115c2021-06-24 15:39:18 -0700294 LOG_RPC_DETAIL("Sending %s on RpcTransport %p: %s", what, connection->rpcTransport.get(),
Steven Moreland62129012021-07-29 12:14:44 -0700295 android::base::HexString(data, size).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000296
297 if (size > std::numeric_limits<ssize_t>::max()) {
298 ALOGE("Cannot send %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000299 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000300 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000301 }
302
Yifan Hong702115c2021-06-24 15:39:18 -0700303 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700304 connection->rpcTransport->interruptableWriteFully(session->mShutdownTrigger.get(),
305 data, size);
Steven Moreland798e0d12021-07-14 23:19:25 +0000306 status != OK) {
Yifan Hong702115c2021-06-24 15:39:18 -0700307 LOG_RPC_DETAIL("Failed to write %s (%zu bytes) on RpcTransport %p, error: %s", what, size,
308 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000309 (void)session->shutdownAndWait(false);
Steven Moreland798e0d12021-07-14 23:19:25 +0000310 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000311 }
312
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000313 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000314}
315
Steven Moreland5ae62562021-06-10 03:21:42 +0000316status_t RpcState::rpcRec(const sp<RpcSession::RpcConnection>& connection,
317 const sp<RpcSession>& session, const char* what, void* data,
318 size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000319 if (size > std::numeric_limits<ssize_t>::max()) {
320 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000321 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000322 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000323 }
324
Steven Moreland5ae62562021-06-10 03:21:42 +0000325 if (status_t status =
Yifan Hong8c950422021-08-05 17:13:55 -0700326 connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
327 data, size);
Steven Morelandee3f4662021-05-22 01:07:33 +0000328 status != OK) {
Yifan Hong702115c2021-06-24 15:39:18 -0700329 LOG_RPC_DETAIL("Failed to read %s (%zu bytes) on RpcTransport %p, error: %s", what, size,
330 connection->rpcTransport.get(), statusToString(status).c_str());
Steven Morelandae58f432021-08-05 17:53:16 -0700331 (void)session->shutdownAndWait(false);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000332 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000333 }
334
Yifan Hong702115c2021-06-24 15:39:18 -0700335 LOG_RPC_DETAIL("Received %s on RpcTransport %p: %s", what, connection->rpcTransport.get(),
Steven Moreland62129012021-07-29 12:14:44 -0700336 android::base::HexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000337 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000338}
339
Steven Morelandbf57bce2021-07-26 15:26:12 -0700340status_t RpcState::readNewSessionResponse(const sp<RpcSession::RpcConnection>& connection,
341 const sp<RpcSession>& session, uint32_t* version) {
342 RpcNewSessionResponse response;
343 if (status_t status =
344 rpcRec(connection, session, "new session response", &response, sizeof(response));
345 status != OK) {
346 return status;
347 }
348 *version = response.version;
349 return OK;
350}
351
Steven Moreland5ae62562021-06-10 03:21:42 +0000352status_t RpcState::sendConnectionInit(const sp<RpcSession::RpcConnection>& connection,
353 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000354 RpcOutgoingConnectionInit init{
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000355 .msg = RPC_CONNECTION_INIT_OKAY,
356 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000357 return rpcSend(connection, session, "connection init", &init, sizeof(init));
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000358}
359
Steven Moreland5ae62562021-06-10 03:21:42 +0000360status_t RpcState::readConnectionInit(const sp<RpcSession::RpcConnection>& connection,
361 const sp<RpcSession>& session) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000362 RpcOutgoingConnectionInit init;
Steven Moreland5ae62562021-06-10 03:21:42 +0000363 if (status_t status = rpcRec(connection, session, "connection init", &init, sizeof(init));
364 status != OK)
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000365 return status;
366
367 static_assert(sizeof(init.msg) == sizeof(RPC_CONNECTION_INIT_OKAY));
368 if (0 != strncmp(init.msg, RPC_CONNECTION_INIT_OKAY, sizeof(init.msg))) {
369 ALOGE("Connection init message unrecognized %.*s", static_cast<int>(sizeof(init.msg)),
370 init.msg);
371 return BAD_VALUE;
372 }
373 return OK;
374}
375
Steven Moreland5ae62562021-06-10 03:21:42 +0000376sp<IBinder> RpcState::getRootObject(const sp<RpcSession::RpcConnection>& connection,
377 const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000378 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000379 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000380 Parcel reply;
381
Steven Moreland5623d1a2021-09-10 15:45:34 -0700382 status_t status =
383 transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_ROOT, data, session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000384 if (status != OK) {
385 ALOGE("Error getting root object: %s", statusToString(status).c_str());
386 return nullptr;
387 }
388
389 return reply.readStrongBinder();
390}
391
Steven Moreland5ae62562021-06-10 03:21:42 +0000392status_t RpcState::getMaxThreads(const sp<RpcSession::RpcConnection>& connection,
393 const sp<RpcSession>& session, size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000394 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000395 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000396 Parcel reply;
397
Steven Moreland5623d1a2021-09-10 15:45:34 -0700398 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
399 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000400 if (status != OK) {
401 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
402 return status;
403 }
404
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000405 int32_t maxThreads;
406 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000407 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000408 if (maxThreads <= 0) {
409 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000410 return BAD_VALUE;
411 }
412
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000413 *maxThreadsOut = maxThreads;
414 return OK;
415}
416
Steven Moreland5ae62562021-06-10 03:21:42 +0000417status_t RpcState::getSessionId(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland826367f2021-09-10 14:05:31 -0700418 const sp<RpcSession>& session, std::vector<uint8_t>* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000419 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000420 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000421 Parcel reply;
422
Steven Moreland5623d1a2021-09-10 15:45:34 -0700423 status_t status = transactAddress(connection, 0, RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
424 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000425 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000426 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000427 return status;
428 }
429
Steven Moreland826367f2021-09-10 14:05:31 -0700430 return reply.readByteVector(sessionIdOut);
Steven Morelandf137de92021-04-24 01:54:26 +0000431}
432
Steven Moreland5ae62562021-06-10 03:21:42 +0000433status_t RpcState::transact(const sp<RpcSession::RpcConnection>& connection,
434 const sp<IBinder>& binder, uint32_t code, const Parcel& data,
435 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000436 if (!data.isForRpc()) {
437 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
438 return BAD_TYPE;
439 }
440
441 if (data.objectsCount() != 0) {
442 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
443 return BAD_TYPE;
444 }
445
Steven Moreland5623d1a2021-09-10 15:45:34 -0700446 uint64_t address;
Steven Morelandf5174272021-05-25 00:39:28 +0000447 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
448
Steven Moreland5ae62562021-06-10 03:21:42 +0000449 return transactAddress(connection, address, code, data, session, reply, flags);
Steven Morelandf5174272021-05-25 00:39:28 +0000450}
451
Steven Moreland5ae62562021-06-10 03:21:42 +0000452status_t RpcState::transactAddress(const sp<RpcSession::RpcConnection>& connection,
Steven Moreland5623d1a2021-09-10 15:45:34 -0700453 uint64_t address, uint32_t code, const Parcel& data,
Steven Moreland5ae62562021-06-10 03:21:42 +0000454 const sp<RpcSession>& session, Parcel* reply, uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000455 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
456 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
457
Steven Moreland5553ac42020-11-11 02:14:45 +0000458 uint64_t asyncNumber = 0;
459
Steven Moreland5623d1a2021-09-10 15:45:34 -0700460 if (address != 0) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000461 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000462 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
463 auto it = mNodeForAddress.find(address);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700464 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
465 "Sending transact on unknown address %" PRIu64, address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000466
467 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000468 asyncNumber = it->second.asyncNumber;
Steven Morelandc9d7b532021-06-04 20:57:41 +0000469 if (!nodeProgressAsyncNumber(&it->second)) {
470 _l.unlock();
471 (void)session->shutdownAndWait(false);
472 return DEAD_OBJECT;
473 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000474 }
475 }
476
Steven Moreland77c30112021-06-02 20:45:46 +0000477 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
478 sizeof(RpcWireTransaction) <
479 data.dataSize(),
480 "Too much data %zu", data.dataSize());
481
482 RpcWireHeader command{
483 .command = RPC_COMMAND_TRANSACT,
484 .bodySize = static_cast<uint32_t>(sizeof(RpcWireTransaction) + data.dataSize()),
485 };
Steven Moreland5623d1a2021-09-10 15:45:34 -0700486
Steven Moreland5553ac42020-11-11 02:14:45 +0000487 RpcWireTransaction transaction{
Steven Moreland5623d1a2021-09-10 15:45:34 -0700488 .address = RpcWireAddress::fromRaw(address),
Steven Moreland5553ac42020-11-11 02:14:45 +0000489 .code = code,
490 .flags = flags,
491 .asyncNumber = asyncNumber,
492 };
Steven Moreland77c30112021-06-02 20:45:46 +0000493 CommandData transactionData(sizeof(RpcWireHeader) + sizeof(RpcWireTransaction) +
494 data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000495 if (!transactionData.valid()) {
496 return NO_MEMORY;
497 }
498
Steven Moreland77c30112021-06-02 20:45:46 +0000499 memcpy(transactionData.data() + 0, &command, sizeof(RpcWireHeader));
500 memcpy(transactionData.data() + sizeof(RpcWireHeader), &transaction,
501 sizeof(RpcWireTransaction));
502 memcpy(transactionData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireTransaction), data.data(),
503 data.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000504
Steven Moreland5ae62562021-06-10 03:21:42 +0000505 if (status_t status = rpcSend(connection, session, "transaction", transactionData.data(),
506 transactionData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000507 status != OK)
Steven Morelanda5036f02021-06-08 02:26:57 +0000508 // TODO(b/167966510): need to undo onBinderLeaving - we know the
509 // refcount isn't successfully transferred.
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000510 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000511
512 if (flags & IBinder::FLAG_ONEWAY) {
Yifan Hong702115c2021-06-24 15:39:18 -0700513 LOG_RPC_DETAIL("Oneway command, so no longer waiting on RpcTransport %p",
514 connection->rpcTransport.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000515
516 // Do not wait on result.
517 // However, too many oneway calls may cause refcounts to build up and fill up the socket,
518 // so process those.
Steven Moreland5ae62562021-06-10 03:21:42 +0000519 return drainCommands(connection, session, CommandType::CONTROL_ONLY);
Steven Moreland5553ac42020-11-11 02:14:45 +0000520 }
521
522 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
523
Steven Moreland5ae62562021-06-10 03:21:42 +0000524 return waitForReply(connection, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000525}
526
Steven Moreland438cce82021-04-02 18:04:08 +0000527static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
528 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000529 (void)p;
530 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
531 (void)dataSize;
532 LOG_ALWAYS_FATAL_IF(objects != nullptr);
Yifan Hong239a2ca2021-06-24 16:05:16 -0700533 LOG_ALWAYS_FATAL_IF(objectsCount != 0, "%zu objects remaining", objectsCount);
Steven Moreland5553ac42020-11-11 02:14:45 +0000534}
535
Steven Moreland5ae62562021-06-10 03:21:42 +0000536status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
537 const sp<RpcSession>& session, Parcel* reply) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000538 RpcWireHeader command;
539 while (true) {
Steven Morelandae58f432021-08-05 17:53:16 -0700540 if (status_t status = rpcRec(connection, session, "command header (for reply)", &command,
541 sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000542 status != OK)
543 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000544
545 if (command.command == RPC_COMMAND_REPLY) break;
546
Steven Moreland19fc9f72021-06-10 03:57:30 +0000547 if (status_t status = processCommand(connection, session, command, CommandType::ANY);
Steven Moreland52eee942021-06-03 00:59:28 +0000548 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000549 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000550 }
551
Steven Morelanddbe71832021-05-12 23:31:00 +0000552 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000553 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000554
Steven Moreland5ae62562021-06-10 03:21:42 +0000555 if (status_t status = rpcRec(connection, session, "reply body", data.data(), command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000556 status != OK)
557 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000558
559 if (command.bodySize < sizeof(RpcWireReply)) {
560 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
561 sizeof(RpcWireReply), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000562 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000563 return BAD_VALUE;
564 }
Steven Morelande8393342021-05-05 23:27:53 +0000565 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000566 if (rpcReply->status != OK) return rpcReply->status;
567
Steven Morelande8393342021-05-05 23:27:53 +0000568 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000569 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000570 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000571
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000572 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000573
574 return OK;
575}
576
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000577status_t RpcState::sendDecStrongToTarget(const sp<RpcSession::RpcConnection>& connection,
578 const sp<RpcSession>& session, uint64_t addr,
579 size_t target) {
580 RpcDecStrong body = {
581 .address = RpcWireAddress::fromRaw(addr),
582 };
583
Steven Moreland5553ac42020-11-11 02:14:45 +0000584 {
585 std::lock_guard<std::mutex> _l(mNodeMutex);
586 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
587 auto it = mNodeForAddress.find(addr);
Steven Moreland5623d1a2021-09-10 15:45:34 -0700588 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(),
589 "Sending dec strong on unknown address %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000590
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000591 LOG_ALWAYS_FATAL_IF(it->second.timesRecd < target, "Can't dec count of %zu to %zu.",
592 it->second.timesRecd, target);
593
594 // typically this happens when multiple threads send dec refs at the
595 // same time - the transactions will get combined automatically
596 if (it->second.timesRecd == target) return OK;
597
598 body.amount = it->second.timesRecd - target;
599 it->second.timesRecd = target;
600
Steven Moreland31bde7a2021-06-04 00:57:36 +0000601 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
602 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000603 }
604
605 RpcWireHeader cmd = {
606 .command = RPC_COMMAND_DEC_STRONG,
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000607 .bodySize = sizeof(RpcDecStrong),
Steven Moreland5553ac42020-11-11 02:14:45 +0000608 };
Steven Moreland5ae62562021-06-10 03:21:42 +0000609 if (status_t status = rpcSend(connection, session, "dec ref header", &cmd, sizeof(cmd));
610 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000611 return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000612
613 return rpcSend(connection, session, "dec ref body", &body, sizeof(body));
Steven Moreland5553ac42020-11-11 02:14:45 +0000614}
615
Steven Moreland5ae62562021-06-10 03:21:42 +0000616status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& connection,
617 const sp<RpcSession>& session, CommandType type) {
Yifan Hong702115c2021-06-24 15:39:18 -0700618 LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000619
620 RpcWireHeader command;
Steven Morelandae58f432021-08-05 17:53:16 -0700621 if (status_t status = rpcRec(connection, session, "command header (for server)", &command,
622 sizeof(command));
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000623 status != OK)
624 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000625
Steven Moreland19fc9f72021-06-10 03:57:30 +0000626 return processCommand(connection, session, command, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000627}
628
Steven Moreland5ae62562021-06-10 03:21:42 +0000629status_t RpcState::drainCommands(const sp<RpcSession::RpcConnection>& connection,
630 const sp<RpcSession>& session, CommandType type) {
Steven Moreland52eee942021-06-03 00:59:28 +0000631 uint8_t buf;
Yifan Hong218c4072021-08-04 14:59:10 -0700632 while (connection->rpcTransport->peek(&buf, sizeof(buf)).value_or(0) > 0) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000633 status_t status = getAndExecuteCommand(connection, session, type);
Steven Moreland52eee942021-06-03 00:59:28 +0000634 if (status != OK) return status;
635 }
636 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000637}
638
Steven Moreland19fc9f72021-06-10 03:57:30 +0000639status_t RpcState::processCommand(const sp<RpcSession::RpcConnection>& connection,
640 const sp<RpcSession>& session, const RpcWireHeader& command,
641 CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000642 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
643 IPCThreadState::SpGuard spGuard{
644 .address = __builtin_frame_address(0),
645 .context = "processing binder RPC command",
646 };
647 const IPCThreadState::SpGuard* origGuard;
648 if (kernelBinderState != nullptr) {
649 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
650 }
651 ScopeGuard guardUnguard = [&]() {
652 if (kernelBinderState != nullptr) {
653 kernelBinderState->restoreGetCallingSpGuard(origGuard);
654 }
655 };
656
Steven Moreland5553ac42020-11-11 02:14:45 +0000657 switch (command.command) {
658 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000659 if (type != CommandType::ANY) return BAD_TYPE;
Steven Moreland5ae62562021-06-10 03:21:42 +0000660 return processTransact(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000661 case RPC_COMMAND_DEC_STRONG:
Steven Moreland5ae62562021-06-10 03:21:42 +0000662 return processDecStrong(connection, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000663 }
664
665 // We should always know the version of the opposing side, and since the
666 // RPC-binder-level wire protocol is not self synchronizing, we have no way
667 // to understand where the current command ends and the next one begins. We
668 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000669 // to kill us, so ending the session for misbehaving client.
670 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000671 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000672 return DEAD_OBJECT;
673}
Steven Moreland5ae62562021-06-10 03:21:42 +0000674status_t RpcState::processTransact(const sp<RpcSession::RpcConnection>& connection,
675 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000676 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
677
Steven Morelanddbe71832021-05-12 23:31:00 +0000678 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000679 if (!transactionData.valid()) {
680 return NO_MEMORY;
681 }
Steven Moreland5ae62562021-06-10 03:21:42 +0000682 if (status_t status = rpcRec(connection, session, "transaction body", transactionData.data(),
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000683 transactionData.size());
684 status != OK)
685 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000686
Steven Moreland5ae62562021-06-10 03:21:42 +0000687 return processTransactInternal(connection, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000688}
689
Steven Moreland438cce82021-04-02 18:04:08 +0000690static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
691 const binder_size_t* objects, size_t objectsCount) {
692 (void)p;
693 (void)data;
694 (void)dataSize;
695 (void)objects;
696 (void)objectsCount;
697}
698
Steven Moreland5ae62562021-06-10 03:21:42 +0000699status_t RpcState::processTransactInternal(const sp<RpcSession::RpcConnection>& connection,
700 const sp<RpcSession>& session,
Steven Morelandada72bd2021-06-09 23:29:13 +0000701 CommandData transactionData) {
702 // for 'recursive' calls to this, we have already read and processed the
703 // binder from the transaction data and taken reference counts into account,
704 // so it is cached here.
705 sp<IBinder> targetRef;
706processTransactInternalTailCall:
707
Steven Moreland5553ac42020-11-11 02:14:45 +0000708 if (transactionData.size() < sizeof(RpcWireTransaction)) {
709 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
710 sizeof(RpcWireTransaction), transactionData.size());
Steven Morelandc9d7b532021-06-04 20:57:41 +0000711 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000712 return BAD_VALUE;
713 }
714 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
715
Steven Moreland5623d1a2021-09-10 15:45:34 -0700716 uint64_t addr = RpcWireAddress::toRaw(transaction->address);
Steven Morelandc7d40132021-06-10 03:42:11 +0000717 bool oneway = transaction->flags & IBinder::FLAG_ONEWAY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000718
719 status_t replyStatus = OK;
720 sp<IBinder> target;
Steven Moreland5623d1a2021-09-10 15:45:34 -0700721 if (addr != 0) {
Steven Morelandf5174272021-05-25 00:39:28 +0000722 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000723 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000724 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000725 target = targetRef;
726 }
727
Steven Moreland7227c8a2021-06-02 00:24:32 +0000728 if (replyStatus != OK) {
729 // do nothing
730 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000731 // This can happen if the binder is remote in this process, and
732 // another thread has called the last decStrong on this binder.
733 // However, for local binders, it indicates a misbehaving client
734 // (any binder which is being transacted on should be holding a
735 // strong ref count), so in either case, terminating the
736 // session.
Steven Moreland5623d1a2021-09-10 15:45:34 -0700737 ALOGE("While transacting, binder has been deleted at address %" PRIu64 ". Terminating!",
738 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000739 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000740 replyStatus = BAD_VALUE;
741 } else if (target->localBinder() == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700742 ALOGE("Unknown binder address or non-local binder, not address %" PRIu64
743 ". Terminating!",
744 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000745 (void)session->shutdownAndWait(false);
Steven Morelandf5174272021-05-25 00:39:28 +0000746 replyStatus = BAD_VALUE;
Steven Morelandc7d40132021-06-10 03:42:11 +0000747 } else if (oneway) {
Steven Morelandd45be622021-06-04 02:19:37 +0000748 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Morelandf5174272021-05-25 00:39:28 +0000749 auto it = mNodeForAddress.find(addr);
750 if (it->second.binder.promote() != target) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700751 ALOGE("Binder became invalid during transaction. Bad client? %" PRIu64, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000752 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000753 } else if (transaction->asyncNumber != it->second.asyncNumber) {
754 // we need to process some other asynchronous transaction
755 // first
Steven Morelandf5174272021-05-25 00:39:28 +0000756 it->second.asyncTodo.push(BinderNode::AsyncTodo{
757 .ref = target,
758 .data = std::move(transactionData),
759 .asyncNumber = transaction->asyncNumber,
760 });
Steven Morelandd45be622021-06-04 02:19:37 +0000761
762 size_t numPending = it->second.asyncTodo.size();
Steven Moreland5623d1a2021-09-10 15:45:34 -0700763 LOG_RPC_DETAIL("Enqueuing %" PRIu64 " on %" PRIu64 " (%zu pending)",
764 transaction->asyncNumber, addr, numPending);
Steven Morelandd45be622021-06-04 02:19:37 +0000765
766 constexpr size_t kArbitraryOnewayCallTerminateLevel = 10000;
767 constexpr size_t kArbitraryOnewayCallWarnLevel = 1000;
768 constexpr size_t kArbitraryOnewayCallWarnPer = 1000;
769
770 if (numPending >= kArbitraryOnewayCallWarnLevel) {
771 if (numPending >= kArbitraryOnewayCallTerminateLevel) {
772 ALOGE("WARNING: %zu pending oneway transactions. Terminating!", numPending);
773 _l.unlock();
774 (void)session->shutdownAndWait(false);
775 return FAILED_TRANSACTION;
776 }
777
778 if (numPending % kArbitraryOnewayCallWarnPer == 0) {
779 ALOGW("Warning: many oneway transactions built up on %p (%zu)",
780 target.get(), numPending);
781 }
782 }
Steven Morelandf5174272021-05-25 00:39:28 +0000783 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000784 }
785 }
786 }
787
Steven Moreland5553ac42020-11-11 02:14:45 +0000788 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000789 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000790
791 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000792 Parcel data;
793 // transaction->data is owned by this function. Parcel borrows this data and
794 // only holds onto it for the duration of this function call. Parcel will be
795 // deleted before the 'transactionData' object.
796 data.ipcSetDataReference(transaction->data,
797 transactionData.size() - offsetof(RpcWireTransaction, data),
798 nullptr /*object*/, 0 /*objectCount*/,
799 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000800 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000801
Steven Moreland5553ac42020-11-11 02:14:45 +0000802 if (target) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000803 bool origAllowNested = connection->allowNested;
804 connection->allowNested = !oneway;
805
Steven Moreland5553ac42020-11-11 02:14:45 +0000806 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
Steven Morelandc7d40132021-06-10 03:42:11 +0000807
808 connection->allowNested = origAllowNested;
Steven Moreland5553ac42020-11-11 02:14:45 +0000809 } else {
810 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000811
Steven Moreland103424e2021-06-02 18:16:19 +0000812 switch (transaction->code) {
813 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
814 replyStatus = reply.writeInt32(session->getMaxThreads());
815 break;
816 }
817 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
818 // for client connections, this should always report the value
Steven Moreland01a6bad2021-06-11 00:59:20 +0000819 // originally returned from the server, so this is asserting
820 // that it exists
Steven Moreland826367f2021-09-10 14:05:31 -0700821 replyStatus = reply.writeByteVector(session->mId);
Steven Moreland103424e2021-06-02 18:16:19 +0000822 break;
823 }
824 default: {
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000825 sp<RpcServer> server = session->server();
Steven Moreland103424e2021-06-02 18:16:19 +0000826 if (server) {
827 switch (transaction->code) {
828 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
829 replyStatus = reply.writeStrongBinder(server->getRootObject());
830 break;
831 }
832 default: {
833 replyStatus = UNKNOWN_TRANSACTION;
834 }
835 }
836 } else {
837 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000838 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000839 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000840 }
841 }
842 }
843
Steven Morelandc7d40132021-06-10 03:42:11 +0000844 if (oneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000845 if (replyStatus != OK) {
846 ALOGW("Oneway call failed with error: %d", replyStatus);
847 }
848
Steven Moreland5623d1a2021-09-10 15:45:34 -0700849 LOG_RPC_DETAIL("Processed async transaction %" PRIu64 " on %" PRIu64,
850 transaction->asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000851
852 // Check to see if there is another asynchronous transaction to process.
853 // This behavior differs from binder behavior, since in the binder
854 // driver, asynchronous transactions will be processed after existing
855 // pending binder transactions on the queue. The downside of this is
856 // that asynchronous transactions can be drowned out by synchronous
857 // transactions. However, we have no easy way to queue these
858 // transactions after the synchronous transactions we may want to read
859 // from the wire. So, in socket binder here, we have the opposite
860 // downside: asynchronous transactions may drown out synchronous
861 // transactions.
862 {
863 std::unique_lock<std::mutex> _l(mNodeMutex);
864 auto it = mNodeForAddress.find(addr);
865 // last refcount dropped after this transaction happened
866 if (it == mNodeForAddress.end()) return OK;
867
Steven Morelandc9d7b532021-06-04 20:57:41 +0000868 if (!nodeProgressAsyncNumber(&it->second)) {
869 _l.unlock();
870 (void)session->shutdownAndWait(false);
871 return DEAD_OBJECT;
872 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000873
874 if (it->second.asyncTodo.size() == 0) return OK;
875 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700876 LOG_RPC_DETAIL("Found next async transaction %" PRIu64 " on %" PRIu64,
877 it->second.asyncNumber, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000878
879 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000880 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000881 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000882 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
883
Steven Morelandada72bd2021-06-09 23:29:13 +0000884 // reset up arguments
885 transactionData = std::move(todo.data);
886 targetRef = std::move(todo.ref);
Steven Morelandf5174272021-05-25 00:39:28 +0000887
Steven Moreland5553ac42020-11-11 02:14:45 +0000888 it->second.asyncTodo.pop();
Steven Morelandada72bd2021-06-09 23:29:13 +0000889 goto processTransactInternalTailCall;
Steven Moreland5553ac42020-11-11 02:14:45 +0000890 }
891 }
892 return OK;
893 }
894
Steven Moreland77c30112021-06-02 20:45:46 +0000895 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
896 sizeof(RpcWireReply) <
897 reply.dataSize(),
898 "Too much data for reply %zu", reply.dataSize());
899
900 RpcWireHeader cmdReply{
901 .command = RPC_COMMAND_REPLY,
902 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
903 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000904 RpcWireReply rpcReply{
905 .status = replyStatus,
906 };
907
Steven Moreland77c30112021-06-02 20:45:46 +0000908 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000909 if (!replyData.valid()) {
910 return NO_MEMORY;
911 }
Steven Moreland77c30112021-06-02 20:45:46 +0000912 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
913 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
914 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
915 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000916
Steven Moreland5ae62562021-06-10 03:21:42 +0000917 return rpcSend(connection, session, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000918}
919
Steven Moreland5ae62562021-06-10 03:21:42 +0000920status_t RpcState::processDecStrong(const sp<RpcSession::RpcConnection>& connection,
921 const sp<RpcSession>& session, const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000922 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
923
Steven Morelanddbe71832021-05-12 23:31:00 +0000924 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000925 if (!commandData.valid()) {
926 return NO_MEMORY;
927 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000928 if (status_t status =
Steven Moreland5ae62562021-06-10 03:21:42 +0000929 rpcRec(connection, session, "dec ref body", commandData.data(), commandData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000930 status != OK)
931 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000932
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000933 if (command.bodySize != sizeof(RpcDecStrong)) {
934 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcDecStrong. Terminating!",
935 sizeof(RpcDecStrong), command.bodySize);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000936 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000937 return BAD_VALUE;
938 }
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000939 RpcDecStrong* body = reinterpret_cast<RpcDecStrong*>(commandData.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000940
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000941 uint64_t addr = RpcWireAddress::toRaw(body->address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000942 std::unique_lock<std::mutex> _l(mNodeMutex);
943 auto it = mNodeForAddress.find(addr);
944 if (it == mNodeForAddress.end()) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700945 ALOGE("Unknown binder address %" PRIu64 " for dec strong.", addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000946 return OK;
947 }
948
949 sp<IBinder> target = it->second.binder.promote();
950 if (target == nullptr) {
Steven Moreland5623d1a2021-09-10 15:45:34 -0700951 ALOGE("While requesting dec strong, binder has been deleted at address %" PRIu64
952 ". Terminating!",
953 addr);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000954 _l.unlock();
955 (void)session->shutdownAndWait(false);
Steven Moreland5553ac42020-11-11 02:14:45 +0000956 return BAD_VALUE;
957 }
958
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000959 if (it->second.timesSent < body->amount) {
960 ALOGE("Record of sending binder %zu times, but requested decStrong for %" PRIu64 " of %u",
961 it->second.timesSent, addr, body->amount);
Steven Moreland5553ac42020-11-11 02:14:45 +0000962 return OK;
963 }
964
Steven Moreland5623d1a2021-09-10 15:45:34 -0700965 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %" PRIu64,
966 addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000967
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000968 LOG_RPC_DETAIL("Processing dec strong of %" PRIu64 " by %u from %zu", addr, body->amount,
969 it->second.timesSent);
970
971 it->second.timesSent -= body->amount;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000972 sp<IBinder> tempHold = tryEraseNode(it);
973 _l.unlock();
974 tempHold = nullptr; // destructor may make binder calls on this session
975
976 return OK;
977}
978
Steven Moreland5623d1a2021-09-10 15:45:34 -0700979sp<IBinder> RpcState::tryEraseNode(std::map<uint64_t, BinderNode>::iterator& it) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000980 sp<IBinder> ref;
981
Steven Moreland5553ac42020-11-11 02:14:45 +0000982 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000983 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000984
985 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +0000986 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
987 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +0000988 mNodeForAddress.erase(it);
989 }
990 }
991
Steven Moreland31bde7a2021-06-04 00:57:36 +0000992 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +0000993}
994
Steven Morelandc9d7b532021-06-04 20:57:41 +0000995bool RpcState::nodeProgressAsyncNumber(BinderNode* node) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000996 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
997 // a single binder
998 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
999 ALOGE("Out of async transaction IDs. Terminating");
Steven Moreland583a14a2021-06-04 02:04:58 +00001000 return false;
1001 }
1002 node->asyncNumber++;
1003 return true;
1004}
1005
Steven Moreland5553ac42020-11-11 02:14:45 +00001006} // namespace android