blob: 08bf4ec068e75635a24aa7fc9a6bff75592242f2 [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);
137 ALOGE("DUMP OF RpcState %p", this);
138 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
139 for (const auto& [address, node] : mNodeForAddress) {
140 sp<IBinder> binder = node.binder.promote();
141
142 const char* desc;
143 if (binder) {
144 if (binder->remoteBinder()) {
145 if (binder->remoteBinder()->isRpcBinder()) {
146 desc = "(rpc binder proxy)";
147 } else {
148 desc = "(binder proxy)";
149 }
150 } else {
151 desc = "(local binder)";
152 }
153 } else {
154 desc = "(null)";
155 }
156
157 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a:%s type:%s",
158 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address.toString().c_str(),
159 desc);
160 }
161 ALOGE("END DUMP OF RpcState");
162}
163
164void RpcState::terminate() {
165 if (SHOULD_LOG_RPC_DETAIL) {
166 ALOGE("RpcState::terminate()");
167 dump();
168 }
169
170 // if the destructor of a binder object makes another RPC call, then calling
171 // decStrong could deadlock. So, we must hold onto these binders until
172 // mNodeMutex is no longer taken.
173 std::vector<sp<IBinder>> tempHoldBinder;
174
175 {
176 std::lock_guard<std::mutex> _l(mNodeMutex);
177 mTerminated = true;
178 for (auto& [address, node] : mNodeForAddress) {
179 sp<IBinder> binder = node.binder.promote();
180 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
181
182 if (node.sentRef != nullptr) {
183 tempHoldBinder.push_back(node.sentRef);
184 }
185 }
186
187 mNodeForAddress.clear();
188 }
189}
190
Steven Morelanddbe71832021-05-12 23:31:00 +0000191RpcState::CommandData::CommandData(size_t size) : mSize(size) {
192 // The maximum size for regular binder is 1MB for all concurrent
193 // transactions. A very small proportion of transactions are even
194 // larger than a page, but we need to avoid allocating too much
195 // data on behalf of an arbitrary client, or we could risk being in
196 // a position where a single additional allocation could run out of
197 // memory.
198 //
199 // Note, this limit may not reflect the total amount of data allocated for a
200 // transaction (in some cases, additional fixed size amounts are added),
201 // though for rough consistency, we should avoid cases where this data type
202 // is used for multiple dynamic allocations for a single transaction.
203 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
204 if (size == 0) return;
205 if (size > kMaxTransactionAllocation) {
206 ALOGW("Transaction requested too much data allocation %zu", size);
207 return;
208 }
209 mData.reset(new (std::nothrow) uint8_t[size]);
210}
211
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000212status_t RpcState::rpcSend(const base::unique_fd& fd, const char* what, const void* data,
213 size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000214 LOG_RPC_DETAIL("Sending %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
215
216 if (size > std::numeric_limits<ssize_t>::max()) {
217 ALOGE("Cannot send %s at size %zu (too big)", what, size);
218 terminate();
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000219 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000220 }
221
Steven Morelandc6ddf362021-04-02 01:13:36 +0000222 ssize_t sent = TEMP_FAILURE_RETRY(send(fd.get(), data, size, MSG_NOSIGNAL));
Steven Moreland5553ac42020-11-11 02:14:45 +0000223
224 if (sent < 0 || sent != static_cast<ssize_t>(size)) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000225 int savedErrno = errno;
Steven Morelandc12c9d92021-05-26 18:44:11 +0000226 LOG_RPC_DETAIL("Failed to send %s (sent %zd of %zu bytes) on fd %d, error: %s", what, sent,
227 size, fd.get(), strerror(savedErrno));
Steven Moreland5553ac42020-11-11 02:14:45 +0000228
229 terminate();
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000230 return -savedErrno;
Steven Moreland5553ac42020-11-11 02:14:45 +0000231 }
232
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000233 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000234}
235
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000236status_t RpcState::rpcRec(const base::unique_fd& fd, const sp<RpcSession>& session,
237 const char* what, void* data, size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000238 if (size > std::numeric_limits<ssize_t>::max()) {
239 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
240 terminate();
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000241 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000242 }
243
Steven Morelandee3f4662021-05-22 01:07:33 +0000244 if (status_t status = session->mShutdownTrigger->interruptableReadFully(fd.get(), data, size);
245 status != OK) {
Steven Morelandc12c9d92021-05-26 18:44:11 +0000246 LOG_RPC_DETAIL("Failed to read %s (%zu bytes) on fd %d, error: %s", what, size, fd.get(),
247 statusToString(status).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000248 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000249 }
250
Steven Morelandee3f4662021-05-22 01:07:33 +0000251 LOG_RPC_DETAIL("Received %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000252 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000253}
254
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000255sp<IBinder> RpcState::getRootObject(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000256 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000257 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000258 Parcel reply;
259
Steven Morelandf5174272021-05-25 00:39:28 +0000260 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT, data,
261 session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000262 if (status != OK) {
263 ALOGE("Error getting root object: %s", statusToString(status).c_str());
264 return nullptr;
265 }
266
267 return reply.readStrongBinder();
268}
269
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000270status_t RpcState::getMaxThreads(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000271 size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000272 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000273 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000274 Parcel reply;
275
Steven Morelandf5174272021-05-25 00:39:28 +0000276 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS,
277 data, session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000278 if (status != OK) {
279 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
280 return status;
281 }
282
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000283 int32_t maxThreads;
284 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000285 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000286 if (maxThreads <= 0) {
287 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000288 return BAD_VALUE;
289 }
290
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000291 *maxThreadsOut = maxThreads;
292 return OK;
293}
294
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000295status_t RpcState::getSessionId(const base::unique_fd& fd, const sp<RpcSession>& session,
296 int32_t* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000297 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000298 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000299 Parcel reply;
300
Steven Morelandf5174272021-05-25 00:39:28 +0000301 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_SESSION_ID,
302 data, session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000303 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000304 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000305 return status;
306 }
307
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000308 int32_t sessionId;
309 status = reply.readInt32(&sessionId);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000310 if (status != OK) return status;
311
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000312 *sessionIdOut = sessionId;
Steven Morelandf137de92021-04-24 01:54:26 +0000313 return OK;
314}
315
Steven Morelandf5174272021-05-25 00:39:28 +0000316status_t RpcState::transact(const base::unique_fd& fd, const sp<IBinder>& binder, uint32_t code,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000317 const Parcel& data, const sp<RpcSession>& session, Parcel* reply,
Steven Moreland5553ac42020-11-11 02:14:45 +0000318 uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000319 if (!data.isForRpc()) {
320 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
321 return BAD_TYPE;
322 }
323
324 if (data.objectsCount() != 0) {
325 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
326 return BAD_TYPE;
327 }
328
329 RpcAddress address = RpcAddress::zero();
330 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
331
332 return transactAddress(fd, address, code, data, session, reply, flags);
333}
334
335status_t RpcState::transactAddress(const base::unique_fd& fd, const RpcAddress& address,
336 uint32_t code, const Parcel& data, const sp<RpcSession>& session,
337 Parcel* reply, uint32_t flags) {
338 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
339 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
340
Steven Moreland5553ac42020-11-11 02:14:45 +0000341 uint64_t asyncNumber = 0;
342
343 if (!address.isZero()) {
344 std::lock_guard<std::mutex> _l(mNodeMutex);
345 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
346 auto it = mNodeForAddress.find(address);
347 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
348 address.toString().c_str());
349
350 if (flags & IBinder::FLAG_ONEWAY) {
351 asyncNumber = it->second.asyncNumber++;
352 }
353 }
354
Steven Moreland77c30112021-06-02 20:45:46 +0000355 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
356 sizeof(RpcWireTransaction) <
357 data.dataSize(),
358 "Too much data %zu", data.dataSize());
359
360 RpcWireHeader command{
361 .command = RPC_COMMAND_TRANSACT,
362 .bodySize = static_cast<uint32_t>(sizeof(RpcWireTransaction) + data.dataSize()),
363 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000364 RpcWireTransaction transaction{
365 .address = address.viewRawEmbedded(),
366 .code = code,
367 .flags = flags,
368 .asyncNumber = asyncNumber,
369 };
Steven Moreland77c30112021-06-02 20:45:46 +0000370 CommandData transactionData(sizeof(RpcWireHeader) + sizeof(RpcWireTransaction) +
371 data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000372 if (!transactionData.valid()) {
373 return NO_MEMORY;
374 }
375
Steven Moreland77c30112021-06-02 20:45:46 +0000376 memcpy(transactionData.data() + 0, &command, sizeof(RpcWireHeader));
377 memcpy(transactionData.data() + sizeof(RpcWireHeader), &transaction,
378 sizeof(RpcWireTransaction));
379 memcpy(transactionData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireTransaction), data.data(),
380 data.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000381
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000382 if (status_t status =
Steven Moreland77c30112021-06-02 20:45:46 +0000383 rpcSend(fd, "transaction", transactionData.data(), transactionData.size());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000384 status != OK)
385 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000386
387 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland659416d2021-05-11 00:47:50 +0000388 LOG_RPC_DETAIL("Oneway command, so no longer waiting on %d", fd.get());
Steven Moreland52eee942021-06-03 00:59:28 +0000389
390 // Do not wait on result.
391 // However, too many oneway calls may cause refcounts to build up and fill up the socket,
392 // so process those.
393 return drainCommands(fd, session, CommandType::CONTROL_ONLY);
Steven Moreland5553ac42020-11-11 02:14:45 +0000394 }
395
396 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
397
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000398 return waitForReply(fd, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000399}
400
Steven Moreland438cce82021-04-02 18:04:08 +0000401static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
402 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000403 (void)p;
404 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
405 (void)dataSize;
406 LOG_ALWAYS_FATAL_IF(objects != nullptr);
407 LOG_ALWAYS_FATAL_IF(objectsCount, 0);
408}
409
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000410status_t RpcState::waitForReply(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000411 Parcel* reply) {
412 RpcWireHeader command;
413 while (true) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000414 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
415 status != OK)
416 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000417
418 if (command.command == RPC_COMMAND_REPLY) break;
419
Steven Moreland52eee942021-06-03 00:59:28 +0000420 if (status_t status = processServerCommand(fd, session, command, CommandType::ANY);
421 status != OK)
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000422 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000423 }
424
Steven Morelanddbe71832021-05-12 23:31:00 +0000425 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000426 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000427
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000428 if (status_t status = rpcRec(fd, session, "reply body", data.data(), command.bodySize);
429 status != OK)
430 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000431
432 if (command.bodySize < sizeof(RpcWireReply)) {
433 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
434 sizeof(RpcWireReply), command.bodySize);
435 terminate();
436 return BAD_VALUE;
437 }
Steven Morelande8393342021-05-05 23:27:53 +0000438 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000439 if (rpcReply->status != OK) return rpcReply->status;
440
Steven Morelande8393342021-05-05 23:27:53 +0000441 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000442 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000443 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000444
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000445 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000446
447 return OK;
448}
449
450status_t RpcState::sendDecStrong(const base::unique_fd& fd, const RpcAddress& addr) {
451 {
452 std::lock_guard<std::mutex> _l(mNodeMutex);
453 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
454 auto it = mNodeForAddress.find(addr);
455 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
456 addr.toString().c_str());
457 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
458 addr.toString().c_str());
459
460 it->second.timesRecd--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000461 LOG_ALWAYS_FATAL_IF(nullptr != tryEraseNode(it),
462 "Bad state. RpcState shouldn't own received binder");
Steven Moreland5553ac42020-11-11 02:14:45 +0000463 }
464
465 RpcWireHeader cmd = {
466 .command = RPC_COMMAND_DEC_STRONG,
467 .bodySize = sizeof(RpcWireAddress),
468 };
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000469 if (status_t status = rpcSend(fd, "dec ref header", &cmd, sizeof(cmd)); status != OK)
470 return status;
471 if (status_t status =
472 rpcSend(fd, "dec ref body", &addr.viewRawEmbedded(), sizeof(RpcWireAddress));
473 status != OK)
474 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000475 return OK;
476}
477
Steven Moreland52eee942021-06-03 00:59:28 +0000478status_t RpcState::getAndExecuteCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
479 CommandType type) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000480 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", fd.get());
481
482 RpcWireHeader command;
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000483 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
484 status != OK)
485 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000486
Steven Moreland52eee942021-06-03 00:59:28 +0000487 return processServerCommand(fd, session, command, type);
488}
489
490status_t RpcState::drainCommands(const base::unique_fd& fd, const sp<RpcSession>& session,
491 CommandType type) {
492 uint8_t buf;
493 while (0 < TEMP_FAILURE_RETRY(recv(fd.get(), &buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT))) {
494 status_t status = getAndExecuteCommand(fd, session, type);
495 if (status != OK) return status;
496 }
497 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000498}
499
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000500status_t RpcState::processServerCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland52eee942021-06-03 00:59:28 +0000501 const RpcWireHeader& command, CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000502 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
503 IPCThreadState::SpGuard spGuard{
504 .address = __builtin_frame_address(0),
505 .context = "processing binder RPC command",
506 };
507 const IPCThreadState::SpGuard* origGuard;
508 if (kernelBinderState != nullptr) {
509 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
510 }
511 ScopeGuard guardUnguard = [&]() {
512 if (kernelBinderState != nullptr) {
513 kernelBinderState->restoreGetCallingSpGuard(origGuard);
514 }
515 };
516
Steven Moreland5553ac42020-11-11 02:14:45 +0000517 switch (command.command) {
518 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000519 if (type != CommandType::ANY) return BAD_TYPE;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000520 return processTransact(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000521 case RPC_COMMAND_DEC_STRONG:
Steven Morelandee3f4662021-05-22 01:07:33 +0000522 return processDecStrong(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000523 }
524
525 // We should always know the version of the opposing side, and since the
526 // RPC-binder-level wire protocol is not self synchronizing, we have no way
527 // to understand where the current command ends and the next one begins. We
528 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000529 // to kill us, so ending the session for misbehaving client.
530 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000531 terminate();
532 return DEAD_OBJECT;
533}
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000534status_t RpcState::processTransact(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000535 const RpcWireHeader& command) {
536 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
537
Steven Morelanddbe71832021-05-12 23:31:00 +0000538 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000539 if (!transactionData.valid()) {
540 return NO_MEMORY;
541 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000542 if (status_t status = rpcRec(fd, session, "transaction body", transactionData.data(),
543 transactionData.size());
544 status != OK)
545 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000546
Steven Morelandf5174272021-05-25 00:39:28 +0000547 return processTransactInternal(fd, session, std::move(transactionData), nullptr /*targetRef*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000548}
549
Steven Moreland438cce82021-04-02 18:04:08 +0000550static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
551 const binder_size_t* objects, size_t objectsCount) {
552 (void)p;
553 (void)data;
554 (void)dataSize;
555 (void)objects;
556 (void)objectsCount;
557}
558
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000559status_t RpcState::processTransactInternal(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Morelandf5174272021-05-25 00:39:28 +0000560 CommandData transactionData, sp<IBinder>&& targetRef) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000561 if (transactionData.size() < sizeof(RpcWireTransaction)) {
562 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
563 sizeof(RpcWireTransaction), transactionData.size());
564 terminate();
565 return BAD_VALUE;
566 }
567 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
568
569 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
570 // maybe add an RpcAddress 'view' if the type remains 'heavy'
571 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
572
573 status_t replyStatus = OK;
574 sp<IBinder> target;
575 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000576 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000577 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000578 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000579 target = targetRef;
580 }
581
Steven Moreland7227c8a2021-06-02 00:24:32 +0000582 if (replyStatus != OK) {
583 // do nothing
584 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000585 // This can happen if the binder is remote in this process, and
586 // another thread has called the last decStrong on this binder.
587 // However, for local binders, it indicates a misbehaving client
588 // (any binder which is being transacted on should be holding a
589 // strong ref count), so in either case, terminating the
590 // session.
591 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
592 addr.toString().c_str());
593 terminate();
594 replyStatus = BAD_VALUE;
595 } else if (target->localBinder() == nullptr) {
596 ALOGE("Unknown binder address or non-local binder, not address %s. Terminating!",
597 addr.toString().c_str());
598 terminate();
599 replyStatus = BAD_VALUE;
600 } else if (transaction->flags & IBinder::FLAG_ONEWAY) {
601 std::lock_guard<std::mutex> _l(mNodeMutex);
602 auto it = mNodeForAddress.find(addr);
603 if (it->second.binder.promote() != target) {
604 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000605 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000606 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000607 } else if (transaction->asyncNumber != it->second.asyncNumber) {
608 // we need to process some other asynchronous transaction
609 // first
610 // TODO(b/183140903): limit enqueues/detect overfill for bad client
611 // TODO(b/183140903): detect when an object is deleted when it still has
612 // pending async transactions
613 it->second.asyncTodo.push(BinderNode::AsyncTodo{
614 .ref = target,
615 .data = std::move(transactionData),
616 .asyncNumber = transaction->asyncNumber,
617 });
618 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s", transaction->asyncNumber,
619 addr.toString().c_str());
620 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000621 }
622 }
623 }
624
Steven Moreland5553ac42020-11-11 02:14:45 +0000625 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000626 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000627
628 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000629 Parcel data;
630 // transaction->data is owned by this function. Parcel borrows this data and
631 // only holds onto it for the duration of this function call. Parcel will be
632 // deleted before the 'transactionData' object.
633 data.ipcSetDataReference(transaction->data,
634 transactionData.size() - offsetof(RpcWireTransaction, data),
635 nullptr /*object*/, 0 /*objectCount*/,
636 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000637 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000638
Steven Moreland5553ac42020-11-11 02:14:45 +0000639 if (target) {
640 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
641 } else {
642 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000643
Steven Moreland103424e2021-06-02 18:16:19 +0000644 switch (transaction->code) {
645 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
646 replyStatus = reply.writeInt32(session->getMaxThreads());
647 break;
648 }
649 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
650 // for client connections, this should always report the value
651 // originally returned from the server
652 int32_t id = session->mId.value();
653 replyStatus = reply.writeInt32(id);
654 break;
655 }
656 default: {
657 sp<RpcServer> server = session->server().promote();
658 if (server) {
659 switch (transaction->code) {
660 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
661 replyStatus = reply.writeStrongBinder(server->getRootObject());
662 break;
663 }
664 default: {
665 replyStatus = UNKNOWN_TRANSACTION;
666 }
667 }
668 } else {
669 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000670 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000671 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000672 }
673 }
674 }
675
676 if (transaction->flags & IBinder::FLAG_ONEWAY) {
677 if (replyStatus != OK) {
678 ALOGW("Oneway call failed with error: %d", replyStatus);
679 }
680
681 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
682 addr.toString().c_str());
683
684 // Check to see if there is another asynchronous transaction to process.
685 // This behavior differs from binder behavior, since in the binder
686 // driver, asynchronous transactions will be processed after existing
687 // pending binder transactions on the queue. The downside of this is
688 // that asynchronous transactions can be drowned out by synchronous
689 // transactions. However, we have no easy way to queue these
690 // transactions after the synchronous transactions we may want to read
691 // from the wire. So, in socket binder here, we have the opposite
692 // downside: asynchronous transactions may drown out synchronous
693 // transactions.
694 {
695 std::unique_lock<std::mutex> _l(mNodeMutex);
696 auto it = mNodeForAddress.find(addr);
697 // last refcount dropped after this transaction happened
698 if (it == mNodeForAddress.end()) return OK;
699
700 // note - only updated now, instead of later, so that other threads
701 // will queue any later transactions
702
703 // TODO(b/183140903): support > 2**64 async transactions
704 // (we can do this by allowing asyncNumber to wrap, since we
705 // don't expect more than 2**64 simultaneous transactions)
706 it->second.asyncNumber++;
707
708 if (it->second.asyncTodo.size() == 0) return OK;
709 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
710 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
711 it->second.asyncNumber, addr.toString().c_str());
712
713 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000714 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000715 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000716 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
717
718 CommandData nextData = std::move(todo.data);
719 sp<IBinder> nextRef = std::move(todo.ref);
720
Steven Moreland5553ac42020-11-11 02:14:45 +0000721 it->second.asyncTodo.pop();
722 _l.unlock();
Steven Morelandf5174272021-05-25 00:39:28 +0000723 return processTransactInternal(fd, session, std::move(nextData),
724 std::move(nextRef));
Steven Moreland5553ac42020-11-11 02:14:45 +0000725 }
726 }
727 return OK;
728 }
729
Steven Moreland77c30112021-06-02 20:45:46 +0000730 LOG_ALWAYS_FATAL_IF(std::numeric_limits<int32_t>::max() - sizeof(RpcWireHeader) -
731 sizeof(RpcWireReply) <
732 reply.dataSize(),
733 "Too much data for reply %zu", reply.dataSize());
734
735 RpcWireHeader cmdReply{
736 .command = RPC_COMMAND_REPLY,
737 .bodySize = static_cast<uint32_t>(sizeof(RpcWireReply) + reply.dataSize()),
738 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000739 RpcWireReply rpcReply{
740 .status = replyStatus,
741 };
742
Steven Moreland77c30112021-06-02 20:45:46 +0000743 CommandData replyData(sizeof(RpcWireHeader) + sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000744 if (!replyData.valid()) {
745 return NO_MEMORY;
746 }
Steven Moreland77c30112021-06-02 20:45:46 +0000747 memcpy(replyData.data() + 0, &cmdReply, sizeof(RpcWireHeader));
748 memcpy(replyData.data() + sizeof(RpcWireHeader), &rpcReply, sizeof(RpcWireReply));
749 memcpy(replyData.data() + sizeof(RpcWireHeader) + sizeof(RpcWireReply), reply.data(),
750 reply.dataSize());
Steven Moreland5553ac42020-11-11 02:14:45 +0000751
Steven Moreland77c30112021-06-02 20:45:46 +0000752 return rpcSend(fd, "reply", replyData.data(), replyData.size());
Steven Moreland5553ac42020-11-11 02:14:45 +0000753}
754
Steven Morelandee3f4662021-05-22 01:07:33 +0000755status_t RpcState::processDecStrong(const base::unique_fd& fd, const sp<RpcSession>& session,
756 const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000757 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
758
Steven Morelanddbe71832021-05-12 23:31:00 +0000759 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000760 if (!commandData.valid()) {
761 return NO_MEMORY;
762 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000763 if (status_t status =
764 rpcRec(fd, session, "dec ref body", commandData.data(), commandData.size());
765 status != OK)
766 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000767
768 if (command.bodySize < sizeof(RpcWireAddress)) {
769 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
770 sizeof(RpcWireAddress), command.bodySize);
771 terminate();
772 return BAD_VALUE;
773 }
774 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
775
776 // TODO(b/182939933): heap allocation just for lookup
777 auto addr = RpcAddress::fromRawEmbedded(address);
778 std::unique_lock<std::mutex> _l(mNodeMutex);
779 auto it = mNodeForAddress.find(addr);
780 if (it == mNodeForAddress.end()) {
781 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000782 return OK;
783 }
784
785 sp<IBinder> target = it->second.binder.promote();
786 if (target == nullptr) {
787 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
788 addr.toString().c_str());
789 terminate();
790 return BAD_VALUE;
791 }
792
793 if (it->second.timesSent == 0) {
794 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
795 return OK;
796 }
797
798 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
799 addr.toString().c_str());
800
Steven Moreland5553ac42020-11-11 02:14:45 +0000801 it->second.timesSent--;
Steven Moreland31bde7a2021-06-04 00:57:36 +0000802 sp<IBinder> tempHold = tryEraseNode(it);
803 _l.unlock();
804 tempHold = nullptr; // destructor may make binder calls on this session
805
806 return OK;
807}
808
809sp<IBinder> RpcState::tryEraseNode(std::map<RpcAddress, BinderNode>::iterator& it) {
810 sp<IBinder> ref;
811
Steven Moreland5553ac42020-11-11 02:14:45 +0000812 if (it->second.timesSent == 0) {
Steven Moreland31bde7a2021-06-04 00:57:36 +0000813 ref = std::move(it->second.sentRef);
Steven Moreland5553ac42020-11-11 02:14:45 +0000814
815 if (it->second.timesRecd == 0) {
Steven Morelanda6e11cf2021-06-04 00:58:31 +0000816 LOG_ALWAYS_FATAL_IF(!it->second.asyncTodo.empty(),
817 "Can't delete binder w/ pending async transactions");
Steven Moreland5553ac42020-11-11 02:14:45 +0000818 mNodeForAddress.erase(it);
819 }
820 }
821
Steven Moreland31bde7a2021-06-04 00:57:36 +0000822 return ref;
Steven Moreland5553ac42020-11-11 02:14:45 +0000823}
824
825} // namespace android