blob: 76df97069cf8796deb913c17ca455972747db6b7 [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 Moreland5553ac42020-11-11 02:14:45 +0000389 return OK; // do not wait for result
390 }
391
392 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
393
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000394 return waitForReply(fd, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000395}
396
Steven Moreland438cce82021-04-02 18:04:08 +0000397static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
398 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000399 (void)p;
400 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
401 (void)dataSize;
402 LOG_ALWAYS_FATAL_IF(objects != nullptr);
403 LOG_ALWAYS_FATAL_IF(objectsCount, 0);
404}
405
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000406status_t RpcState::waitForReply(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000407 Parcel* reply) {
408 RpcWireHeader command;
409 while (true) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000410 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
411 status != OK)
412 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000413
414 if (command.command == RPC_COMMAND_REPLY) break;
415
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000416 if (status_t status = processServerCommand(fd, session, command); status != OK)
417 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000418 }
419
Steven Morelanddbe71832021-05-12 23:31:00 +0000420 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000421 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000422
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000423 if (status_t status = rpcRec(fd, session, "reply body", data.data(), command.bodySize);
424 status != OK)
425 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000426
427 if (command.bodySize < sizeof(RpcWireReply)) {
428 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
429 sizeof(RpcWireReply), command.bodySize);
430 terminate();
431 return BAD_VALUE;
432 }
Steven Morelande8393342021-05-05 23:27:53 +0000433 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000434 if (rpcReply->status != OK) return rpcReply->status;
435
Steven Morelande8393342021-05-05 23:27:53 +0000436 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000437 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000438 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000439
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000440 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000441
442 return OK;
443}
444
445status_t RpcState::sendDecStrong(const base::unique_fd& fd, const RpcAddress& addr) {
446 {
447 std::lock_guard<std::mutex> _l(mNodeMutex);
448 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
449 auto it = mNodeForAddress.find(addr);
450 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
451 addr.toString().c_str());
452 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
453 addr.toString().c_str());
454
455 it->second.timesRecd--;
456 if (it->second.timesRecd == 0 && it->second.timesSent == 0) {
457 mNodeForAddress.erase(it);
458 }
459 }
460
461 RpcWireHeader cmd = {
462 .command = RPC_COMMAND_DEC_STRONG,
463 .bodySize = sizeof(RpcWireAddress),
464 };
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000465 if (status_t status = rpcSend(fd, "dec ref header", &cmd, sizeof(cmd)); status != OK)
466 return status;
467 if (status_t status =
468 rpcSend(fd, "dec ref body", &addr.viewRawEmbedded(), sizeof(RpcWireAddress));
469 status != OK)
470 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000471 return OK;
472}
473
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000474status_t RpcState::getAndExecuteCommand(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000475 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", fd.get());
476
477 RpcWireHeader command;
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000478 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
479 status != OK)
480 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000481
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000482 return processServerCommand(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000483}
484
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000485status_t RpcState::processServerCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000486 const RpcWireHeader& command) {
Steven Morelandd7302072021-05-15 01:32:04 +0000487 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
488 IPCThreadState::SpGuard spGuard{
489 .address = __builtin_frame_address(0),
490 .context = "processing binder RPC command",
491 };
492 const IPCThreadState::SpGuard* origGuard;
493 if (kernelBinderState != nullptr) {
494 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
495 }
496 ScopeGuard guardUnguard = [&]() {
497 if (kernelBinderState != nullptr) {
498 kernelBinderState->restoreGetCallingSpGuard(origGuard);
499 }
500 };
501
Steven Moreland5553ac42020-11-11 02:14:45 +0000502 switch (command.command) {
503 case RPC_COMMAND_TRANSACT:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000504 return processTransact(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000505 case RPC_COMMAND_DEC_STRONG:
Steven Morelandee3f4662021-05-22 01:07:33 +0000506 return processDecStrong(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000507 }
508
509 // We should always know the version of the opposing side, and since the
510 // RPC-binder-level wire protocol is not self synchronizing, we have no way
511 // to understand where the current command ends and the next one begins. We
512 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000513 // to kill us, so ending the session for misbehaving client.
514 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000515 terminate();
516 return DEAD_OBJECT;
517}
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000518status_t RpcState::processTransact(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000519 const RpcWireHeader& command) {
520 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
521
Steven Morelanddbe71832021-05-12 23:31:00 +0000522 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000523 if (!transactionData.valid()) {
524 return NO_MEMORY;
525 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000526 if (status_t status = rpcRec(fd, session, "transaction body", transactionData.data(),
527 transactionData.size());
528 status != OK)
529 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000530
Steven Morelandf5174272021-05-25 00:39:28 +0000531 return processTransactInternal(fd, session, std::move(transactionData), nullptr /*targetRef*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000532}
533
Steven Moreland438cce82021-04-02 18:04:08 +0000534static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
535 const binder_size_t* objects, size_t objectsCount) {
536 (void)p;
537 (void)data;
538 (void)dataSize;
539 (void)objects;
540 (void)objectsCount;
541}
542
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000543status_t RpcState::processTransactInternal(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Morelandf5174272021-05-25 00:39:28 +0000544 CommandData transactionData, sp<IBinder>&& targetRef) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000545 if (transactionData.size() < sizeof(RpcWireTransaction)) {
546 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
547 sizeof(RpcWireTransaction), transactionData.size());
548 terminate();
549 return BAD_VALUE;
550 }
551 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
552
553 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
554 // maybe add an RpcAddress 'view' if the type remains 'heavy'
555 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
556
557 status_t replyStatus = OK;
558 sp<IBinder> target;
559 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000560 if (!targetRef) {
Steven Moreland7227c8a2021-06-02 00:24:32 +0000561 replyStatus = onBinderEntering(session, addr, &target);
Steven Moreland5553ac42020-11-11 02:14:45 +0000562 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000563 target = targetRef;
564 }
565
Steven Moreland7227c8a2021-06-02 00:24:32 +0000566 if (replyStatus != OK) {
567 // do nothing
568 } else if (target == nullptr) {
Steven Morelandf5174272021-05-25 00:39:28 +0000569 // This can happen if the binder is remote in this process, and
570 // another thread has called the last decStrong on this binder.
571 // However, for local binders, it indicates a misbehaving client
572 // (any binder which is being transacted on should be holding a
573 // strong ref count), so in either case, terminating the
574 // session.
575 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
576 addr.toString().c_str());
577 terminate();
578 replyStatus = BAD_VALUE;
579 } else if (target->localBinder() == nullptr) {
580 ALOGE("Unknown binder address or non-local binder, not address %s. Terminating!",
581 addr.toString().c_str());
582 terminate();
583 replyStatus = BAD_VALUE;
584 } else if (transaction->flags & IBinder::FLAG_ONEWAY) {
585 std::lock_guard<std::mutex> _l(mNodeMutex);
586 auto it = mNodeForAddress.find(addr);
587 if (it->second.binder.promote() != target) {
588 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000589 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000590 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000591 } else if (transaction->asyncNumber != it->second.asyncNumber) {
592 // we need to process some other asynchronous transaction
593 // first
594 // TODO(b/183140903): limit enqueues/detect overfill for bad client
595 // TODO(b/183140903): detect when an object is deleted when it still has
596 // pending async transactions
597 it->second.asyncTodo.push(BinderNode::AsyncTodo{
598 .ref = target,
599 .data = std::move(transactionData),
600 .asyncNumber = transaction->asyncNumber,
601 });
602 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s", transaction->asyncNumber,
603 addr.toString().c_str());
604 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000605 }
606 }
607 }
608
Steven Moreland5553ac42020-11-11 02:14:45 +0000609 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000610 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000611
612 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000613 Parcel data;
614 // transaction->data is owned by this function. Parcel borrows this data and
615 // only holds onto it for the duration of this function call. Parcel will be
616 // deleted before the 'transactionData' object.
617 data.ipcSetDataReference(transaction->data,
618 transactionData.size() - offsetof(RpcWireTransaction, data),
619 nullptr /*object*/, 0 /*objectCount*/,
620 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000621 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000622
Steven Moreland5553ac42020-11-11 02:14:45 +0000623 if (target) {
624 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
625 } else {
626 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000627
Steven Moreland103424e2021-06-02 18:16:19 +0000628 switch (transaction->code) {
629 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
630 replyStatus = reply.writeInt32(session->getMaxThreads());
631 break;
632 }
633 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
634 // for client connections, this should always report the value
635 // originally returned from the server
636 int32_t id = session->mId.value();
637 replyStatus = reply.writeInt32(id);
638 break;
639 }
640 default: {
641 sp<RpcServer> server = session->server().promote();
642 if (server) {
643 switch (transaction->code) {
644 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
645 replyStatus = reply.writeStrongBinder(server->getRootObject());
646 break;
647 }
648 default: {
649 replyStatus = UNKNOWN_TRANSACTION;
650 }
651 }
652 } else {
653 ALOGE("Special command sent, but no server object attached.");
Steven Morelandf137de92021-04-24 01:54:26 +0000654 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000655 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000656 }
657 }
658 }
659
660 if (transaction->flags & IBinder::FLAG_ONEWAY) {
661 if (replyStatus != OK) {
662 ALOGW("Oneway call failed with error: %d", replyStatus);
663 }
664
665 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
666 addr.toString().c_str());
667
668 // Check to see if there is another asynchronous transaction to process.
669 // This behavior differs from binder behavior, since in the binder
670 // driver, asynchronous transactions will be processed after existing
671 // pending binder transactions on the queue. The downside of this is
672 // that asynchronous transactions can be drowned out by synchronous
673 // transactions. However, we have no easy way to queue these
674 // transactions after the synchronous transactions we may want to read
675 // from the wire. So, in socket binder here, we have the opposite
676 // downside: asynchronous transactions may drown out synchronous
677 // transactions.
678 {
679 std::unique_lock<std::mutex> _l(mNodeMutex);
680 auto it = mNodeForAddress.find(addr);
681 // last refcount dropped after this transaction happened
682 if (it == mNodeForAddress.end()) return OK;
683
684 // note - only updated now, instead of later, so that other threads
685 // will queue any later transactions
686
687 // TODO(b/183140903): support > 2**64 async transactions
688 // (we can do this by allowing asyncNumber to wrap, since we
689 // don't expect more than 2**64 simultaneous transactions)
690 it->second.asyncNumber++;
691
692 if (it->second.asyncTodo.size() == 0) return OK;
693 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
694 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
695 it->second.asyncNumber, addr.toString().c_str());
696
697 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000698 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000699 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000700 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
701
702 CommandData nextData = std::move(todo.data);
703 sp<IBinder> nextRef = std::move(todo.ref);
704
Steven Moreland5553ac42020-11-11 02:14:45 +0000705 it->second.asyncTodo.pop();
706 _l.unlock();
Steven Morelandf5174272021-05-25 00:39:28 +0000707 return processTransactInternal(fd, session, std::move(nextData),
708 std::move(nextRef));
Steven Moreland5553ac42020-11-11 02:14:45 +0000709 }
710 }
711 return OK;
712 }
713
714 RpcWireReply rpcReply{
715 .status = replyStatus,
716 };
717
Steven Morelanddbe71832021-05-12 23:31:00 +0000718 CommandData replyData(sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000719 if (!replyData.valid()) {
720 return NO_MEMORY;
721 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000722 memcpy(replyData.data() + 0, &rpcReply, sizeof(RpcWireReply));
723 memcpy(replyData.data() + sizeof(RpcWireReply), reply.data(), reply.dataSize());
724
725 if (replyData.size() > std::numeric_limits<uint32_t>::max()) {
726 ALOGE("Reply size too big %zu", transactionData.size());
727 terminate();
728 return BAD_VALUE;
729 }
730
731 RpcWireHeader cmdReply{
732 .command = RPC_COMMAND_REPLY,
733 .bodySize = static_cast<uint32_t>(replyData.size()),
734 };
735
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000736 if (status_t status = rpcSend(fd, "reply header", &cmdReply, sizeof(RpcWireHeader));
737 status != OK)
738 return status;
739 if (status_t status = rpcSend(fd, "reply body", replyData.data(), replyData.size());
740 status != OK)
741 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000742 return OK;
743}
744
Steven Morelandee3f4662021-05-22 01:07:33 +0000745status_t RpcState::processDecStrong(const base::unique_fd& fd, const sp<RpcSession>& session,
746 const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000747 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
748
Steven Morelanddbe71832021-05-12 23:31:00 +0000749 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000750 if (!commandData.valid()) {
751 return NO_MEMORY;
752 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000753 if (status_t status =
754 rpcRec(fd, session, "dec ref body", commandData.data(), commandData.size());
755 status != OK)
756 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000757
758 if (command.bodySize < sizeof(RpcWireAddress)) {
759 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
760 sizeof(RpcWireAddress), command.bodySize);
761 terminate();
762 return BAD_VALUE;
763 }
764 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
765
766 // TODO(b/182939933): heap allocation just for lookup
767 auto addr = RpcAddress::fromRawEmbedded(address);
768 std::unique_lock<std::mutex> _l(mNodeMutex);
769 auto it = mNodeForAddress.find(addr);
770 if (it == mNodeForAddress.end()) {
771 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000772 return OK;
773 }
774
775 sp<IBinder> target = it->second.binder.promote();
776 if (target == nullptr) {
777 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
778 addr.toString().c_str());
779 terminate();
780 return BAD_VALUE;
781 }
782
783 if (it->second.timesSent == 0) {
784 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
785 return OK;
786 }
787
788 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
789 addr.toString().c_str());
790
791 sp<IBinder> tempHold;
792
793 it->second.timesSent--;
794 if (it->second.timesSent == 0) {
795 tempHold = it->second.sentRef;
796 it->second.sentRef = nullptr;
797
798 if (it->second.timesRecd == 0) {
799 mNodeForAddress.erase(it);
800 }
801 }
802
803 _l.unlock();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000804 tempHold = nullptr; // destructor may make binder calls on this session
Steven Moreland5553ac42020-11-11 02:14:45 +0000805
806 return OK;
807}
808
809} // namespace android