blob: 93f15294dff52ea99c2805e80e0cbfdea2ab7499 [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 Morelandd7302072021-05-15 01:32:04 +000021#include <android-base/scopeguard.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000022#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000023#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000024#include <binder/RpcServer.h>
25
26#include "Debug.h"
27#include "RpcWireFormat.h"
28
29#include <inttypes.h>
30
31namespace android {
32
Steven Morelandd7302072021-05-15 01:32:04 +000033using base::ScopeGuard;
34
Steven Moreland5553ac42020-11-11 02:14:45 +000035RpcState::RpcState() {}
36RpcState::~RpcState() {}
37
Steven Morelandbdb53ab2021-05-05 17:57:41 +000038status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5553ac42020-11-11 02:14:45 +000039 RpcAddress* outAddress) {
40 bool isRemote = binder->remoteBinder();
41 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
42
Steven Morelandbdb53ab2021-05-05 17:57:41 +000043 if (isRpc && binder->remoteBinder()->getPrivateAccessorForId().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000044 // We need to be able to send instructions over the socket for how to
45 // connect to a different server, and we also need to let the host
46 // process know that this is happening.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000047 ALOGE("Cannot send binder from unrelated binder RPC session.");
Steven Moreland5553ac42020-11-11 02:14:45 +000048 return INVALID_OPERATION;
49 }
50
51 if (isRemote && !isRpc) {
52 // Without additional work, this would have the effect of using this
53 // process to proxy calls from the socket over to the other process, and
54 // it would make those calls look like they come from us (not over the
55 // sockets). In order to make this work transparently like binder, we
56 // would instead need to send instructions over the socket for how to
57 // connect to the host process, and we also need to let the host process
58 // know this was happening.
59 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
60 return INVALID_OPERATION;
61 }
62
63 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +000064 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +000065
66 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
67 // in RpcState
68 for (auto& [addr, node] : mNodeForAddress) {
69 if (binder == node.binder) {
70 if (isRpc) {
71 const RpcAddress& actualAddr =
72 binder->remoteBinder()->getPrivateAccessorForId().rpcAddress();
73 // TODO(b/182939933): this is only checking integrity of data structure
74 // a different data structure doesn't need this
75 LOG_ALWAYS_FATAL_IF(addr < actualAddr, "Address mismatch");
76 LOG_ALWAYS_FATAL_IF(actualAddr < addr, "Address mismatch");
77 }
78 node.timesSent++;
79 node.sentRef = binder; // might already be set
80 *outAddress = addr;
81 return OK;
82 }
83 }
84 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
85
86 auto&& [it, inserted] = mNodeForAddress.insert({RpcAddress::unique(),
87 BinderNode{
88 .binder = binder,
89 .timesSent = 1,
90 .sentRef = binder,
91 }});
92 // TODO(b/182939933): better organization could avoid needing this log
93 LOG_ALWAYS_FATAL_IF(!inserted);
94
95 *outAddress = it->first;
96 return OK;
97}
98
Steven Moreland7227c8a2021-06-02 00:24:32 +000099status_t RpcState::onBinderEntering(const sp<RpcSession>& session, const RpcAddress& address,
100 sp<IBinder>* out) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000101 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland7227c8a2021-06-02 00:24:32 +0000102 if (mTerminated) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000103
104 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000105 *out = it->second.binder.promote();
Steven Moreland5553ac42020-11-11 02:14:45 +0000106
107 // implicitly have strong RPC refcount, since we received this binder
108 it->second.timesRecd++;
109
110 _l.unlock();
111
112 // We have timesRecd RPC refcounts, but we only need to hold on to one
113 // when we keep the object. All additional dec strongs are sent
114 // immediately, we wait to send the last one in BpBinder::onLastDecStrong.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000115 (void)session->sendDecStrong(address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000116
Steven Moreland7227c8a2021-06-02 00:24:32 +0000117 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000118 }
119
120 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
121 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
122
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000123 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000124 // device global binders in the RPC world).
Steven Moreland7227c8a2021-06-02 00:24:32 +0000125 it->second.binder = *out = BpBinder::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000126 it->second.timesRecd = 1;
Steven Moreland7227c8a2021-06-02 00:24:32 +0000127 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000128}
129
130size_t RpcState::countBinders() {
131 std::lock_guard<std::mutex> _l(mNodeMutex);
132 return mNodeForAddress.size();
133}
134
135void RpcState::dump() {
136 std::lock_guard<std::mutex> _l(mNodeMutex);
Steven Moreland583a14a2021-06-04 02:04:58 +0000137 dumpLocked();
138}
139
140void RpcState::terminate() {
141 std::unique_lock<std::mutex> _l(mNodeMutex);
142 terminate(_l);
143}
144
145void RpcState::dumpLocked() {
Steven Moreland5553ac42020-11-11 02:14:45 +0000146 ALOGE("DUMP OF RpcState %p", this);
147 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
148 for (const auto& [address, node] : mNodeForAddress) {
149 sp<IBinder> binder = node.binder.promote();
150
151 const char* desc;
152 if (binder) {
153 if (binder->remoteBinder()) {
154 if (binder->remoteBinder()->isRpcBinder()) {
155 desc = "(rpc binder proxy)";
156 } else {
157 desc = "(binder proxy)";
158 }
159 } else {
160 desc = "(local binder)";
161 }
162 } else {
163 desc = "(null)";
164 }
165
166 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a:%s type:%s",
167 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address.toString().c_str(),
168 desc);
169 }
170 ALOGE("END DUMP OF RpcState");
171}
172
Steven Moreland583a14a2021-06-04 02:04:58 +0000173void RpcState::terminate(std::unique_lock<std::mutex>& lock) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000174 if (SHOULD_LOG_RPC_DETAIL) {
175 ALOGE("RpcState::terminate()");
Steven Moreland583a14a2021-06-04 02:04:58 +0000176 dumpLocked();
Steven Moreland5553ac42020-11-11 02:14:45 +0000177 }
178
179 // if the destructor of a binder object makes another RPC call, then calling
180 // decStrong could deadlock. So, we must hold onto these binders until
181 // mNodeMutex is no longer taken.
182 std::vector<sp<IBinder>> tempHoldBinder;
183
Steven Moreland583a14a2021-06-04 02:04:58 +0000184 mTerminated = true;
185 for (auto& [address, node] : mNodeForAddress) {
186 sp<IBinder> binder = node.binder.promote();
187 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000188
Steven Moreland583a14a2021-06-04 02:04:58 +0000189 if (node.sentRef != nullptr) {
190 tempHoldBinder.push_back(node.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000191 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000192 }
Steven Moreland583a14a2021-06-04 02:04:58 +0000193
194 mNodeForAddress.clear();
195
196 lock.unlock();
197 tempHoldBinder.clear(); // explicit
Steven Moreland5553ac42020-11-11 02:14:45 +0000198}
199
Steven Morelanddbe71832021-05-12 23:31:00 +0000200RpcState::CommandData::CommandData(size_t size) : mSize(size) {
201 // The maximum size for regular binder is 1MB for all concurrent
202 // transactions. A very small proportion of transactions are even
203 // larger than a page, but we need to avoid allocating too much
204 // data on behalf of an arbitrary client, or we could risk being in
205 // a position where a single additional allocation could run out of
206 // memory.
207 //
208 // Note, this limit may not reflect the total amount of data allocated for a
209 // transaction (in some cases, additional fixed size amounts are added),
210 // though for rough consistency, we should avoid cases where this data type
211 // is used for multiple dynamic allocations for a single transaction.
212 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
213 if (size == 0) return;
214 if (size > kMaxTransactionAllocation) {
215 ALOGW("Transaction requested too much data allocation %zu", size);
216 return;
217 }
218 mData.reset(new (std::nothrow) uint8_t[size]);
219}
220
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000221status_t RpcState::rpcSend(const base::unique_fd& fd, const char* what, const void* data,
222 size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000223 LOG_RPC_DETAIL("Sending %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
224
225 if (size > std::numeric_limits<ssize_t>::max()) {
226 ALOGE("Cannot send %s at size %zu (too big)", what, size);
227 terminate();
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000228 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000229 }
230
Steven Morelandc6ddf362021-04-02 01:13:36 +0000231 ssize_t sent = TEMP_FAILURE_RETRY(send(fd.get(), data, size, MSG_NOSIGNAL));
Steven Moreland5553ac42020-11-11 02:14:45 +0000232
233 if (sent < 0 || sent != static_cast<ssize_t>(size)) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000234 int savedErrno = errno;
Steven Morelandc12c9d92021-05-26 18:44:11 +0000235 LOG_RPC_DETAIL("Failed to send %s (sent %zd of %zu bytes) on fd %d, error: %s", what, sent,
236 size, fd.get(), strerror(savedErrno));
Steven Moreland5553ac42020-11-11 02:14:45 +0000237
238 terminate();
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000239 return -savedErrno;
Steven Moreland5553ac42020-11-11 02:14:45 +0000240 }
241
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000242 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000243}
244
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000245status_t RpcState::rpcRec(const base::unique_fd& fd, const sp<RpcSession>& session,
246 const char* what, void* data, size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000247 if (size > std::numeric_limits<ssize_t>::max()) {
248 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
249 terminate();
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000250 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000251 }
252
Steven Morelandee3f4662021-05-22 01:07:33 +0000253 if (status_t status = session->mShutdownTrigger->interruptableReadFully(fd.get(), data, size);
254 status != OK) {
Steven Morelandc12c9d92021-05-26 18:44:11 +0000255 LOG_RPC_DETAIL("Failed to read %s (%zu bytes) on fd %d, error: %s", what, size, fd.get(),
256 statusToString(status).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000257 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000258 }
259
Steven Morelandee3f4662021-05-22 01:07:33 +0000260 LOG_RPC_DETAIL("Received %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000261 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000262}
263
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000264sp<IBinder> RpcState::getRootObject(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000265 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000266 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000267 Parcel reply;
268
Steven Morelandf5174272021-05-25 00:39:28 +0000269 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT, data,
270 session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000271 if (status != OK) {
272 ALOGE("Error getting root object: %s", statusToString(status).c_str());
273 return nullptr;
274 }
275
276 return reply.readStrongBinder();
277}
278
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000279status_t RpcState::getMaxThreads(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000280 size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000281 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000282 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000283 Parcel reply;
284
Steven Morelandf5174272021-05-25 00:39:28 +0000285 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS,
286 data, session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000287 if (status != OK) {
288 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
289 return status;
290 }
291
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000292 int32_t maxThreads;
293 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000294 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000295 if (maxThreads <= 0) {
296 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000297 return BAD_VALUE;
298 }
299
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000300 *maxThreadsOut = maxThreads;
301 return OK;
302}
303
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000304status_t RpcState::getSessionId(const base::unique_fd& fd, const sp<RpcSession>& session,
305 int32_t* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000306 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000307 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000308 Parcel reply;
309
Steven Morelandf5174272021-05-25 00:39:28 +0000310 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_SESSION_ID,
311 data, session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000312 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000313 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000314 return status;
315 }
316
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000317 int32_t sessionId;
318 status = reply.readInt32(&sessionId);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000319 if (status != OK) return status;
320
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000321 *sessionIdOut = sessionId;
Steven Morelandf137de92021-04-24 01:54:26 +0000322 return OK;
323}
324
Steven Morelandf5174272021-05-25 00:39:28 +0000325status_t RpcState::transact(const base::unique_fd& fd, const sp<IBinder>& binder, uint32_t code,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000326 const Parcel& data, const sp<RpcSession>& session, Parcel* reply,
Steven Moreland5553ac42020-11-11 02:14:45 +0000327 uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000328 if (!data.isForRpc()) {
329 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
330 return BAD_TYPE;
331 }
332
333 if (data.objectsCount() != 0) {
334 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
335 return BAD_TYPE;
336 }
337
338 RpcAddress address = RpcAddress::zero();
339 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
340
341 return transactAddress(fd, address, code, data, session, reply, flags);
342}
343
344status_t RpcState::transactAddress(const base::unique_fd& fd, const RpcAddress& address,
345 uint32_t code, const Parcel& data, const sp<RpcSession>& session,
346 Parcel* reply, uint32_t flags) {
347 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
348 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
349
Steven Moreland5553ac42020-11-11 02:14:45 +0000350 uint64_t asyncNumber = 0;
351
352 if (!address.isZero()) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000353 std::unique_lock<std::mutex> _l(mNodeMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000354 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
355 auto it = mNodeForAddress.find(address);
356 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
357 address.toString().c_str());
358
359 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland583a14a2021-06-04 02:04:58 +0000360 asyncNumber = it->second.asyncNumber;
361 if (!nodeProgressAsyncNumber(&it->second, _l)) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000362 }
363 }
364
Steven Moreland77c30112021-06-02 20:45:46 +0000365 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
366 sizeof(RpcWireTransaction) <
367 data.dataSize(),
368 "Too much data %zu", data.dataSize());
369
370 RpcWireHeader command{
371 .command = RPC_COMMAND_TRANSACT,
372 .bodySize = static_cast<uint32_t>(sizeof(RpcWireTransaction) + data.dataSize()),
373 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000374 RpcWireTransaction transaction{
375 .address = address.viewRawEmbedded(),
376 .code = code,
377 .flags = flags,
378 .asyncNumber = asyncNumber,
379 };
Steven Moreland77c30112021-06-02 20:45:46 +0000380 CommandData transactionData(sizeof(RpcWireHeader) + sizeof(RpcWireTransaction) +
381 data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000382 if (!transactionData.valid()) {
383 return NO_MEMORY;
384 }
385
Steven Moreland77c30112021-06-02 20:45:46 +0000386 memcpy(transactionData.data() + 0, &command, sizeof(RpcWireHeader));
387 memcpy(transactionData.data() + sizeof(RpcWireHeader), &transaction,
388 sizeof(RpcWireTransaction));
389 memcpy(transactionData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireTransaction), data.data(),
390 data.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000391
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000392 if (status_t status =
Steven Moreland77c30112021-06-02 20:45:46 +0000393 rpcSend(fd, "transaction", transactionData.data(), transactionData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000394 status != OK)
395 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000396
397 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland659416d2021-05-11 00:47:50 +0000398 LOG_RPC_DETAIL("Oneway command, so no longer waiting on %d", fd.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000399
400 // Do not wait on result.
401 // However, too many oneway calls may cause refcounts to build up and fill up the socket,
402 // so process those.
403 return drainCommands(fd, session, CommandType::CONTROL_ONLY);
Steven Moreland5553ac42020-11-11 02:14:45 +0000404 }
405
406 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
407
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000408 return waitForReply(fd, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000409}
410
Steven Moreland438cce82021-04-02 18:04:08 +0000411static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
412 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000413 (void)p;
414 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
415 (void)dataSize;
416 LOG_ALWAYS_FATAL_IF(objects != nullptr);
417 LOG_ALWAYS_FATAL_IF(objectsCount, 0);
418}
419
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000420status_t RpcState::waitForReply(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000421 Parcel* reply) {
422 RpcWireHeader command;
423 while (true) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000424 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
425 status != OK)
426 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000427
428 if (command.command == RPC_COMMAND_REPLY) break;
429
Steven Moreland52eee942021-06-03 00:59:28 +0000430 if (status_t status = processServerCommand(fd, session, command, CommandType::ANY);
431 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000432 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000433 }
434
Steven Morelanddbe71832021-05-12 23:31:00 +0000435 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000436 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000437
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000438 if (status_t status = rpcRec(fd, session, "reply body", data.data(), command.bodySize);
439 status != OK)
440 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000441
442 if (command.bodySize < sizeof(RpcWireReply)) {
443 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
444 sizeof(RpcWireReply), command.bodySize);
445 terminate();
446 return BAD_VALUE;
447 }
Steven Morelande8393342021-05-05 23:27:53 +0000448 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000449 if (rpcReply->status != OK) return rpcReply->status;
450
Steven Morelande8393342021-05-05 23:27:53 +0000451 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000452 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000453 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000454
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000455 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000456
457 return OK;
458}
459
460status_t RpcState::sendDecStrong(const base::unique_fd& fd, const RpcAddress& addr) {
461 {
462 std::lock_guard<std::mutex> _l(mNodeMutex);
463 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
464 auto it = mNodeForAddress.find(addr);
465 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
466 addr.toString().c_str());
467 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
468 addr.toString().c_str());
469
470 it->second.timesRecd--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000471 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
472 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000473 }
474
475 RpcWireHeader cmd = {
476 .command = RPC_COMMAND_DEC_STRONG,
477 .bodySize = sizeof(RpcWireAddress),
478 };
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000479 if (status_t status = rpcSend(fd, "dec ref header", &cmd, sizeof(cmd)); status != OK)
480 return status;
481 if (status_t status =
482 rpcSend(fd, "dec ref body", &addr.viewRawEmbedded(), sizeof(RpcWireAddress));
483 status != OK)
484 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000485 return OK;
486}
487
Steven Moreland52eee942021-06-03 00:59:28 +0000488status_t RpcState::getAndExecuteCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
489 CommandType type) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000490 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", fd.get());
491
492 RpcWireHeader command;
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000493 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
494 status != OK)
495 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000496
Steven Moreland52eee942021-06-03 00:59:28 +0000497 return processServerCommand(fd, session, command, type);
498}
499
500status_t RpcState::drainCommands(const base::unique_fd& fd, const sp<RpcSession>& session,
501 CommandType type) {
502 uint8_t buf;
503 while (0 < TEMP_FAILURE_RETRY(recv(fd.get(), &buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT))) {
504 status_t status = getAndExecuteCommand(fd, session, type);
505 if (status != OK) return status;
506 }
507 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000508}
509
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000510status_t RpcState::processServerCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland52eee942021-06-03 00:59:28 +0000511 const RpcWireHeader& command, CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000512 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
513 IPCThreadState::SpGuard spGuard{
514 .address = __builtin_frame_address(0),
515 .context = "processing binder RPC command",
516 };
517 const IPCThreadState::SpGuard* origGuard;
518 if (kernelBinderState != nullptr) {
519 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
520 }
521 ScopeGuard guardUnguard = [&]() {
522 if (kernelBinderState != nullptr) {
523 kernelBinderState->restoreGetCallingSpGuard(origGuard);
524 }
525 };
526
Steven Moreland5553ac42020-11-11 02:14:45 +0000527 switch (command.command) {
528 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000529 if (type != CommandType::ANY) return BAD_TYPE;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000530 return processTransact(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000531 case RPC_COMMAND_DEC_STRONG:
Steven Morelandee3f4662021-05-22 01:07:33 +0000532 return processDecStrong(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000533 }
534
535 // We should always know the version of the opposing side, and since the
536 // RPC-binder-level wire protocol is not self synchronizing, we have no way
537 // to understand where the current command ends and the next one begins. We
538 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000539 // to kill us, so ending the session for misbehaving client.
540 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000541 terminate();
542 return DEAD_OBJECT;
543}
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000544status_t RpcState::processTransact(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000545 const RpcWireHeader& command) {
546 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
547
Steven Morelanddbe71832021-05-12 23:31:00 +0000548 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000549 if (!transactionData.valid()) {
550 return NO_MEMORY;
551 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000552 if (status_t status = rpcRec(fd, session, "transaction body", transactionData.data(),
553 transactionData.size());
554 status != OK)
555 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000556
Steven Morelandf5174272021-05-25 00:39:28 +0000557 return processTransactInternal(fd, session, std::move(transactionData), nullptr /*targetRef*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000558}
559
Steven Moreland438cce82021-04-02 18:04:08 +0000560static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
561 const binder_size_t* objects, size_t objectsCount) {
562 (void)p;
563 (void)data;
564 (void)dataSize;
565 (void)objects;
566 (void)objectsCount;
567}
568
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000569status_t RpcState::processTransactInternal(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Morelandf5174272021-05-25 00:39:28 +0000570 CommandData transactionData, sp<IBinder>&& targetRef) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000571 if (transactionData.size() < sizeof(RpcWireTransaction)) {
572 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
573 sizeof(RpcWireTransaction), transactionData.size());
574 terminate();
575 return BAD_VALUE;
576 }
577 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
578
579 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
580 // maybe add an RpcAddress 'view' if the type remains 'heavy'
581 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
582
583 status_t replyStatus = OK;
584 sp<IBinder> target;
585 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000586 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000587 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000588 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000589 target = targetRef;
590 }
591
Steven Moreland7227c8a2021-06-02 00:24:32 +0000592 if (replyStatus != OK) {
593 // do nothing
594 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000595 // This can happen if the binder is remote in this process, and
596 // another thread has called the last decStrong on this binder.
597 // However, for local binders, it indicates a misbehaving client
598 // (any binder which is being transacted on should be holding a
599 // strong ref count), so in either case, terminating the
600 // session.
601 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
602 addr.toString().c_str());
603 terminate();
604 replyStatus = BAD_VALUE;
605 } else if (target->localBinder() == nullptr) {
606 ALOGE("Unknown binder address or non-local binder, not address %s. Terminating!",
607 addr.toString().c_str());
608 terminate();
609 replyStatus = BAD_VALUE;
610 } else if (transaction->flags & IBinder::FLAG_ONEWAY) {
611 std::lock_guard<std::mutex> _l(mNodeMutex);
612 auto it = mNodeForAddress.find(addr);
613 if (it->second.binder.promote() != target) {
614 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000615 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000616 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000617 } else if (transaction->asyncNumber != it->second.asyncNumber) {
618 // we need to process some other asynchronous transaction
619 // first
620 // TODO(b/183140903): limit enqueues/detect overfill for bad client
621 // TODO(b/183140903): detect when an object is deleted when it still has
622 // pending async transactions
623 it->second.asyncTodo.push(BinderNode::AsyncTodo{
624 .ref = target,
625 .data = std::move(transactionData),
626 .asyncNumber = transaction->asyncNumber,
627 });
628 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s", transaction->asyncNumber,
629 addr.toString().c_str());
630 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000631 }
632 }
633 }
634
Steven Moreland5553ac42020-11-11 02:14:45 +0000635 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000636 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000637
638 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000639 Parcel data;
640 // transaction->data is owned by this function. Parcel borrows this data and
641 // only holds onto it for the duration of this function call. Parcel will be
642 // deleted before the 'transactionData' object.
643 data.ipcSetDataReference(transaction->data,
644 transactionData.size() - offsetof(RpcWireTransaction, data),
645 nullptr /*object*/, 0 /*objectCount*/,
646 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000647 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000648
Steven Moreland5553ac42020-11-11 02:14:45 +0000649 if (target) {
650 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
651 } else {
652 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000653
Steven Moreland103424e2021-06-02 18:16:19 +0000654 switch (transaction->code) {
655 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
656 replyStatus = reply.writeInt32(session->getMaxThreads());
657 break;
658 }
659 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
660 // for client connections, this should always report the value
661 // originally returned from the server
662 int32_t id = session->mId.value();
663 replyStatus = reply.writeInt32(id);
664 break;
665 }
666 default: {
667 sp<RpcServer> server = session->server().promote();
668 if (server) {
669 switch (transaction->code) {
670 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
671 replyStatus = reply.writeStrongBinder(server->getRootObject());
672 break;
673 }
674 default: {
675 replyStatus = UNKNOWN_TRANSACTION;
676 }
677 }
678 } else {
679 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000680 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000681 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000682 }
683 }
684 }
685
686 if (transaction->flags & IBinder::FLAG_ONEWAY) {
687 if (replyStatus != OK) {
688 ALOGW("Oneway call failed with error: %d", replyStatus);
689 }
690
691 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
692 addr.toString().c_str());
693
694 // Check to see if there is another asynchronous transaction to process.
695 // This behavior differs from binder behavior, since in the binder
696 // driver, asynchronous transactions will be processed after existing
697 // pending binder transactions on the queue. The downside of this is
698 // that asynchronous transactions can be drowned out by synchronous
699 // transactions. However, we have no easy way to queue these
700 // transactions after the synchronous transactions we may want to read
701 // from the wire. So, in socket binder here, we have the opposite
702 // downside: asynchronous transactions may drown out synchronous
703 // transactions.
704 {
705 std::unique_lock<std::mutex> _l(mNodeMutex);
706 auto it = mNodeForAddress.find(addr);
707 // last refcount dropped after this transaction happened
708 if (it == mNodeForAddress.end()) return OK;
709
Steven Moreland583a14a2021-06-04 02:04:58 +0000710 if (!nodeProgressAsyncNumber(&it->second, _l)) return DEAD_OBJECT;
Steven Moreland5553ac42020-11-11 02:14:45 +0000711
712 if (it->second.asyncTodo.size() == 0) return OK;
713 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
714 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
715 it->second.asyncNumber, addr.toString().c_str());
716
717 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000718 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000719 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000720 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
721
722 CommandData nextData = std::move(todo.data);
723 sp<IBinder> nextRef = std::move(todo.ref);
724
Steven Moreland5553ac42020-11-11 02:14:45 +0000725 it->second.asyncTodo.pop();
726 _l.unlock();
Steven Morelandf5174272021-05-25 00:39:28 +0000727 return processTransactInternal(fd, session, std::move(nextData),
728 std::move(nextRef));
Steven Moreland5553ac42020-11-11 02:14:45 +0000729 }
730 }
731 return OK;
732 }
733
Steven Moreland77c30112021-06-02 20:45:46 +0000734 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
735 sizeof(RpcWireReply) <
736 reply.dataSize(),
737 "Too much data for reply %zu", reply.dataSize());
738
739 RpcWireHeader cmdReply{
740 .command = RPC_COMMAND_REPLY,
741 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
742 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000743 RpcWireReply rpcReply{
744 .status = replyStatus,
745 };
746
Steven Moreland77c30112021-06-02 20:45:46 +0000747 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000748 if (!replyData.valid()) {
749 return NO_MEMORY;
750 }
Steven Moreland77c30112021-06-02 20:45:46 +0000751 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
752 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
753 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
754 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000755
Steven Moreland77c30112021-06-02 20:45:46 +0000756 return rpcSend(fd, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000757}
758
Steven Morelandee3f4662021-05-22 01:07:33 +0000759status_t RpcState::processDecStrong(const base::unique_fd& fd, const sp<RpcSession>& session,
760 const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000761 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
762
Steven Morelanddbe71832021-05-12 23:31:00 +0000763 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000764 if (!commandData.valid()) {
765 return NO_MEMORY;
766 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000767 if (status_t status =
768 rpcRec(fd, session, "dec ref body", commandData.data(), commandData.size());
769 status != OK)
770 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000771
772 if (command.bodySize < sizeof(RpcWireAddress)) {
773 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
774 sizeof(RpcWireAddress), command.bodySize);
775 terminate();
776 return BAD_VALUE;
777 }
778 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
779
780 // TODO(b/182939933): heap allocation just for lookup
781 auto addr = RpcAddress::fromRawEmbedded(address);
782 std::unique_lock<std::mutex> _l(mNodeMutex);
783 auto it = mNodeForAddress.find(addr);
784 if (it == mNodeForAddress.end()) {
785 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000786 return OK;
787 }
788
789 sp<IBinder> target = it->second.binder.promote();
790 if (target == nullptr) {
791 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
792 addr.toString().c_str());
793 terminate();
794 return BAD_VALUE;
795 }
796
797 if (it->second.timesSent == 0) {
798 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
799 return OK;
800 }
801
802 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
803 addr.toString().c_str());
804
Steven Moreland5553ac42020-11-11 02:14:45 +0000805 it->second.timesSent--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000806 sp<IBinder> tempHold = tryEraseNode(it);
807 _l.unlock();
808 tempHold = nullptr; // destructor may make binder calls on this session
809
810 return OK;
811}
812
813sp<IBinder> RpcState::tryEraseNode(std::map<RpcAddress, BinderNode>::iterator& it) {
814 sp<IBinder> ref;
815
Steven Moreland5553ac42020-11-11 02:14:45 +0000816 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000817 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000818
819 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +0000820 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
821 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +0000822 mNodeForAddress.erase(it);
823 }
824 }
825
Steven Moreland31bde7a2021-06-04 00:57:36 +0000826 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +0000827}
828
Steven Moreland583a14a2021-06-04 02:04:58 +0000829bool RpcState::nodeProgressAsyncNumber(BinderNode* node, std::unique_lock<std::mutex>& lock) {
830 // 2**64 =~ 10**19 =~ 1000 transactions per second for 585 million years to
831 // a single binder
832 if (node->asyncNumber >= std::numeric_limits<decltype(node->asyncNumber)>::max()) {
833 ALOGE("Out of async transaction IDs. Terminating");
834 terminate(lock);
835 return false;
836 }
837 node->asyncNumber++;
838 return true;
839}
840
Steven Moreland5553ac42020-11-11 02:14:45 +0000841} // namespace android