blob: 19dea7e6072ea75e7f68f554a36bae3382ffe212 [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
21#include <binder/BpBinder.h>
22#include <binder/RpcServer.h>
23
24#include "Debug.h"
25#include "RpcWireFormat.h"
26
27#include <inttypes.h>
28
29namespace android {
30
31RpcState::RpcState() {}
32RpcState::~RpcState() {}
33
34status_t RpcState::onBinderLeaving(const sp<RpcConnection>& connection, const sp<IBinder>& binder,
35 RpcAddress* outAddress) {
36 bool isRemote = binder->remoteBinder();
37 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
38
39 if (isRpc && binder->remoteBinder()->getPrivateAccessorForId().rpcConnection() != connection) {
40 // We need to be able to send instructions over the socket for how to
41 // connect to a different server, and we also need to let the host
42 // process know that this is happening.
Yifan Hong85602162021-04-14 17:36:36 -070043 ALOGE("Cannot send binder from unrelated binder RPC connection.");
Steven Moreland5553ac42020-11-11 02:14:45 +000044 return INVALID_OPERATION;
45 }
46
47 if (isRemote && !isRpc) {
48 // Without additional work, this would have the effect of using this
49 // process to proxy calls from the socket over to the other process, and
50 // it would make those calls look like they come from us (not over the
51 // sockets). In order to make this work transparently like binder, we
52 // would instead need to send instructions over the socket for how to
53 // connect to the host process, and we also need to let the host process
54 // know this was happening.
55 ALOGE("Cannot send binder proxy %p over sockets", binder.get());
56 return INVALID_OPERATION;
57 }
58
59 std::lock_guard<std::mutex> _l(mNodeMutex);
60
61 // TODO(b/182939933): maybe move address out of BpBinder, and keep binder->address map
62 // in RpcState
63 for (auto& [addr, node] : mNodeForAddress) {
64 if (binder == node.binder) {
65 if (isRpc) {
66 const RpcAddress& actualAddr =
67 binder->remoteBinder()->getPrivateAccessorForId().rpcAddress();
68 // TODO(b/182939933): this is only checking integrity of data structure
69 // a different data structure doesn't need this
70 LOG_ALWAYS_FATAL_IF(addr < actualAddr, "Address mismatch");
71 LOG_ALWAYS_FATAL_IF(actualAddr < addr, "Address mismatch");
72 }
73 node.timesSent++;
74 node.sentRef = binder; // might already be set
75 *outAddress = addr;
76 return OK;
77 }
78 }
79 LOG_ALWAYS_FATAL_IF(isRpc, "RPC binder must have known address at this point");
80
81 auto&& [it, inserted] = mNodeForAddress.insert({RpcAddress::unique(),
82 BinderNode{
83 .binder = binder,
84 .timesSent = 1,
85 .sentRef = binder,
86 }});
87 // TODO(b/182939933): better organization could avoid needing this log
88 LOG_ALWAYS_FATAL_IF(!inserted);
89
90 *outAddress = it->first;
91 return OK;
92}
93
94sp<IBinder> RpcState::onBinderEntering(const sp<RpcConnection>& connection,
95 const RpcAddress& address) {
96 std::unique_lock<std::mutex> _l(mNodeMutex);
97
98 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
99 sp<IBinder> binder = it->second.binder.promote();
100
101 // implicitly have strong RPC refcount, since we received this binder
102 it->second.timesRecd++;
103
104 _l.unlock();
105
106 // We have timesRecd RPC refcounts, but we only need to hold on to one
107 // when we keep the object. All additional dec strongs are sent
108 // immediately, we wait to send the last one in BpBinder::onLastDecStrong.
109 (void)connection->sendDecStrong(address);
110
111 return binder;
112 }
113
114 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
115 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
116
117 // Currently, all binders are assumed to be part of the same connection (no
118 // device global binders in the RPC world).
119 sp<IBinder> binder = BpBinder::create(connection, it->first);
120 it->second.binder = binder;
121 it->second.timesRecd = 1;
122 return binder;
123}
124
125size_t RpcState::countBinders() {
126 std::lock_guard<std::mutex> _l(mNodeMutex);
127 return mNodeForAddress.size();
128}
129
130void RpcState::dump() {
131 std::lock_guard<std::mutex> _l(mNodeMutex);
132 ALOGE("DUMP OF RpcState %p", this);
133 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
134 for (const auto& [address, node] : mNodeForAddress) {
135 sp<IBinder> binder = node.binder.promote();
136
137 const char* desc;
138 if (binder) {
139 if (binder->remoteBinder()) {
140 if (binder->remoteBinder()->isRpcBinder()) {
141 desc = "(rpc binder proxy)";
142 } else {
143 desc = "(binder proxy)";
144 }
145 } else {
146 desc = "(local binder)";
147 }
148 } else {
149 desc = "(null)";
150 }
151
152 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a:%s type:%s",
153 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address.toString().c_str(),
154 desc);
155 }
156 ALOGE("END DUMP OF RpcState");
157}
158
159void RpcState::terminate() {
160 if (SHOULD_LOG_RPC_DETAIL) {
161 ALOGE("RpcState::terminate()");
162 dump();
163 }
164
165 // if the destructor of a binder object makes another RPC call, then calling
166 // decStrong could deadlock. So, we must hold onto these binders until
167 // mNodeMutex is no longer taken.
168 std::vector<sp<IBinder>> tempHoldBinder;
169
170 {
171 std::lock_guard<std::mutex> _l(mNodeMutex);
172 mTerminated = true;
173 for (auto& [address, node] : mNodeForAddress) {
174 sp<IBinder> binder = node.binder.promote();
175 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
176
177 if (node.sentRef != nullptr) {
178 tempHoldBinder.push_back(node.sentRef);
179 }
180 }
181
182 mNodeForAddress.clear();
183 }
184}
185
186bool RpcState::rpcSend(const base::unique_fd& fd, const char* what, const void* data, size_t size) {
187 LOG_RPC_DETAIL("Sending %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
188
189 if (size > std::numeric_limits<ssize_t>::max()) {
190 ALOGE("Cannot send %s at size %zu (too big)", what, size);
191 terminate();
192 return false;
193 }
194
Steven Morelandc6ddf362021-04-02 01:13:36 +0000195 ssize_t sent = TEMP_FAILURE_RETRY(send(fd.get(), data, size, MSG_NOSIGNAL));
Steven Moreland5553ac42020-11-11 02:14:45 +0000196
197 if (sent < 0 || sent != static_cast<ssize_t>(size)) {
198 ALOGE("Failed to send %s (sent %zd of %zu bytes) on fd %d, error: %s", what, sent, size,
199 fd.get(), strerror(errno));
200
201 terminate();
202 return false;
203 }
204
205 return true;
206}
207
208bool RpcState::rpcRec(const base::unique_fd& fd, const char* what, void* data, size_t size) {
209 if (size > std::numeric_limits<ssize_t>::max()) {
210 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
211 terminate();
212 return false;
213 }
214
Steven Morelandc6ddf362021-04-02 01:13:36 +0000215 ssize_t recd = TEMP_FAILURE_RETRY(recv(fd.get(), data, size, MSG_WAITALL | MSG_NOSIGNAL));
Steven Moreland5553ac42020-11-11 02:14:45 +0000216
217 if (recd < 0 || recd != static_cast<ssize_t>(size)) {
218 terminate();
219
220 if (recd == 0 && errno == 0) {
221 LOG_RPC_DETAIL("No more data when trying to read %s on fd %d", what, fd.get());
222 return false;
223 }
224
225 ALOGE("Failed to read %s (received %zd of %zu bytes) on fd %d, error: %s", what, recd, size,
226 fd.get(), strerror(errno));
227 return false;
228 } else {
229 LOG_RPC_DETAIL("Received %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
230 }
231
232 return true;
233}
234
235sp<IBinder> RpcState::getRootObject(const base::unique_fd& fd,
236 const sp<RpcConnection>& connection) {
237 Parcel data;
238 data.markForRpc(connection);
239 Parcel reply;
240
241 status_t status = transact(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT, data,
242 connection, &reply, 0);
243 if (status != OK) {
244 ALOGE("Error getting root object: %s", statusToString(status).c_str());
245 return nullptr;
246 }
247
248 return reply.readStrongBinder();
249}
250
Steven Morelandf137de92021-04-24 01:54:26 +0000251status_t RpcState::getMaxThreads(const base::unique_fd& fd, const sp<RpcConnection>& connection,
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000252 size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000253 Parcel data;
254 data.markForRpc(connection);
255 Parcel reply;
256
257 status_t status = transact(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
258 connection, &reply, 0);
259 if (status != OK) {
260 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
261 return status;
262 }
263
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000264 int32_t maxThreads;
265 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000266 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000267 if (maxThreads <= 0) {
268 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000269 return BAD_VALUE;
270 }
271
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000272 *maxThreadsOut = maxThreads;
273 return OK;
274}
275
276status_t RpcState::getConnectionId(const base::unique_fd& fd, const sp<RpcConnection>& connection,
277 int32_t* connectionIdOut) {
278 Parcel data;
279 data.markForRpc(connection);
280 Parcel reply;
281
282 status_t status = transact(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_CONNECTION_ID, data,
283 connection, &reply, 0);
284 if (status != OK) {
285 ALOGE("Error getting connection ID: %s", statusToString(status).c_str());
286 return status;
287 }
288
289 int32_t connectionId;
290 status = reply.readInt32(&connectionId);
291 if (status != OK) return status;
292
293 *connectionIdOut = connectionId;
Steven Morelandf137de92021-04-24 01:54:26 +0000294 return OK;
295}
296
Steven Moreland5553ac42020-11-11 02:14:45 +0000297status_t RpcState::transact(const base::unique_fd& fd, const RpcAddress& address, uint32_t code,
298 const Parcel& data, const sp<RpcConnection>& connection, Parcel* reply,
299 uint32_t flags) {
300 uint64_t asyncNumber = 0;
301
302 if (!address.isZero()) {
303 std::lock_guard<std::mutex> _l(mNodeMutex);
304 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
305 auto it = mNodeForAddress.find(address);
306 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
307 address.toString().c_str());
308
309 if (flags & IBinder::FLAG_ONEWAY) {
310 asyncNumber = it->second.asyncNumber++;
311 }
312 }
313
314 if (!data.isForRpc()) {
315 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
316 return BAD_TYPE;
317 }
318
319 if (data.objectsCount() != 0) {
320 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
321 return BAD_TYPE;
322 }
323
324 RpcWireTransaction transaction{
325 .address = address.viewRawEmbedded(),
326 .code = code,
327 .flags = flags,
328 .asyncNumber = asyncNumber,
329 };
330
331 std::vector<uint8_t> transactionData(sizeof(RpcWireTransaction) + data.dataSize());
332 memcpy(transactionData.data() + 0, &transaction, sizeof(RpcWireTransaction));
333 memcpy(transactionData.data() + sizeof(RpcWireTransaction), data.data(), data.dataSize());
334
335 if (transactionData.size() > std::numeric_limits<uint32_t>::max()) {
336 ALOGE("Transaction size too big %zu", transactionData.size());
337 return BAD_VALUE;
338 }
339
340 RpcWireHeader command{
341 .command = RPC_COMMAND_TRANSACT,
342 .bodySize = static_cast<uint32_t>(transactionData.size()),
343 };
344
345 if (!rpcSend(fd, "transact header", &command, sizeof(command))) {
346 return DEAD_OBJECT;
347 }
348 if (!rpcSend(fd, "command body", transactionData.data(), transactionData.size())) {
349 return DEAD_OBJECT;
350 }
351
352 if (flags & IBinder::FLAG_ONEWAY) {
353 return OK; // do not wait for result
354 }
355
356 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
357
358 return waitForReply(fd, connection, reply);
359}
360
Steven Moreland438cce82021-04-02 18:04:08 +0000361static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
362 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000363 (void)p;
364 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
365 (void)dataSize;
366 LOG_ALWAYS_FATAL_IF(objects != nullptr);
367 LOG_ALWAYS_FATAL_IF(objectsCount, 0);
368}
369
370status_t RpcState::waitForReply(const base::unique_fd& fd, const sp<RpcConnection>& connection,
371 Parcel* reply) {
372 RpcWireHeader command;
373 while (true) {
374 if (!rpcRec(fd, "command header", &command, sizeof(command))) {
375 return DEAD_OBJECT;
376 }
377
378 if (command.command == RPC_COMMAND_REPLY) break;
379
380 status_t status = processServerCommand(fd, connection, command);
381 if (status != OK) return status;
382 }
383
384 uint8_t* data = new uint8_t[command.bodySize];
385
386 if (!rpcRec(fd, "reply body", data, command.bodySize)) {
387 return DEAD_OBJECT;
388 }
389
390 if (command.bodySize < sizeof(RpcWireReply)) {
391 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
392 sizeof(RpcWireReply), command.bodySize);
393 terminate();
394 return BAD_VALUE;
395 }
396 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data);
397 if (rpcReply->status != OK) return rpcReply->status;
398
399 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000400 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000401
402 reply->markForRpc(connection);
403
404 return OK;
405}
406
407status_t RpcState::sendDecStrong(const base::unique_fd& fd, const RpcAddress& addr) {
408 {
409 std::lock_guard<std::mutex> _l(mNodeMutex);
410 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
411 auto it = mNodeForAddress.find(addr);
412 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
413 addr.toString().c_str());
414 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
415 addr.toString().c_str());
416
417 it->second.timesRecd--;
418 if (it->second.timesRecd == 0 && it->second.timesSent == 0) {
419 mNodeForAddress.erase(it);
420 }
421 }
422
423 RpcWireHeader cmd = {
424 .command = RPC_COMMAND_DEC_STRONG,
425 .bodySize = sizeof(RpcWireAddress),
426 };
427 if (!rpcSend(fd, "dec ref header", &cmd, sizeof(cmd))) return DEAD_OBJECT;
428 if (!rpcSend(fd, "dec ref body", &addr.viewRawEmbedded(), sizeof(RpcWireAddress)))
429 return DEAD_OBJECT;
430 return OK;
431}
432
433status_t RpcState::getAndExecuteCommand(const base::unique_fd& fd,
434 const sp<RpcConnection>& connection) {
435 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", fd.get());
436
437 RpcWireHeader command;
438 if (!rpcRec(fd, "command header", &command, sizeof(command))) {
439 return DEAD_OBJECT;
440 }
441
442 return processServerCommand(fd, connection, command);
443}
444
445status_t RpcState::processServerCommand(const base::unique_fd& fd,
446 const sp<RpcConnection>& connection,
447 const RpcWireHeader& command) {
448 switch (command.command) {
449 case RPC_COMMAND_TRANSACT:
450 return processTransact(fd, connection, command);
451 case RPC_COMMAND_DEC_STRONG:
452 return processDecStrong(fd, command);
453 }
454
455 // We should always know the version of the opposing side, and since the
456 // RPC-binder-level wire protocol is not self synchronizing, we have no way
457 // to understand where the current command ends and the next one begins. We
458 // also can't consider it a fatal error because this would allow any client
459 // to kill us, so ending the connection for misbehaving client.
460 ALOGE("Unknown RPC command %d - terminating connection", command.command);
461 terminate();
462 return DEAD_OBJECT;
463}
464status_t RpcState::processTransact(const base::unique_fd& fd, const sp<RpcConnection>& connection,
465 const RpcWireHeader& command) {
466 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
467
468 std::vector<uint8_t> transactionData(command.bodySize);
469 if (!rpcRec(fd, "transaction body", transactionData.data(), transactionData.size())) {
470 return DEAD_OBJECT;
471 }
472
473 return processTransactInternal(fd, connection, std::move(transactionData));
474}
475
Steven Moreland438cce82021-04-02 18:04:08 +0000476static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
477 const binder_size_t* objects, size_t objectsCount) {
478 (void)p;
479 (void)data;
480 (void)dataSize;
481 (void)objects;
482 (void)objectsCount;
483}
484
Steven Moreland5553ac42020-11-11 02:14:45 +0000485status_t RpcState::processTransactInternal(const base::unique_fd& fd,
486 const sp<RpcConnection>& connection,
487 std::vector<uint8_t>&& transactionData) {
488 if (transactionData.size() < sizeof(RpcWireTransaction)) {
489 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
490 sizeof(RpcWireTransaction), transactionData.size());
491 terminate();
492 return BAD_VALUE;
493 }
494 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
495
496 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
497 // maybe add an RpcAddress 'view' if the type remains 'heavy'
498 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
499
500 status_t replyStatus = OK;
501 sp<IBinder> target;
502 if (!addr.isZero()) {
503 std::lock_guard<std::mutex> _l(mNodeMutex);
504
505 auto it = mNodeForAddress.find(addr);
506 if (it == mNodeForAddress.end()) {
507 ALOGE("Unknown binder address %s.", addr.toString().c_str());
508 dump();
509 replyStatus = BAD_VALUE;
510 } else {
511 target = it->second.binder.promote();
512 if (target == nullptr) {
513 // This can happen if the binder is remote in this process, and
514 // another thread has called the last decStrong on this binder.
515 // However, for local binders, it indicates a misbehaving client
516 // (any binder which is being transacted on should be holding a
517 // strong ref count), so in either case, terminating the
518 // connection.
519 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
520 addr.toString().c_str());
521 terminate();
522 replyStatus = BAD_VALUE;
523 } else if (target->localBinder() == nullptr) {
524 ALOGE("Transactions can only go to local binders, not address %s. Terminating!",
525 addr.toString().c_str());
526 terminate();
527 replyStatus = BAD_VALUE;
528 } else if (transaction->flags & IBinder::FLAG_ONEWAY) {
529 if (transaction->asyncNumber != it->second.asyncNumber) {
530 // we need to process some other asynchronous transaction
531 // first
532 // TODO(b/183140903): limit enqueues/detect overfill for bad client
533 // TODO(b/183140903): detect when an object is deleted when it still has
534 // pending async transactions
535 it->second.asyncTodo.push(BinderNode::AsyncTodo{
536 .data = std::move(transactionData),
537 .asyncNumber = transaction->asyncNumber,
538 });
539 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s", transaction->asyncNumber,
540 addr.toString().c_str());
541 return OK;
542 }
543 }
544 }
545 }
546
Steven Moreland5553ac42020-11-11 02:14:45 +0000547 Parcel reply;
548 reply.markForRpc(connection);
549
550 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000551 Parcel data;
552 // transaction->data is owned by this function. Parcel borrows this data and
553 // only holds onto it for the duration of this function call. Parcel will be
554 // deleted before the 'transactionData' object.
555 data.ipcSetDataReference(transaction->data,
556 transactionData.size() - offsetof(RpcWireTransaction, data),
557 nullptr /*object*/, 0 /*objectCount*/,
558 do_nothing_to_transact_data);
559 data.markForRpc(connection);
560
Steven Moreland5553ac42020-11-11 02:14:45 +0000561 if (target) {
562 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
563 } else {
564 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000565
Steven Morelandf137de92021-04-24 01:54:26 +0000566 sp<RpcServer> server = connection->server().promote();
567 if (server) {
568 // special case for 'zero' address (special server commands)
569 switch (transaction->code) {
570 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
571 replyStatus = reply.writeStrongBinder(server->getRootObject());
572 break;
573 }
574 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
575 replyStatus = reply.writeInt32(server->getMaxThreads());
576 break;
577 }
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000578 case RPC_SPECIAL_TRANSACT_GET_CONNECTION_ID: {
579 // only connections w/ services can be the source of a
580 // connection ID (so still guarded by non-null server)
581 //
582 // connections associated with servers must have an ID
583 // (hence abort)
584 int32_t id = connection->getPrivateAccessorForId().get().value();
585 replyStatus = reply.writeInt32(id);
586 break;
587 }
Steven Morelandf137de92021-04-24 01:54:26 +0000588 default: {
589 replyStatus = UNKNOWN_TRANSACTION;
590 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000591 }
Steven Morelandf137de92021-04-24 01:54:26 +0000592 } else {
593 ALOGE("Special command sent, but no server object attached.");
Steven Moreland5553ac42020-11-11 02:14:45 +0000594 }
595 }
596 }
597
598 if (transaction->flags & IBinder::FLAG_ONEWAY) {
599 if (replyStatus != OK) {
600 ALOGW("Oneway call failed with error: %d", replyStatus);
601 }
602
603 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
604 addr.toString().c_str());
605
606 // Check to see if there is another asynchronous transaction to process.
607 // This behavior differs from binder behavior, since in the binder
608 // driver, asynchronous transactions will be processed after existing
609 // pending binder transactions on the queue. The downside of this is
610 // that asynchronous transactions can be drowned out by synchronous
611 // transactions. However, we have no easy way to queue these
612 // transactions after the synchronous transactions we may want to read
613 // from the wire. So, in socket binder here, we have the opposite
614 // downside: asynchronous transactions may drown out synchronous
615 // transactions.
616 {
617 std::unique_lock<std::mutex> _l(mNodeMutex);
618 auto it = mNodeForAddress.find(addr);
619 // last refcount dropped after this transaction happened
620 if (it == mNodeForAddress.end()) return OK;
621
622 // note - only updated now, instead of later, so that other threads
623 // will queue any later transactions
624
625 // TODO(b/183140903): support > 2**64 async transactions
626 // (we can do this by allowing asyncNumber to wrap, since we
627 // don't expect more than 2**64 simultaneous transactions)
628 it->second.asyncNumber++;
629
630 if (it->second.asyncTodo.size() == 0) return OK;
631 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
632 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
633 it->second.asyncNumber, addr.toString().c_str());
634
635 // justification for const_cast (consider avoiding priority_queue):
636 // - AsyncTodo operator< doesn't depend on 'data' object
637 // - gotta go fast
638 std::vector<uint8_t> data = std::move(
639 const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top()).data);
640 it->second.asyncTodo.pop();
641 _l.unlock();
642 return processTransactInternal(fd, connection, std::move(data));
643 }
644 }
645 return OK;
646 }
647
648 RpcWireReply rpcReply{
649 .status = replyStatus,
650 };
651
652 std::vector<uint8_t> replyData(sizeof(RpcWireReply) + reply.dataSize());
653 memcpy(replyData.data() + 0, &rpcReply, sizeof(RpcWireReply));
654 memcpy(replyData.data() + sizeof(RpcWireReply), reply.data(), reply.dataSize());
655
656 if (replyData.size() > std::numeric_limits<uint32_t>::max()) {
657 ALOGE("Reply size too big %zu", transactionData.size());
658 terminate();
659 return BAD_VALUE;
660 }
661
662 RpcWireHeader cmdReply{
663 .command = RPC_COMMAND_REPLY,
664 .bodySize = static_cast<uint32_t>(replyData.size()),
665 };
666
667 if (!rpcSend(fd, "reply header", &cmdReply, sizeof(RpcWireHeader))) {
668 return DEAD_OBJECT;
669 }
670 if (!rpcSend(fd, "reply body", replyData.data(), replyData.size())) {
671 return DEAD_OBJECT;
672 }
673 return OK;
674}
675
676status_t RpcState::processDecStrong(const base::unique_fd& fd, const RpcWireHeader& command) {
677 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
678
679 std::vector<uint8_t> commandData(command.bodySize);
680 if (!rpcRec(fd, "dec ref body", commandData.data(), commandData.size())) {
681 return DEAD_OBJECT;
682 }
683
684 if (command.bodySize < sizeof(RpcWireAddress)) {
685 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
686 sizeof(RpcWireAddress), command.bodySize);
687 terminate();
688 return BAD_VALUE;
689 }
690 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
691
692 // TODO(b/182939933): heap allocation just for lookup
693 auto addr = RpcAddress::fromRawEmbedded(address);
694 std::unique_lock<std::mutex> _l(mNodeMutex);
695 auto it = mNodeForAddress.find(addr);
696 if (it == mNodeForAddress.end()) {
697 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
698 dump();
699 return OK;
700 }
701
702 sp<IBinder> target = it->second.binder.promote();
703 if (target == nullptr) {
704 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
705 addr.toString().c_str());
706 terminate();
707 return BAD_VALUE;
708 }
709
710 if (it->second.timesSent == 0) {
711 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
712 return OK;
713 }
714
715 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
716 addr.toString().c_str());
717
718 sp<IBinder> tempHold;
719
720 it->second.timesSent--;
721 if (it->second.timesSent == 0) {
722 tempHold = it->second.sentRef;
723 it->second.sentRef = nullptr;
724
725 if (it->second.timesRecd == 0) {
726 mNodeForAddress.erase(it);
727 }
728 }
729
730 _l.unlock();
731 tempHold = nullptr; // destructor may make binder calls on this connection
732
733 return OK;
734}
735
736} // namespace android