blob: 2f6b1b3ac45aba3b2938afb7a19bcbb765d0ccb6 [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);
64
65 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
66 // in RpcState
67 for (auto& [addr, node] : mNodeForAddress) {
68 if (binder == node.binder) {
69 if (isRpc) {
70 const RpcAddress& actualAddr =
71 binder->remoteBinder()->getPrivateAccessorForId().rpcAddress();
72 // TODO(b/182939933): this is only checking integrity of data structure
73 // a different data structure doesn't need this
74 LOG_ALWAYS_FATAL_IF(addr < actualAddr, "Address mismatch");
75 LOG_ALWAYS_FATAL_IF(actualAddr < addr, "Address mismatch");
76 }
77 node.timesSent++;
78 node.sentRef = binder; // might already be set
79 *outAddress = addr;
80 return OK;
81 }
82 }
83 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
84
85 auto&& [it, inserted] = mNodeForAddress.insert({RpcAddress::unique(),
86 BinderNode{
87 .binder = binder,
88 .timesSent = 1,
89 .sentRef = binder,
90 }});
91 // TODO(b/182939933): better organization could avoid needing this log
92 LOG_ALWAYS_FATAL_IF(!inserted);
93
94 *outAddress = it->first;
95 return OK;
96}
97
Steven Morelandbdb53ab2021-05-05 17:57:41 +000098sp<IBinder> RpcState::onBinderEntering(const sp<RpcSession>& session, const RpcAddress& address) {
Steven Moreland5553ac42020-11-11 02:14:45 +000099 std::unique_lock<std::mutex> _l(mNodeMutex);
100
101 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
102 sp<IBinder> binder = it->second.binder.promote();
103
104 // implicitly have strong RPC refcount, since we received this binder
105 it->second.timesRecd++;
106
107 _l.unlock();
108
109 // We have timesRecd RPC refcounts, but we only need to hold on to one
110 // when we keep the object. All additional dec strongs are sent
111 // immediately, we wait to send the last one in BpBinder::onLastDecStrong.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000112 (void)session->sendDecStrong(address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000113
114 return binder;
115 }
116
117 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
118 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
119
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000120 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000121 // device global binders in the RPC world).
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000122 sp<IBinder> binder = BpBinder::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000123 it->second.binder = binder;
124 it->second.timesRecd = 1;
125 return binder;
126}
127
128size_t RpcState::countBinders() {
129 std::lock_guard<std::mutex> _l(mNodeMutex);
130 return mNodeForAddress.size();
131}
132
133void RpcState::dump() {
134 std::lock_guard<std::mutex> _l(mNodeMutex);
135 ALOGE("DUMP OF RpcState %p", this);
136 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
137 for (const auto& [address, node] : mNodeForAddress) {
138 sp<IBinder> binder = node.binder.promote();
139
140 const char* desc;
141 if (binder) {
142 if (binder->remoteBinder()) {
143 if (binder->remoteBinder()->isRpcBinder()) {
144 desc = "(rpc binder proxy)";
145 } else {
146 desc = "(binder proxy)";
147 }
148 } else {
149 desc = "(local binder)";
150 }
151 } else {
152 desc = "(null)";
153 }
154
155 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a:%s type:%s",
156 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address.toString().c_str(),
157 desc);
158 }
159 ALOGE("END DUMP OF RpcState");
160}
161
162void RpcState::terminate() {
163 if (SHOULD_LOG_RPC_DETAIL) {
164 ALOGE("RpcState::terminate()");
165 dump();
166 }
167
168 // if the destructor of a binder object makes another RPC call, then calling
169 // decStrong could deadlock. So, we must hold onto these binders until
170 // mNodeMutex is no longer taken.
171 std::vector<sp<IBinder>> tempHoldBinder;
172
173 {
174 std::lock_guard<std::mutex> _l(mNodeMutex);
175 mTerminated = true;
176 for (auto& [address, node] : mNodeForAddress) {
177 sp<IBinder> binder = node.binder.promote();
178 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
179
180 if (node.sentRef != nullptr) {
181 tempHoldBinder.push_back(node.sentRef);
182 }
183 }
184
185 mNodeForAddress.clear();
186 }
187}
188
Steven Morelanddbe71832021-05-12 23:31:00 +0000189RpcState::CommandData::CommandData(size_t size) : mSize(size) {
190 // The maximum size for regular binder is 1MB for all concurrent
191 // transactions. A very small proportion of transactions are even
192 // larger than a page, but we need to avoid allocating too much
193 // data on behalf of an arbitrary client, or we could risk being in
194 // a position where a single additional allocation could run out of
195 // memory.
196 //
197 // Note, this limit may not reflect the total amount of data allocated for a
198 // transaction (in some cases, additional fixed size amounts are added),
199 // though for rough consistency, we should avoid cases where this data type
200 // is used for multiple dynamic allocations for a single transaction.
201 constexpr size_t kMaxTransactionAllocation = 100 * 1000;
202 if (size == 0) return;
203 if (size > kMaxTransactionAllocation) {
204 ALOGW("Transaction requested too much data allocation %zu", size);
205 return;
206 }
207 mData.reset(new (std::nothrow) uint8_t[size]);
208}
209
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000210status_t RpcState::rpcSend(const base::unique_fd& fd, const char* what, const void* data,
211 size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000212 LOG_RPC_DETAIL("Sending %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
213
214 if (size > std::numeric_limits<ssize_t>::max()) {
215 ALOGE("Cannot send %s at size %zu (too big)", what, size);
216 terminate();
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000217 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000218 }
219
Steven Morelandc6ddf362021-04-02 01:13:36 +0000220 ssize_t sent = TEMP_FAILURE_RETRY(send(fd.get(), data, size, MSG_NOSIGNAL));
Steven Moreland5553ac42020-11-11 02:14:45 +0000221
222 if (sent < 0 || sent != static_cast<ssize_t>(size)) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000223 int savedErrno = errno;
Steven Morelandc12c9d92021-05-26 18:44:11 +0000224 LOG_RPC_DETAIL("Failed to send %s (sent %zd of %zu bytes) on fd %d, error: %s", what, sent,
225 size, fd.get(), strerror(savedErrno));
Steven Moreland5553ac42020-11-11 02:14:45 +0000226
227 terminate();
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000228 return -savedErrno;
Steven Moreland5553ac42020-11-11 02:14:45 +0000229 }
230
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000231 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000232}
233
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000234status_t RpcState::rpcRec(const base::unique_fd& fd, const sp<RpcSession>& session,
235 const char* what, void* data, size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000236 if (size > std::numeric_limits<ssize_t>::max()) {
237 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
238 terminate();
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000239 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000240 }
241
Steven Morelandee3f4662021-05-22 01:07:33 +0000242 if (status_t status = session->mShutdownTrigger->interruptableReadFully(fd.get(), data, size);
243 status != OK) {
Steven Morelandc12c9d92021-05-26 18:44:11 +0000244 LOG_RPC_DETAIL("Failed to read %s (%zu bytes) on fd %d, error: %s", what, size, fd.get(),
245 statusToString(status).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000246 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000247 }
248
Steven Morelandee3f4662021-05-22 01:07:33 +0000249 LOG_RPC_DETAIL("Received %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000250 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000251}
252
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000253sp<IBinder> RpcState::getRootObject(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000254 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000255 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000256 Parcel reply;
257
Steven Morelandf5174272021-05-25 00:39:28 +0000258 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT, data,
259 session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000260 if (status != OK) {
261 ALOGE("Error getting root object: %s", statusToString(status).c_str());
262 return nullptr;
263 }
264
265 return reply.readStrongBinder();
266}
267
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000268status_t RpcState::getMaxThreads(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000269 size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000270 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000271 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000272 Parcel reply;
273
Steven Morelandf5174272021-05-25 00:39:28 +0000274 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS,
275 data, session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000276 if (status != OK) {
277 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
278 return status;
279 }
280
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000281 int32_t maxThreads;
282 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000283 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000284 if (maxThreads <= 0) {
285 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000286 return BAD_VALUE;
287 }
288
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000289 *maxThreadsOut = maxThreads;
290 return OK;
291}
292
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000293status_t RpcState::getSessionId(const base::unique_fd& fd, const sp<RpcSession>& session,
294 int32_t* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000295 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000296 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000297 Parcel reply;
298
Steven Morelandf5174272021-05-25 00:39:28 +0000299 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_SESSION_ID,
300 data, session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000301 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000302 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000303 return status;
304 }
305
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000306 int32_t sessionId;
307 status = reply.readInt32(&sessionId);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000308 if (status != OK) return status;
309
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000310 *sessionIdOut = sessionId;
Steven Morelandf137de92021-04-24 01:54:26 +0000311 return OK;
312}
313
Steven Morelandf5174272021-05-25 00:39:28 +0000314status_t RpcState::transact(const base::unique_fd& fd, const sp<IBinder>& binder, uint32_t code,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000315 const Parcel& data, const sp<RpcSession>& session, Parcel* reply,
Steven Moreland5553ac42020-11-11 02:14:45 +0000316 uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000317 if (!data.isForRpc()) {
318 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
319 return BAD_TYPE;
320 }
321
322 if (data.objectsCount() != 0) {
323 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
324 return BAD_TYPE;
325 }
326
327 RpcAddress address = RpcAddress::zero();
328 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
329
330 return transactAddress(fd, address, code, data, session, reply, flags);
331}
332
333status_t RpcState::transactAddress(const base::unique_fd& fd, const RpcAddress& address,
334 uint32_t code, const Parcel& data, const sp<RpcSession>& session,
335 Parcel* reply, uint32_t flags) {
336 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
337 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
338
Steven Moreland5553ac42020-11-11 02:14:45 +0000339 uint64_t asyncNumber = 0;
340
341 if (!address.isZero()) {
342 std::lock_guard<std::mutex> _l(mNodeMutex);
343 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
344 auto it = mNodeForAddress.find(address);
345 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
346 address.toString().c_str());
347
348 if (flags & IBinder::FLAG_ONEWAY) {
349 asyncNumber = it->second.asyncNumber++;
350 }
351 }
352
Steven Moreland5553ac42020-11-11 02:14:45 +0000353 RpcWireTransaction transaction{
354 .address = address.viewRawEmbedded(),
355 .code = code,
356 .flags = flags,
357 .asyncNumber = asyncNumber,
358 };
359
Steven Morelanddbe71832021-05-12 23:31:00 +0000360 CommandData transactionData(sizeof(RpcWireTransaction) + data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000361 if (!transactionData.valid()) {
362 return NO_MEMORY;
363 }
364
Steven Moreland5553ac42020-11-11 02:14:45 +0000365 memcpy(transactionData.data() + 0, &transaction, sizeof(RpcWireTransaction));
366 memcpy(transactionData.data() + sizeof(RpcWireTransaction), data.data(), data.dataSize());
367
368 if (transactionData.size() > std::numeric_limits<uint32_t>::max()) {
369 ALOGE("Transaction size too big %zu", transactionData.size());
370 return BAD_VALUE;
371 }
372
373 RpcWireHeader command{
374 .command = RPC_COMMAND_TRANSACT,
375 .bodySize = static_cast<uint32_t>(transactionData.size()),
376 };
377
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000378 if (status_t status = rpcSend(fd, "transact header", &command, sizeof(command)); status != OK)
379 return status;
380 if (status_t status =
381 rpcSend(fd, "command body", transactionData.data(), transactionData.size());
382 status != OK)
383 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000384
385 if (flags & IBinder::FLAG_ONEWAY) {
Steven Moreland659416d2021-05-11 00:47:50 +0000386 LOG_RPC_DETAIL("Oneway command, so no longer waiting on %d", fd.get());
Steven Moreland5553ac42020-11-11 02:14:45 +0000387 return OK; // do not wait for result
388 }
389
390 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
391
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000392 return waitForReply(fd, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000393}
394
Steven Moreland438cce82021-04-02 18:04:08 +0000395static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
396 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000397 (void)p;
398 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
399 (void)dataSize;
400 LOG_ALWAYS_FATAL_IF(objects != nullptr);
401 LOG_ALWAYS_FATAL_IF(objectsCount, 0);
402}
403
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000404status_t RpcState::waitForReply(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000405 Parcel* reply) {
406 RpcWireHeader command;
407 while (true) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000408 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
409 status != OK)
410 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000411
412 if (command.command == RPC_COMMAND_REPLY) break;
413
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000414 if (status_t status = processServerCommand(fd, session, command); status != OK)
415 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000416 }
417
Steven Morelanddbe71832021-05-12 23:31:00 +0000418 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000419 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000420
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000421 if (status_t status = rpcRec(fd, session, "reply body", data.data(), command.bodySize);
422 status != OK)
423 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000424
425 if (command.bodySize < sizeof(RpcWireReply)) {
426 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
427 sizeof(RpcWireReply), command.bodySize);
428 terminate();
429 return BAD_VALUE;
430 }
Steven Morelande8393342021-05-05 23:27:53 +0000431 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000432 if (rpcReply->status != OK) return rpcReply->status;
433
Steven Morelande8393342021-05-05 23:27:53 +0000434 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000435 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000436 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000437
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000438 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000439
440 return OK;
441}
442
443status_t RpcState::sendDecStrong(const base::unique_fd& fd, const RpcAddress& addr) {
444 {
445 std::lock_guard<std::mutex> _l(mNodeMutex);
446 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
447 auto it = mNodeForAddress.find(addr);
448 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
449 addr.toString().c_str());
450 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
451 addr.toString().c_str());
452
453 it->second.timesRecd--;
454 if (it->second.timesRecd == 0 && it->second.timesSent == 0) {
455 mNodeForAddress.erase(it);
456 }
457 }
458
459 RpcWireHeader cmd = {
460 .command = RPC_COMMAND_DEC_STRONG,
461 .bodySize = sizeof(RpcWireAddress),
462 };
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000463 if (status_t status = rpcSend(fd, "dec ref header", &cmd, sizeof(cmd)); status != OK)
464 return status;
465 if (status_t status =
466 rpcSend(fd, "dec ref body", &addr.viewRawEmbedded(), sizeof(RpcWireAddress));
467 status != OK)
468 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000469 return OK;
470}
471
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000472status_t RpcState::getAndExecuteCommand(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000473 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", fd.get());
474
475 RpcWireHeader command;
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000476 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
477 status != OK)
478 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000479
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000480 return processServerCommand(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000481}
482
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000483status_t RpcState::processServerCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000484 const RpcWireHeader& command) {
Steven Morelandd7302072021-05-15 01:32:04 +0000485 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
486 IPCThreadState::SpGuard spGuard{
487 .address = __builtin_frame_address(0),
488 .context = "processing binder RPC command",
489 };
490 const IPCThreadState::SpGuard* origGuard;
491 if (kernelBinderState != nullptr) {
492 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
493 }
494 ScopeGuard guardUnguard = [&]() {
495 if (kernelBinderState != nullptr) {
496 kernelBinderState->restoreGetCallingSpGuard(origGuard);
497 }
498 };
499
Steven Moreland5553ac42020-11-11 02:14:45 +0000500 switch (command.command) {
501 case RPC_COMMAND_TRANSACT:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000502 return processTransact(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000503 case RPC_COMMAND_DEC_STRONG:
Steven Morelandee3f4662021-05-22 01:07:33 +0000504 return processDecStrong(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000505 }
506
507 // We should always know the version of the opposing side, and since the
508 // RPC-binder-level wire protocol is not self synchronizing, we have no way
509 // to understand where the current command ends and the next one begins. We
510 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000511 // to kill us, so ending the session for misbehaving client.
512 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000513 terminate();
514 return DEAD_OBJECT;
515}
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000516status_t RpcState::processTransact(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000517 const RpcWireHeader& command) {
518 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
519
Steven Morelanddbe71832021-05-12 23:31:00 +0000520 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000521 if (!transactionData.valid()) {
522 return NO_MEMORY;
523 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000524 if (status_t status = rpcRec(fd, session, "transaction body", transactionData.data(),
525 transactionData.size());
526 status != OK)
527 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000528
Steven Morelandf5174272021-05-25 00:39:28 +0000529 return processTransactInternal(fd, session, std::move(transactionData), nullptr /*targetRef*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000530}
531
Steven Moreland438cce82021-04-02 18:04:08 +0000532static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
533 const binder_size_t* objects, size_t objectsCount) {
534 (void)p;
535 (void)data;
536 (void)dataSize;
537 (void)objects;
538 (void)objectsCount;
539}
540
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000541status_t RpcState::processTransactInternal(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Morelandf5174272021-05-25 00:39:28 +0000542 CommandData transactionData, sp<IBinder>&& targetRef) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000543 if (transactionData.size() < sizeof(RpcWireTransaction)) {
544 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
545 sizeof(RpcWireTransaction), transactionData.size());
546 terminate();
547 return BAD_VALUE;
548 }
549 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
550
551 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
552 // maybe add an RpcAddress 'view' if the type remains 'heavy'
553 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
554
555 status_t replyStatus = OK;
556 sp<IBinder> target;
557 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000558 if (!targetRef) {
559 target = onBinderEntering(session, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000560 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000561 target = targetRef;
562 }
563
564 if (target == nullptr) {
565 // This can happen if the binder is remote in this process, and
566 // another thread has called the last decStrong on this binder.
567 // However, for local binders, it indicates a misbehaving client
568 // (any binder which is being transacted on should be holding a
569 // strong ref count), so in either case, terminating the
570 // session.
571 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
572 addr.toString().c_str());
573 terminate();
574 replyStatus = BAD_VALUE;
575 } else if (target->localBinder() == nullptr) {
576 ALOGE("Unknown binder address or non-local binder, not address %s. Terminating!",
577 addr.toString().c_str());
578 terminate();
579 replyStatus = BAD_VALUE;
580 } else if (transaction->flags & IBinder::FLAG_ONEWAY) {
581 std::lock_guard<std::mutex> _l(mNodeMutex);
582 auto it = mNodeForAddress.find(addr);
583 if (it->second.binder.promote() != target) {
584 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000585 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000586 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000587 } else if (transaction->asyncNumber != it->second.asyncNumber) {
588 // we need to process some other asynchronous transaction
589 // first
590 // TODO(b/183140903): limit enqueues/detect overfill for bad client
591 // TODO(b/183140903): detect when an object is deleted when it still has
592 // pending async transactions
593 it->second.asyncTodo.push(BinderNode::AsyncTodo{
594 .ref = target,
595 .data = std::move(transactionData),
596 .asyncNumber = transaction->asyncNumber,
597 });
598 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s", transaction->asyncNumber,
599 addr.toString().c_str());
600 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000601 }
602 }
603 }
604
Steven Moreland5553ac42020-11-11 02:14:45 +0000605 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000606 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000607
608 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000609 Parcel data;
610 // transaction->data is owned by this function. Parcel borrows this data and
611 // only holds onto it for the duration of this function call. Parcel will be
612 // deleted before the 'transactionData' object.
613 data.ipcSetDataReference(transaction->data,
614 transactionData.size() - offsetof(RpcWireTransaction, data),
615 nullptr /*object*/, 0 /*objectCount*/,
616 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000617 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000618
Steven Moreland5553ac42020-11-11 02:14:45 +0000619 if (target) {
620 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
621 } else {
622 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000623
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000624 sp<RpcServer> server = session->server().promote();
Steven Morelandf137de92021-04-24 01:54:26 +0000625 if (server) {
626 // special case for 'zero' address (special server commands)
627 switch (transaction->code) {
628 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
629 replyStatus = reply.writeStrongBinder(server->getRootObject());
630 break;
631 }
632 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
633 replyStatus = reply.writeInt32(server->getMaxThreads());
634 break;
635 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000636 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
637 // only sessions w/ services can be the source of a
638 // session ID (so still guarded by non-null server)
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000639 //
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000640 // sessions associated with servers must have an ID
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000641 // (hence abort)
Steven Morelandee3f4662021-05-22 01:07:33 +0000642 int32_t id = session->mId.value();
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000643 replyStatus = reply.writeInt32(id);
644 break;
645 }
Steven Morelandf137de92021-04-24 01:54:26 +0000646 default: {
647 replyStatus = UNKNOWN_TRANSACTION;
648 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000649 }
Steven Morelandf137de92021-04-24 01:54:26 +0000650 } else {
651 ALOGE("Special command sent, but no server object attached.");
Steven Moreland5553ac42020-11-11 02:14:45 +0000652 }
653 }
654 }
655
656 if (transaction->flags & IBinder::FLAG_ONEWAY) {
657 if (replyStatus != OK) {
658 ALOGW("Oneway call failed with error: %d", replyStatus);
659 }
660
661 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
662 addr.toString().c_str());
663
664 // Check to see if there is another asynchronous transaction to process.
665 // This behavior differs from binder behavior, since in the binder
666 // driver, asynchronous transactions will be processed after existing
667 // pending binder transactions on the queue. The downside of this is
668 // that asynchronous transactions can be drowned out by synchronous
669 // transactions. However, we have no easy way to queue these
670 // transactions after the synchronous transactions we may want to read
671 // from the wire. So, in socket binder here, we have the opposite
672 // downside: asynchronous transactions may drown out synchronous
673 // transactions.
674 {
675 std::unique_lock<std::mutex> _l(mNodeMutex);
676 auto it = mNodeForAddress.find(addr);
677 // last refcount dropped after this transaction happened
678 if (it == mNodeForAddress.end()) return OK;
679
680 // note - only updated now, instead of later, so that other threads
681 // will queue any later transactions
682
683 // TODO(b/183140903): support > 2**64 async transactions
684 // (we can do this by allowing asyncNumber to wrap, since we
685 // don't expect more than 2**64 simultaneous transactions)
686 it->second.asyncNumber++;
687
688 if (it->second.asyncTodo.size() == 0) return OK;
689 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
690 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
691 it->second.asyncNumber, addr.toString().c_str());
692
693 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000694 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000695 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000696 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
697
698 CommandData nextData = std::move(todo.data);
699 sp<IBinder> nextRef = std::move(todo.ref);
700
Steven Moreland5553ac42020-11-11 02:14:45 +0000701 it->second.asyncTodo.pop();
702 _l.unlock();
Steven Morelandf5174272021-05-25 00:39:28 +0000703 return processTransactInternal(fd, session, std::move(nextData),
704 std::move(nextRef));
Steven Moreland5553ac42020-11-11 02:14:45 +0000705 }
706 }
707 return OK;
708 }
709
710 RpcWireReply rpcReply{
711 .status = replyStatus,
712 };
713
Steven Morelanddbe71832021-05-12 23:31:00 +0000714 CommandData replyData(sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000715 if (!replyData.valid()) {
716 return NO_MEMORY;
717 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000718 memcpy(replyData.data() + 0, &rpcReply, sizeof(RpcWireReply));
719 memcpy(replyData.data() + sizeof(RpcWireReply), reply.data(), reply.dataSize());
720
721 if (replyData.size() > std::numeric_limits<uint32_t>::max()) {
722 ALOGE("Reply size too big %zu", transactionData.size());
723 terminate();
724 return BAD_VALUE;
725 }
726
727 RpcWireHeader cmdReply{
728 .command = RPC_COMMAND_REPLY,
729 .bodySize = static_cast<uint32_t>(replyData.size()),
730 };
731
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000732 if (status_t status = rpcSend(fd, "reply header", &cmdReply, sizeof(RpcWireHeader));
733 status != OK)
734 return status;
735 if (status_t status = rpcSend(fd, "reply body", replyData.data(), replyData.size());
736 status != OK)
737 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000738 return OK;
739}
740
Steven Morelandee3f4662021-05-22 01:07:33 +0000741status_t RpcState::processDecStrong(const base::unique_fd& fd, const sp<RpcSession>& session,
742 const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000743 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
744
Steven Morelanddbe71832021-05-12 23:31:00 +0000745 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000746 if (!commandData.valid()) {
747 return NO_MEMORY;
748 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000749 if (status_t status =
750 rpcRec(fd, session, "dec ref body", commandData.data(), commandData.size());
751 status != OK)
752 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000753
754 if (command.bodySize < sizeof(RpcWireAddress)) {
755 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
756 sizeof(RpcWireAddress), command.bodySize);
757 terminate();
758 return BAD_VALUE;
759 }
760 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
761
762 // TODO(b/182939933): heap allocation just for lookup
763 auto addr = RpcAddress::fromRawEmbedded(address);
764 std::unique_lock<std::mutex> _l(mNodeMutex);
765 auto it = mNodeForAddress.find(addr);
766 if (it == mNodeForAddress.end()) {
767 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000768 return OK;
769 }
770
771 sp<IBinder> target = it->second.binder.promote();
772 if (target == nullptr) {
773 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
774 addr.toString().c_str());
775 terminate();
776 return BAD_VALUE;
777 }
778
779 if (it->second.timesSent == 0) {
780 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
781 return OK;
782 }
783
784 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
785 addr.toString().c_str());
786
787 sp<IBinder> tempHold;
788
789 it->second.timesSent--;
790 if (it->second.timesSent == 0) {
791 tempHold = it->second.sentRef;
792 it->second.sentRef = nullptr;
793
794 if (it->second.timesRecd == 0) {
795 mNodeForAddress.erase(it);
796 }
797 }
798
799 _l.unlock();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000800 tempHold = nullptr; // destructor may make binder calls on this session
Steven Moreland5553ac42020-11-11 02:14:45 +0000801
802 return OK;
803}
804
805} // namespace android