blob: d40fef6f09d249499d4b9818beffc489bdf1b529 [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 Moreland5553ac42020-11-11 02:14:45 +0000210bool RpcState::rpcSend(const base::unique_fd& fd, const char* what, const void* data, size_t size) {
211 LOG_RPC_DETAIL("Sending %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
212
213 if (size > std::numeric_limits<ssize_t>::max()) {
214 ALOGE("Cannot send %s at size %zu (too big)", what, size);
215 terminate();
216 return false;
217 }
218
Steven Morelandc6ddf362021-04-02 01:13:36 +0000219 ssize_t sent = TEMP_FAILURE_RETRY(send(fd.get(), data, size, MSG_NOSIGNAL));
Steven Moreland5553ac42020-11-11 02:14:45 +0000220
221 if (sent < 0 || sent != static_cast<ssize_t>(size)) {
222 ALOGE("Failed to send %s (sent %zd of %zu bytes) on fd %d, error: %s", what, sent, size,
223 fd.get(), strerror(errno));
224
225 terminate();
226 return false;
227 }
228
229 return true;
230}
231
Steven Morelandee3f4662021-05-22 01:07:33 +0000232bool RpcState::rpcRec(const base::unique_fd& fd, const sp<RpcSession>& session, const char* what,
233 void* data, size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000234 if (size > std::numeric_limits<ssize_t>::max()) {
235 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
236 terminate();
237 return false;
238 }
239
Steven Morelandee3f4662021-05-22 01:07:33 +0000240 if (status_t status = session->mShutdownTrigger->interruptableReadFully(fd.get(), data, size);
241 status != OK) {
242 ALOGE("Failed to read %s (%zu bytes) on fd %d, error: %s", what, size, fd.get(),
243 statusToString(status).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000244 return false;
Steven Moreland5553ac42020-11-11 02:14:45 +0000245 }
246
Steven Morelandee3f4662021-05-22 01:07:33 +0000247 LOG_RPC_DETAIL("Received %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000248 return true;
249}
250
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000251sp<IBinder> RpcState::getRootObject(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000252 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000253 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000254 Parcel reply;
255
Steven Morelandf5174272021-05-25 00:39:28 +0000256 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT, data,
257 session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000258 if (status != OK) {
259 ALOGE("Error getting root object: %s", statusToString(status).c_str());
260 return nullptr;
261 }
262
263 return reply.readStrongBinder();
264}
265
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000266status_t RpcState::getMaxThreads(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000267 size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000268 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000269 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000270 Parcel reply;
271
Steven Morelandf5174272021-05-25 00:39:28 +0000272 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS,
273 data, session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000274 if (status != OK) {
275 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
276 return status;
277 }
278
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000279 int32_t maxThreads;
280 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000281 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000282 if (maxThreads <= 0) {
283 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000284 return BAD_VALUE;
285 }
286
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000287 *maxThreadsOut = maxThreads;
288 return OK;
289}
290
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000291status_t RpcState::getSessionId(const base::unique_fd& fd, const sp<RpcSession>& session,
292 int32_t* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000293 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000294 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000295 Parcel reply;
296
Steven Morelandf5174272021-05-25 00:39:28 +0000297 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_SESSION_ID,
298 data, session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000299 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000300 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000301 return status;
302 }
303
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000304 int32_t sessionId;
305 status = reply.readInt32(&sessionId);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000306 if (status != OK) return status;
307
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000308 *sessionIdOut = sessionId;
Steven Morelandf137de92021-04-24 01:54:26 +0000309 return OK;
310}
311
Steven Morelandf5174272021-05-25 00:39:28 +0000312status_t RpcState::transact(const base::unique_fd& fd, const sp<IBinder>& binder, uint32_t code,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000313 const Parcel& data, const sp<RpcSession>& session, Parcel* reply,
Steven Moreland5553ac42020-11-11 02:14:45 +0000314 uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000315 if (!data.isForRpc()) {
316 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
317 return BAD_TYPE;
318 }
319
320 if (data.objectsCount() != 0) {
321 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
322 return BAD_TYPE;
323 }
324
325 RpcAddress address = RpcAddress::zero();
326 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
327
328 return transactAddress(fd, address, code, data, session, reply, flags);
329}
330
331status_t RpcState::transactAddress(const base::unique_fd& fd, const RpcAddress& address,
332 uint32_t code, const Parcel& data, const sp<RpcSession>& session,
333 Parcel* reply, uint32_t flags) {
334 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
335 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
336
Steven Moreland5553ac42020-11-11 02:14:45 +0000337 uint64_t asyncNumber = 0;
338
339 if (!address.isZero()) {
340 std::lock_guard<std::mutex> _l(mNodeMutex);
341 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
342 auto it = mNodeForAddress.find(address);
343 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
344 address.toString().c_str());
345
346 if (flags & IBinder::FLAG_ONEWAY) {
347 asyncNumber = it->second.asyncNumber++;
348 }
349 }
350
Steven Moreland5553ac42020-11-11 02:14:45 +0000351 RpcWireTransaction transaction{
352 .address = address.viewRawEmbedded(),
353 .code = code,
354 .flags = flags,
355 .asyncNumber = asyncNumber,
356 };
357
Steven Morelanddbe71832021-05-12 23:31:00 +0000358 CommandData transactionData(sizeof(RpcWireTransaction) + data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000359 if (!transactionData.valid()) {
360 return NO_MEMORY;
361 }
362
Steven Moreland5553ac42020-11-11 02:14:45 +0000363 memcpy(transactionData.data() + 0, &transaction, sizeof(RpcWireTransaction));
364 memcpy(transactionData.data() + sizeof(RpcWireTransaction), data.data(), data.dataSize());
365
366 if (transactionData.size() > std::numeric_limits<uint32_t>::max()) {
367 ALOGE("Transaction size too big %zu", transactionData.size());
368 return BAD_VALUE;
369 }
370
371 RpcWireHeader command{
372 .command = RPC_COMMAND_TRANSACT,
373 .bodySize = static_cast<uint32_t>(transactionData.size()),
374 };
375
376 if (!rpcSend(fd, "transact header", &command, sizeof(command))) {
377 return DEAD_OBJECT;
378 }
379 if (!rpcSend(fd, "command body", transactionData.data(), transactionData.size())) {
380 return DEAD_OBJECT;
381 }
382
383 if (flags & IBinder::FLAG_ONEWAY) {
384 return OK; // do not wait for result
385 }
386
387 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
388
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000389 return waitForReply(fd, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000390}
391
Steven Moreland438cce82021-04-02 18:04:08 +0000392static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
393 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000394 (void)p;
395 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
396 (void)dataSize;
397 LOG_ALWAYS_FATAL_IF(objects != nullptr);
398 LOG_ALWAYS_FATAL_IF(objectsCount, 0);
399}
400
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000401status_t RpcState::waitForReply(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000402 Parcel* reply) {
403 RpcWireHeader command;
404 while (true) {
Steven Morelandee3f4662021-05-22 01:07:33 +0000405 if (!rpcRec(fd, session, "command header", &command, sizeof(command))) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000406 return DEAD_OBJECT;
407 }
408
409 if (command.command == RPC_COMMAND_REPLY) break;
410
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000411 status_t status = processServerCommand(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000412 if (status != OK) return status;
413 }
414
Steven Morelanddbe71832021-05-12 23:31:00 +0000415 CommandData data(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000416 if (!data.valid()) {
417 return NO_MEMORY;
418 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000419
Steven Morelandee3f4662021-05-22 01:07:33 +0000420 if (!rpcRec(fd, session, "reply body", data.data(), command.bodySize)) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000421 return DEAD_OBJECT;
422 }
423
424 if (command.bodySize < sizeof(RpcWireReply)) {
425 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
426 sizeof(RpcWireReply), command.bodySize);
427 terminate();
428 return BAD_VALUE;
429 }
Steven Morelande8393342021-05-05 23:27:53 +0000430 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000431 if (rpcReply->status != OK) return rpcReply->status;
432
Steven Morelande8393342021-05-05 23:27:53 +0000433 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000434 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000435 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000436
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000437 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000438
439 return OK;
440}
441
442status_t RpcState::sendDecStrong(const base::unique_fd& fd, const RpcAddress& addr) {
443 {
444 std::lock_guard<std::mutex> _l(mNodeMutex);
445 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
446 auto it = mNodeForAddress.find(addr);
447 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
448 addr.toString().c_str());
449 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
450 addr.toString().c_str());
451
452 it->second.timesRecd--;
453 if (it->second.timesRecd == 0 && it->second.timesSent == 0) {
454 mNodeForAddress.erase(it);
455 }
456 }
457
458 RpcWireHeader cmd = {
459 .command = RPC_COMMAND_DEC_STRONG,
460 .bodySize = sizeof(RpcWireAddress),
461 };
462 if (!rpcSend(fd, "dec ref header", &cmd, sizeof(cmd))) return DEAD_OBJECT;
463 if (!rpcSend(fd, "dec ref body", &addr.viewRawEmbedded(), sizeof(RpcWireAddress)))
464 return DEAD_OBJECT;
465 return OK;
466}
467
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000468status_t RpcState::getAndExecuteCommand(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000469 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", fd.get());
470
471 RpcWireHeader command;
Steven Morelandee3f4662021-05-22 01:07:33 +0000472 if (!rpcRec(fd, session, "command header", &command, sizeof(command))) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000473 return DEAD_OBJECT;
474 }
475
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000476 return processServerCommand(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000477}
478
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000479status_t RpcState::processServerCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000480 const RpcWireHeader& command) {
Steven Morelandd7302072021-05-15 01:32:04 +0000481 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
482 IPCThreadState::SpGuard spGuard{
483 .address = __builtin_frame_address(0),
484 .context = "processing binder RPC command",
485 };
486 const IPCThreadState::SpGuard* origGuard;
487 if (kernelBinderState != nullptr) {
488 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
489 }
490 ScopeGuard guardUnguard = [&]() {
491 if (kernelBinderState != nullptr) {
492 kernelBinderState->restoreGetCallingSpGuard(origGuard);
493 }
494 };
495
Steven Moreland5553ac42020-11-11 02:14:45 +0000496 switch (command.command) {
497 case RPC_COMMAND_TRANSACT:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000498 return processTransact(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000499 case RPC_COMMAND_DEC_STRONG:
Steven Morelandee3f4662021-05-22 01:07:33 +0000500 return processDecStrong(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000501 }
502
503 // We should always know the version of the opposing side, and since the
504 // RPC-binder-level wire protocol is not self synchronizing, we have no way
505 // to understand where the current command ends and the next one begins. We
506 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000507 // to kill us, so ending the session for misbehaving client.
508 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000509 terminate();
510 return DEAD_OBJECT;
511}
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000512status_t RpcState::processTransact(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000513 const RpcWireHeader& command) {
514 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
515
Steven Morelanddbe71832021-05-12 23:31:00 +0000516 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000517 if (!transactionData.valid()) {
518 return NO_MEMORY;
519 }
Steven Morelandee3f4662021-05-22 01:07:33 +0000520 if (!rpcRec(fd, session, "transaction body", transactionData.data(), transactionData.size())) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000521 return DEAD_OBJECT;
522 }
523
Steven Morelandf5174272021-05-25 00:39:28 +0000524 return processTransactInternal(fd, session, std::move(transactionData), nullptr /*targetRef*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000525}
526
Steven Moreland438cce82021-04-02 18:04:08 +0000527static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
528 const binder_size_t* objects, size_t objectsCount) {
529 (void)p;
530 (void)data;
531 (void)dataSize;
532 (void)objects;
533 (void)objectsCount;
534}
535
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000536status_t RpcState::processTransactInternal(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Morelandf5174272021-05-25 00:39:28 +0000537 CommandData transactionData, sp<IBinder>&& targetRef) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000538 if (transactionData.size() < sizeof(RpcWireTransaction)) {
539 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
540 sizeof(RpcWireTransaction), transactionData.size());
541 terminate();
542 return BAD_VALUE;
543 }
544 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
545
546 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
547 // maybe add an RpcAddress 'view' if the type remains 'heavy'
548 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
549
550 status_t replyStatus = OK;
551 sp<IBinder> target;
552 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000553 if (!targetRef) {
554 target = onBinderEntering(session, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000555 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000556 target = targetRef;
557 }
558
559 if (target == nullptr) {
560 // This can happen if the binder is remote in this process, and
561 // another thread has called the last decStrong on this binder.
562 // However, for local binders, it indicates a misbehaving client
563 // (any binder which is being transacted on should be holding a
564 // strong ref count), so in either case, terminating the
565 // session.
566 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
567 addr.toString().c_str());
568 terminate();
569 replyStatus = BAD_VALUE;
570 } else if (target->localBinder() == nullptr) {
571 ALOGE("Unknown binder address or non-local binder, not address %s. Terminating!",
572 addr.toString().c_str());
573 terminate();
574 replyStatus = BAD_VALUE;
575 } else if (transaction->flags & IBinder::FLAG_ONEWAY) {
576 std::lock_guard<std::mutex> _l(mNodeMutex);
577 auto it = mNodeForAddress.find(addr);
578 if (it->second.binder.promote() != target) {
579 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000580 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000581 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000582 } else if (transaction->asyncNumber != it->second.asyncNumber) {
583 // we need to process some other asynchronous transaction
584 // first
585 // TODO(b/183140903): limit enqueues/detect overfill for bad client
586 // TODO(b/183140903): detect when an object is deleted when it still has
587 // pending async transactions
588 it->second.asyncTodo.push(BinderNode::AsyncTodo{
589 .ref = target,
590 .data = std::move(transactionData),
591 .asyncNumber = transaction->asyncNumber,
592 });
593 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s", transaction->asyncNumber,
594 addr.toString().c_str());
595 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000596 }
597 }
598 }
599
Steven Moreland5553ac42020-11-11 02:14:45 +0000600 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000601 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000602
603 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000604 Parcel data;
605 // transaction->data is owned by this function. Parcel borrows this data and
606 // only holds onto it for the duration of this function call. Parcel will be
607 // deleted before the 'transactionData' object.
608 data.ipcSetDataReference(transaction->data,
609 transactionData.size() - offsetof(RpcWireTransaction, data),
610 nullptr /*object*/, 0 /*objectCount*/,
611 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000612 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000613
Steven Moreland5553ac42020-11-11 02:14:45 +0000614 if (target) {
615 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
616 } else {
617 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000618
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000619 sp<RpcServer> server = session->server().promote();
Steven Morelandf137de92021-04-24 01:54:26 +0000620 if (server) {
621 // special case for 'zero' address (special server commands)
622 switch (transaction->code) {
623 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
624 replyStatus = reply.writeStrongBinder(server->getRootObject());
625 break;
626 }
627 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
628 replyStatus = reply.writeInt32(server->getMaxThreads());
629 break;
630 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000631 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
632 // only sessions w/ services can be the source of a
633 // session ID (so still guarded by non-null server)
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000634 //
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000635 // sessions associated with servers must have an ID
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000636 // (hence abort)
Steven Morelandee3f4662021-05-22 01:07:33 +0000637 int32_t id = session->mId.value();
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000638 replyStatus = reply.writeInt32(id);
639 break;
640 }
Steven Morelandf137de92021-04-24 01:54:26 +0000641 default: {
642 replyStatus = UNKNOWN_TRANSACTION;
643 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000644 }
Steven Morelandf137de92021-04-24 01:54:26 +0000645 } else {
646 ALOGE("Special command sent, but no server object attached.");
Steven Moreland5553ac42020-11-11 02:14:45 +0000647 }
648 }
649 }
650
651 if (transaction->flags & IBinder::FLAG_ONEWAY) {
652 if (replyStatus != OK) {
653 ALOGW("Oneway call failed with error: %d", replyStatus);
654 }
655
656 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
657 addr.toString().c_str());
658
659 // Check to see if there is another asynchronous transaction to process.
660 // This behavior differs from binder behavior, since in the binder
661 // driver, asynchronous transactions will be processed after existing
662 // pending binder transactions on the queue. The downside of this is
663 // that asynchronous transactions can be drowned out by synchronous
664 // transactions. However, we have no easy way to queue these
665 // transactions after the synchronous transactions we may want to read
666 // from the wire. So, in socket binder here, we have the opposite
667 // downside: asynchronous transactions may drown out synchronous
668 // transactions.
669 {
670 std::unique_lock<std::mutex> _l(mNodeMutex);
671 auto it = mNodeForAddress.find(addr);
672 // last refcount dropped after this transaction happened
673 if (it == mNodeForAddress.end()) return OK;
674
675 // note - only updated now, instead of later, so that other threads
676 // will queue any later transactions
677
678 // TODO(b/183140903): support > 2**64 async transactions
679 // (we can do this by allowing asyncNumber to wrap, since we
680 // don't expect more than 2**64 simultaneous transactions)
681 it->second.asyncNumber++;
682
683 if (it->second.asyncTodo.size() == 0) return OK;
684 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
685 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
686 it->second.asyncNumber, addr.toString().c_str());
687
688 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000689 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000690 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000691 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
692
693 CommandData nextData = std::move(todo.data);
694 sp<IBinder> nextRef = std::move(todo.ref);
695
Steven Moreland5553ac42020-11-11 02:14:45 +0000696 it->second.asyncTodo.pop();
697 _l.unlock();
Steven Morelandf5174272021-05-25 00:39:28 +0000698 return processTransactInternal(fd, session, std::move(nextData),
699 std::move(nextRef));
Steven Moreland5553ac42020-11-11 02:14:45 +0000700 }
701 }
702 return OK;
703 }
704
705 RpcWireReply rpcReply{
706 .status = replyStatus,
707 };
708
Steven Morelanddbe71832021-05-12 23:31:00 +0000709 CommandData replyData(sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000710 if (!replyData.valid()) {
711 return NO_MEMORY;
712 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000713 memcpy(replyData.data() + 0, &rpcReply, sizeof(RpcWireReply));
714 memcpy(replyData.data() + sizeof(RpcWireReply), reply.data(), reply.dataSize());
715
716 if (replyData.size() > std::numeric_limits<uint32_t>::max()) {
717 ALOGE("Reply size too big %zu", transactionData.size());
718 terminate();
719 return BAD_VALUE;
720 }
721
722 RpcWireHeader cmdReply{
723 .command = RPC_COMMAND_REPLY,
724 .bodySize = static_cast<uint32_t>(replyData.size()),
725 };
726
727 if (!rpcSend(fd, "reply header", &cmdReply, sizeof(RpcWireHeader))) {
728 return DEAD_OBJECT;
729 }
730 if (!rpcSend(fd, "reply body", replyData.data(), replyData.size())) {
731 return DEAD_OBJECT;
732 }
733 return OK;
734}
735
Steven Morelandee3f4662021-05-22 01:07:33 +0000736status_t RpcState::processDecStrong(const base::unique_fd& fd, const sp<RpcSession>& session,
737 const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000738 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
739
Steven Morelanddbe71832021-05-12 23:31:00 +0000740 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000741 if (!commandData.valid()) {
742 return NO_MEMORY;
743 }
Steven Morelandee3f4662021-05-22 01:07:33 +0000744 if (!rpcRec(fd, session, "dec ref body", commandData.data(), commandData.size())) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000745 return DEAD_OBJECT;
746 }
747
748 if (command.bodySize < sizeof(RpcWireAddress)) {
749 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
750 sizeof(RpcWireAddress), command.bodySize);
751 terminate();
752 return BAD_VALUE;
753 }
754 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
755
756 // TODO(b/182939933): heap allocation just for lookup
757 auto addr = RpcAddress::fromRawEmbedded(address);
758 std::unique_lock<std::mutex> _l(mNodeMutex);
759 auto it = mNodeForAddress.find(addr);
760 if (it == mNodeForAddress.end()) {
761 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000762 return OK;
763 }
764
765 sp<IBinder> target = it->second.binder.promote();
766 if (target == nullptr) {
767 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
768 addr.toString().c_str());
769 terminate();
770 return BAD_VALUE;
771 }
772
773 if (it->second.timesSent == 0) {
774 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
775 return OK;
776 }
777
778 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
779 addr.toString().c_str());
780
781 sp<IBinder> tempHold;
782
783 it->second.timesSent--;
784 if (it->second.timesSent == 0) {
785 tempHold = it->second.sentRef;
786 it->second.sentRef = nullptr;
787
788 if (it->second.timesRecd == 0) {
789 mNodeForAddress.erase(it);
790 }
791 }
792
793 _l.unlock();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000794 tempHold = nullptr; // destructor may make binder calls on this session
Steven Moreland5553ac42020-11-11 02:14:45 +0000795
796 return OK;
797}
798
799} // namespace android