blob: f1cbe0d4a48f38d70a8d4b6b6097be04a23a4565 [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 Moreland5553ac42020-11-11 02:14:45 +0000355 RpcWireTransaction transaction{
356 .address = address.viewRawEmbedded(),
357 .code = code,
358 .flags = flags,
359 .asyncNumber = asyncNumber,
360 };
361
Steven Morelanddbe71832021-05-12 23:31:00 +0000362 CommandData transactionData(sizeof(RpcWireTransaction) + data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000363 if (!transactionData.valid()) {
364 return NO_MEMORY;
365 }
366
Steven Moreland5553ac42020-11-11 02:14:45 +0000367 memcpy(transactionData.data() + 0, &transaction, sizeof(RpcWireTransaction));
368 memcpy(transactionData.data() + sizeof(RpcWireTransaction), data.data(), data.dataSize());
369
370 if (transactionData.size() > std::numeric_limits<uint32_t>::max()) {
371 ALOGE("Transaction size too big %zu", transactionData.size());
372 return BAD_VALUE;
373 }
374
375 RpcWireHeader command{
376 .command = RPC_COMMAND_TRANSACT,
377 .bodySize = static_cast<uint32_t>(transactionData.size()),
378 };
379
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000380 if (status_t status = rpcSend(fd, "transact header", &command, sizeof(command)); status != OK)
381 return status;
382 if (status_t status =
383 rpcSend(fd, "command body", transactionData.data(), transactionData.size());
384 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--;
461 if (it->second.timesRecd == 0 && it->second.timesSent == 0) {
462 mNodeForAddress.erase(it);
463 }
464 }
465
466 RpcWireHeader cmd = {
467 .command = RPC_COMMAND_DEC_STRONG,
468 .bodySize = sizeof(RpcWireAddress),
469 };
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000470 if (status_t status = rpcSend(fd, "dec ref header", &cmd, sizeof(cmd)); status != OK)
471 return status;
472 if (status_t status =
473 rpcSend(fd, "dec ref body", &addr.viewRawEmbedded(), sizeof(RpcWireAddress));
474 status != OK)
475 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000476 return OK;
477}
478
Steven Moreland52eee942021-06-03 00:59:28 +0000479status_t RpcState::getAndExecuteCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
480 CommandType type) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000481 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", fd.get());
482
483 RpcWireHeader command;
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000484 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
485 status != OK)
486 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000487
Steven Moreland52eee942021-06-03 00:59:28 +0000488 return processServerCommand(fd, session, command, type);
489}
490
491status_t RpcState::drainCommands(const base::unique_fd& fd, const sp<RpcSession>& session,
492 CommandType type) {
493 uint8_t buf;
494 while (0 < TEMP_FAILURE_RETRY(recv(fd.get(), &buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT))) {
495 status_t status = getAndExecuteCommand(fd, session, type);
496 if (status != OK) return status;
497 }
498 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000499}
500
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000501status_t RpcState::processServerCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland52eee942021-06-03 00:59:28 +0000502 const RpcWireHeader& command, CommandType type) {
Steven Morelandd7302072021-05-15 01:32:04 +0000503 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
504 IPCThreadState::SpGuard spGuard{
505 .address = __builtin_frame_address(0),
506 .context = "processing binder RPC command",
507 };
508 const IPCThreadState::SpGuard* origGuard;
509 if (kernelBinderState != nullptr) {
510 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
511 }
512 ScopeGuard guardUnguard = [&]() {
513 if (kernelBinderState != nullptr) {
514 kernelBinderState->restoreGetCallingSpGuard(origGuard);
515 }
516 };
517
Steven Moreland5553ac42020-11-11 02:14:45 +0000518 switch (command.command) {
519 case RPC_COMMAND_TRANSACT:
Steven Moreland52eee942021-06-03 00:59:28 +0000520 if (type != CommandType::ANY) return BAD_TYPE;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000521 return processTransact(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000522 case RPC_COMMAND_DEC_STRONG:
Steven Morelandee3f4662021-05-22 01:07:33 +0000523 return processDecStrong(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000524 }
525
526 // We should always know the version of the opposing side, and since the
527 // RPC-binder-level wire protocol is not self synchronizing, we have no way
528 // to understand where the current command ends and the next one begins. We
529 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000530 // to kill us, so ending the session for misbehaving client.
531 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000532 terminate();
533 return DEAD_OBJECT;
534}
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000535status_t RpcState::processTransact(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000536 const RpcWireHeader& command) {
537 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
538
Steven Morelanddbe71832021-05-12 23:31:00 +0000539 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000540 if (!transactionData.valid()) {
541 return NO_MEMORY;
542 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000543 if (status_t status = rpcRec(fd, session, "transaction body", transactionData.data(),
544 transactionData.size());
545 status != OK)
546 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000547
Steven Morelandf5174272021-05-25 00:39:28 +0000548 return processTransactInternal(fd, session, std::move(transactionData), nullptr /*targetRef*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000549}
550
Steven Moreland438cce82021-04-02 18:04:08 +0000551static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
552 const binder_size_t* objects, size_t objectsCount) {
553 (void)p;
554 (void)data;
555 (void)dataSize;
556 (void)objects;
557 (void)objectsCount;
558}
559
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000560status_t RpcState::processTransactInternal(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Morelandf5174272021-05-25 00:39:28 +0000561 CommandData transactionData, sp<IBinder>&& targetRef) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000562 if (transactionData.size() < sizeof(RpcWireTransaction)) {
563 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
564 sizeof(RpcWireTransaction), transactionData.size());
565 terminate();
566 return BAD_VALUE;
567 }
568 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
569
570 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
571 // maybe add an RpcAddress 'view' if the type remains 'heavy'
572 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
573
574 status_t replyStatus = OK;
575 sp<IBinder> target;
576 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000577 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000578 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000579 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000580 target = targetRef;
581 }
582
Steven Moreland7227c8a2021-06-02 00:24:32 +0000583 if (replyStatus != OK) {
584 // do nothing
585 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000586 // This can happen if the binder is remote in this process, and
587 // another thread has called the last decStrong on this binder.
588 // However, for local binders, it indicates a misbehaving client
589 // (any binder which is being transacted on should be holding a
590 // strong ref count), so in either case, terminating the
591 // session.
592 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
593 addr.toString().c_str());
594 terminate();
595 replyStatus = BAD_VALUE;
596 } else if (target->localBinder() == nullptr) {
597 ALOGE("Unknown binder address or non-local binder, not address %s. Terminating!",
598 addr.toString().c_str());
599 terminate();
600 replyStatus = BAD_VALUE;
601 } else if (transaction->flags & IBinder::FLAG_ONEWAY) {
602 std::lock_guard<std::mutex> _l(mNodeMutex);
603 auto it = mNodeForAddress.find(addr);
604 if (it->second.binder.promote() != target) {
605 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000606 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000607 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000608 } else if (transaction->asyncNumber != it->second.asyncNumber) {
609 // we need to process some other asynchronous transaction
610 // first
611 // TODO(b/183140903): limit enqueues/detect overfill for bad client
612 // TODO(b/183140903): detect when an object is deleted when it still has
613 // pending async transactions
614 it->second.asyncTodo.push(BinderNode::AsyncTodo{
615 .ref = target,
616 .data = std::move(transactionData),
617 .asyncNumber = transaction->asyncNumber,
618 });
619 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s", transaction->asyncNumber,
620 addr.toString().c_str());
621 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000622 }
623 }
624 }
625
Steven Moreland5553ac42020-11-11 02:14:45 +0000626 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000627 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000628
629 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000630 Parcel data;
631 // transaction->data is owned by this function. Parcel borrows this data and
632 // only holds onto it for the duration of this function call. Parcel will be
633 // deleted before the 'transactionData' object.
634 data.ipcSetDataReference(transaction->data,
635 transactionData.size() - offsetof(RpcWireTransaction, data),
636 nullptr /*object*/, 0 /*objectCount*/,
637 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000638 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000639
Steven Moreland5553ac42020-11-11 02:14:45 +0000640 if (target) {
641 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
642 } else {
643 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000644
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000645 sp<RpcServer> server = session->server().promote();
Steven Morelandf137de92021-04-24 01:54:26 +0000646 if (server) {
647 // special case for 'zero' address (special server commands)
648 switch (transaction->code) {
649 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
650 replyStatus = reply.writeStrongBinder(server->getRootObject());
651 break;
652 }
653 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
654 replyStatus = reply.writeInt32(server->getMaxThreads());
655 break;
656 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000657 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
658 // only sessions w/ services can be the source of a
659 // session ID (so still guarded by non-null server)
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000660 //
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000661 // sessions associated with servers must have an ID
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000662 // (hence abort)
Steven Morelandee3f4662021-05-22 01:07:33 +0000663 int32_t id = session->mId.value();
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000664 replyStatus = reply.writeInt32(id);
665 break;
666 }
Steven Morelandf137de92021-04-24 01:54:26 +0000667 default: {
668 replyStatus = UNKNOWN_TRANSACTION;
669 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000670 }
Steven Morelandf137de92021-04-24 01:54:26 +0000671 } else {
672 ALOGE("Special command sent, but no server object attached.");
Steven Moreland5553ac42020-11-11 02:14:45 +0000673 }
674 }
675 }
676
677 if (transaction->flags & IBinder::FLAG_ONEWAY) {
678 if (replyStatus != OK) {
679 ALOGW("Oneway call failed with error: %d", replyStatus);
680 }
681
682 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
683 addr.toString().c_str());
684
685 // Check to see if there is another asynchronous transaction to process.
686 // This behavior differs from binder behavior, since in the binder
687 // driver, asynchronous transactions will be processed after existing
688 // pending binder transactions on the queue. The downside of this is
689 // that asynchronous transactions can be drowned out by synchronous
690 // transactions. However, we have no easy way to queue these
691 // transactions after the synchronous transactions we may want to read
692 // from the wire. So, in socket binder here, we have the opposite
693 // downside: asynchronous transactions may drown out synchronous
694 // transactions.
695 {
696 std::unique_lock<std::mutex> _l(mNodeMutex);
697 auto it = mNodeForAddress.find(addr);
698 // last refcount dropped after this transaction happened
699 if (it == mNodeForAddress.end()) return OK;
700
701 // note - only updated now, instead of later, so that other threads
702 // will queue any later transactions
703
704 // TODO(b/183140903): support > 2**64 async transactions
705 // (we can do this by allowing asyncNumber to wrap, since we
706 // don't expect more than 2**64 simultaneous transactions)
707 it->second.asyncNumber++;
708
709 if (it->second.asyncTodo.size() == 0) return OK;
710 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
711 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
712 it->second.asyncNumber, addr.toString().c_str());
713
714 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000715 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000716 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000717 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
718
719 CommandData nextData = std::move(todo.data);
720 sp<IBinder> nextRef = std::move(todo.ref);
721
Steven Moreland5553ac42020-11-11 02:14:45 +0000722 it->second.asyncTodo.pop();
723 _l.unlock();
Steven Morelandf5174272021-05-25 00:39:28 +0000724 return processTransactInternal(fd, session, std::move(nextData),
725 std::move(nextRef));
Steven Moreland5553ac42020-11-11 02:14:45 +0000726 }
727 }
728 return OK;
729 }
730
731 RpcWireReply rpcReply{
732 .status = replyStatus,
733 };
734
Steven Morelanddbe71832021-05-12 23:31:00 +0000735 CommandData replyData(sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000736 if (!replyData.valid()) {
737 return NO_MEMORY;
738 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000739 memcpy(replyData.data() + 0, &rpcReply, sizeof(RpcWireReply));
740 memcpy(replyData.data() + sizeof(RpcWireReply), reply.data(), reply.dataSize());
741
742 if (replyData.size() > std::numeric_limits<uint32_t>::max()) {
743 ALOGE("Reply size too big %zu", transactionData.size());
744 terminate();
745 return BAD_VALUE;
746 }
747
748 RpcWireHeader cmdReply{
749 .command = RPC_COMMAND_REPLY,
750 .bodySize = static_cast<uint32_t>(replyData.size()),
751 };
752
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000753 if (status_t status = rpcSend(fd, "reply header", &cmdReply, sizeof(RpcWireHeader));
754 status != OK)
755 return status;
756 if (status_t status = rpcSend(fd, "reply body", replyData.data(), replyData.size());
757 status != OK)
758 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000759 return OK;
760}
761
Steven Morelandee3f4662021-05-22 01:07:33 +0000762status_t RpcState::processDecStrong(const base::unique_fd& fd, const sp<RpcSession>& session,
763 const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000764 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
765
Steven Morelanddbe71832021-05-12 23:31:00 +0000766 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000767 if (!commandData.valid()) {
768 return NO_MEMORY;
769 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000770 if (status_t status =
771 rpcRec(fd, session, "dec ref body", commandData.data(), commandData.size());
772 status != OK)
773 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000774
775 if (command.bodySize < sizeof(RpcWireAddress)) {
776 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
777 sizeof(RpcWireAddress), command.bodySize);
778 terminate();
779 return BAD_VALUE;
780 }
781 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
782
783 // TODO(b/182939933): heap allocation just for lookup
784 auto addr = RpcAddress::fromRawEmbedded(address);
785 std::unique_lock<std::mutex> _l(mNodeMutex);
786 auto it = mNodeForAddress.find(addr);
787 if (it == mNodeForAddress.end()) {
788 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000789 return OK;
790 }
791
792 sp<IBinder> target = it->second.binder.promote();
793 if (target == nullptr) {
794 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
795 addr.toString().c_str());
796 terminate();
797 return BAD_VALUE;
798 }
799
800 if (it->second.timesSent == 0) {
801 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
802 return OK;
803 }
804
805 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
806 addr.toString().c_str());
807
808 sp<IBinder> tempHold;
809
810 it->second.timesSent--;
811 if (it->second.timesSent == 0) {
812 tempHold = it->second.sentRef;
813 it->second.sentRef = nullptr;
814
815 if (it->second.timesRecd == 0) {
816 mNodeForAddress.erase(it);
817 }
818 }
819
820 _l.unlock();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000821 tempHold = nullptr; // destructor may make binder calls on this session
Steven Moreland5553ac42020-11-11 02:14:45 +0000822
823 return OK;
824}
825
826} // namespace android