blob: 96190dc03c186f992715dc499487ba4c773c57cd [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
Steven Morelandbdb53ab2021-05-05 17:57:41 +000034status_t RpcState::onBinderLeaving(const sp<RpcSession>& session, const sp<IBinder>& binder,
Steven Moreland5553ac42020-11-11 02:14:45 +000035 RpcAddress* outAddress) {
36 bool isRemote = binder->remoteBinder();
37 bool isRpc = isRemote && binder->remoteBinder()->isRpcBinder();
38
Steven Morelandbdb53ab2021-05-05 17:57:41 +000039 if (isRpc && binder->remoteBinder()->getPrivateAccessorForId().rpcSession() != session) {
Steven Moreland5553ac42020-11-11 02:14:45 +000040 // 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.
Steven Morelandbdb53ab2021-05-05 17:57:41 +000043 ALOGE("Cannot send binder from unrelated binder RPC session.");
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
Steven Morelandbdb53ab2021-05-05 17:57:41 +000094sp<IBinder> RpcState::onBinderEntering(const sp<RpcSession>& session, const RpcAddress& address) {
Steven Moreland5553ac42020-11-11 02:14:45 +000095 std::unique_lock<std::mutex> _l(mNodeMutex);
96
97 if (auto it = mNodeForAddress.find(address); it != mNodeForAddress.end()) {
98 sp<IBinder> binder = it->second.binder.promote();
99
100 // implicitly have strong RPC refcount, since we received this binder
101 it->second.timesRecd++;
102
103 _l.unlock();
104
105 // We have timesRecd RPC refcounts, but we only need to hold on to one
106 // when we keep the object. All additional dec strongs are sent
107 // immediately, we wait to send the last one in BpBinder::onLastDecStrong.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000108 (void)session->sendDecStrong(address);
Steven Moreland5553ac42020-11-11 02:14:45 +0000109
110 return binder;
111 }
112
113 auto&& [it, inserted] = mNodeForAddress.insert({address, BinderNode{}});
114 LOG_ALWAYS_FATAL_IF(!inserted, "Failed to insert binder when creating proxy");
115
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000116 // Currently, all binders are assumed to be part of the same session (no
Steven Moreland5553ac42020-11-11 02:14:45 +0000117 // device global binders in the RPC world).
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000118 sp<IBinder> binder = BpBinder::create(session, it->first);
Steven Moreland5553ac42020-11-11 02:14:45 +0000119 it->second.binder = binder;
120 it->second.timesRecd = 1;
121 return binder;
122}
123
124size_t RpcState::countBinders() {
125 std::lock_guard<std::mutex> _l(mNodeMutex);
126 return mNodeForAddress.size();
127}
128
129void RpcState::dump() {
130 std::lock_guard<std::mutex> _l(mNodeMutex);
131 ALOGE("DUMP OF RpcState %p", this);
132 ALOGE("DUMP OF RpcState (%zu nodes)", mNodeForAddress.size());
133 for (const auto& [address, node] : mNodeForAddress) {
134 sp<IBinder> binder = node.binder.promote();
135
136 const char* desc;
137 if (binder) {
138 if (binder->remoteBinder()) {
139 if (binder->remoteBinder()->isRpcBinder()) {
140 desc = "(rpc binder proxy)";
141 } else {
142 desc = "(binder proxy)";
143 }
144 } else {
145 desc = "(local binder)";
146 }
147 } else {
148 desc = "(null)";
149 }
150
151 ALOGE("- BINDER NODE: %p times sent:%zu times recd: %zu a:%s type:%s",
152 node.binder.unsafe_get(), node.timesSent, node.timesRecd, address.toString().c_str(),
153 desc);
154 }
155 ALOGE("END DUMP OF RpcState");
156}
157
158void RpcState::terminate() {
159 if (SHOULD_LOG_RPC_DETAIL) {
160 ALOGE("RpcState::terminate()");
161 dump();
162 }
163
164 // if the destructor of a binder object makes another RPC call, then calling
165 // decStrong could deadlock. So, we must hold onto these binders until
166 // mNodeMutex is no longer taken.
167 std::vector<sp<IBinder>> tempHoldBinder;
168
169 {
170 std::lock_guard<std::mutex> _l(mNodeMutex);
171 mTerminated = true;
172 for (auto& [address, node] : mNodeForAddress) {
173 sp<IBinder> binder = node.binder.promote();
174 LOG_ALWAYS_FATAL_IF(binder == nullptr, "Binder %p expected to be owned.", binder.get());
175
176 if (node.sentRef != nullptr) {
177 tempHoldBinder.push_back(node.sentRef);
178 }
179 }
180
181 mNodeForAddress.clear();
182 }
183}
184
185bool RpcState::rpcSend(const base::unique_fd& fd, const char* what, const void* data, size_t size) {
186 LOG_RPC_DETAIL("Sending %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
187
188 if (size > std::numeric_limits<ssize_t>::max()) {
189 ALOGE("Cannot send %s at size %zu (too big)", what, size);
190 terminate();
191 return false;
192 }
193
Steven Morelandc6ddf362021-04-02 01:13:36 +0000194 ssize_t sent = TEMP_FAILURE_RETRY(send(fd.get(), data, size, MSG_NOSIGNAL));
Steven Moreland5553ac42020-11-11 02:14:45 +0000195
196 if (sent < 0 || sent != static_cast<ssize_t>(size)) {
197 ALOGE("Failed to send %s (sent %zd of %zu bytes) on fd %d, error: %s", what, sent, size,
198 fd.get(), strerror(errno));
199
200 terminate();
201 return false;
202 }
203
204 return true;
205}
206
207bool RpcState::rpcRec(const base::unique_fd& fd, const char* what, void* data, size_t size) {
208 if (size > std::numeric_limits<ssize_t>::max()) {
209 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
210 terminate();
211 return false;
212 }
213
Steven Morelandc6ddf362021-04-02 01:13:36 +0000214 ssize_t recd = TEMP_FAILURE_RETRY(recv(fd.get(), data, size, MSG_WAITALL | MSG_NOSIGNAL));
Steven Moreland5553ac42020-11-11 02:14:45 +0000215
216 if (recd < 0 || recd != static_cast<ssize_t>(size)) {
217 terminate();
218
219 if (recd == 0 && errno == 0) {
220 LOG_RPC_DETAIL("No more data when trying to read %s on fd %d", what, fd.get());
221 return false;
222 }
223
224 ALOGE("Failed to read %s (received %zd of %zu bytes) on fd %d, error: %s", what, recd, size,
225 fd.get(), strerror(errno));
226 return false;
227 } else {
228 LOG_RPC_DETAIL("Received %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
229 }
230
231 return true;
232}
233
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000234sp<IBinder> RpcState::getRootObject(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000235 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000236 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000237 Parcel reply;
238
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000239 status_t status = transact(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT, data, session,
240 &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000241 if (status != OK) {
242 ALOGE("Error getting root object: %s", statusToString(status).c_str());
243 return nullptr;
244 }
245
246 return reply.readStrongBinder();
247}
248
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000249status_t RpcState::getMaxThreads(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000250 size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000251 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000252 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000253 Parcel reply;
254
255 status_t status = transact(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000256 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000257 if (status != OK) {
258 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
259 return status;
260 }
261
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000262 int32_t maxThreads;
263 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000264 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000265 if (maxThreads <= 0) {
266 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000267 return BAD_VALUE;
268 }
269
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000270 *maxThreadsOut = maxThreads;
271 return OK;
272}
273
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000274status_t RpcState::getSessionId(const base::unique_fd& fd, const sp<RpcSession>& session,
275 int32_t* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000276 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000277 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000278 Parcel reply;
279
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000280 status_t status = transact(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
281 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000282 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000283 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000284 return status;
285 }
286
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000287 int32_t sessionId;
288 status = reply.readInt32(&sessionId);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000289 if (status != OK) return status;
290
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000291 *sessionIdOut = sessionId;
Steven Morelandf137de92021-04-24 01:54:26 +0000292 return OK;
293}
294
Steven Moreland5553ac42020-11-11 02:14:45 +0000295status_t RpcState::transact(const base::unique_fd& fd, const RpcAddress& address, uint32_t code,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000296 const Parcel& data, const sp<RpcSession>& session, Parcel* reply,
Steven Moreland5553ac42020-11-11 02:14:45 +0000297 uint32_t flags) {
298 uint64_t asyncNumber = 0;
299
300 if (!address.isZero()) {
301 std::lock_guard<std::mutex> _l(mNodeMutex);
302 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
303 auto it = mNodeForAddress.find(address);
304 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
305 address.toString().c_str());
306
307 if (flags & IBinder::FLAG_ONEWAY) {
308 asyncNumber = it->second.asyncNumber++;
309 }
310 }
311
312 if (!data.isForRpc()) {
313 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
314 return BAD_TYPE;
315 }
316
317 if (data.objectsCount() != 0) {
318 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
319 return BAD_TYPE;
320 }
321
322 RpcWireTransaction transaction{
323 .address = address.viewRawEmbedded(),
324 .code = code,
325 .flags = flags,
326 .asyncNumber = asyncNumber,
327 };
328
329 std::vector<uint8_t> transactionData(sizeof(RpcWireTransaction) + data.dataSize());
330 memcpy(transactionData.data() + 0, &transaction, sizeof(RpcWireTransaction));
331 memcpy(transactionData.data() + sizeof(RpcWireTransaction), data.data(), data.dataSize());
332
333 if (transactionData.size() > std::numeric_limits<uint32_t>::max()) {
334 ALOGE("Transaction size too big %zu", transactionData.size());
335 return BAD_VALUE;
336 }
337
338 RpcWireHeader command{
339 .command = RPC_COMMAND_TRANSACT,
340 .bodySize = static_cast<uint32_t>(transactionData.size()),
341 };
342
343 if (!rpcSend(fd, "transact header", &command, sizeof(command))) {
344 return DEAD_OBJECT;
345 }
346 if (!rpcSend(fd, "command body", transactionData.data(), transactionData.size())) {
347 return DEAD_OBJECT;
348 }
349
350 if (flags & IBinder::FLAG_ONEWAY) {
351 return OK; // do not wait for result
352 }
353
354 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
355
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000356 return waitForReply(fd, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000357}
358
Steven Moreland438cce82021-04-02 18:04:08 +0000359static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
360 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000361 (void)p;
362 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
363 (void)dataSize;
364 LOG_ALWAYS_FATAL_IF(objects != nullptr);
365 LOG_ALWAYS_FATAL_IF(objectsCount, 0);
366}
367
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000368status_t RpcState::waitForReply(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000369 Parcel* reply) {
370 RpcWireHeader command;
371 while (true) {
372 if (!rpcRec(fd, "command header", &command, sizeof(command))) {
373 return DEAD_OBJECT;
374 }
375
376 if (command.command == RPC_COMMAND_REPLY) break;
377
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000378 status_t status = processServerCommand(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000379 if (status != OK) return status;
380 }
381
382 uint8_t* data = new uint8_t[command.bodySize];
383
384 if (!rpcRec(fd, "reply body", data, command.bodySize)) {
385 return DEAD_OBJECT;
386 }
387
388 if (command.bodySize < sizeof(RpcWireReply)) {
389 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
390 sizeof(RpcWireReply), command.bodySize);
391 terminate();
392 return BAD_VALUE;
393 }
394 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data);
395 if (rpcReply->status != OK) return rpcReply->status;
396
397 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000398 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000399
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000400 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000401
402 return OK;
403}
404
405status_t RpcState::sendDecStrong(const base::unique_fd& fd, const RpcAddress& addr) {
406 {
407 std::lock_guard<std::mutex> _l(mNodeMutex);
408 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
409 auto it = mNodeForAddress.find(addr);
410 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
411 addr.toString().c_str());
412 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
413 addr.toString().c_str());
414
415 it->second.timesRecd--;
416 if (it->second.timesRecd == 0 && it->second.timesSent == 0) {
417 mNodeForAddress.erase(it);
418 }
419 }
420
421 RpcWireHeader cmd = {
422 .command = RPC_COMMAND_DEC_STRONG,
423 .bodySize = sizeof(RpcWireAddress),
424 };
425 if (!rpcSend(fd, "dec ref header", &cmd, sizeof(cmd))) return DEAD_OBJECT;
426 if (!rpcSend(fd, "dec ref body", &addr.viewRawEmbedded(), sizeof(RpcWireAddress)))
427 return DEAD_OBJECT;
428 return OK;
429}
430
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000431status_t RpcState::getAndExecuteCommand(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000432 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", fd.get());
433
434 RpcWireHeader command;
435 if (!rpcRec(fd, "command header", &command, sizeof(command))) {
436 return DEAD_OBJECT;
437 }
438
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000439 return processServerCommand(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000440}
441
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000442status_t RpcState::processServerCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000443 const RpcWireHeader& command) {
444 switch (command.command) {
445 case RPC_COMMAND_TRANSACT:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000446 return processTransact(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000447 case RPC_COMMAND_DEC_STRONG:
448 return processDecStrong(fd, command);
449 }
450
451 // We should always know the version of the opposing side, and since the
452 // RPC-binder-level wire protocol is not self synchronizing, we have no way
453 // to understand where the current command ends and the next one begins. We
454 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000455 // to kill us, so ending the session for misbehaving client.
456 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000457 terminate();
458 return DEAD_OBJECT;
459}
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000460status_t RpcState::processTransact(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000461 const RpcWireHeader& command) {
462 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
463
464 std::vector<uint8_t> transactionData(command.bodySize);
465 if (!rpcRec(fd, "transaction body", transactionData.data(), transactionData.size())) {
466 return DEAD_OBJECT;
467 }
468
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000469 return processTransactInternal(fd, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000470}
471
Steven Moreland438cce82021-04-02 18:04:08 +0000472static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
473 const binder_size_t* objects, size_t objectsCount) {
474 (void)p;
475 (void)data;
476 (void)dataSize;
477 (void)objects;
478 (void)objectsCount;
479}
480
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000481status_t RpcState::processTransactInternal(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000482 std::vector<uint8_t>&& transactionData) {
483 if (transactionData.size() < sizeof(RpcWireTransaction)) {
484 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
485 sizeof(RpcWireTransaction), transactionData.size());
486 terminate();
487 return BAD_VALUE;
488 }
489 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
490
491 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
492 // maybe add an RpcAddress 'view' if the type remains 'heavy'
493 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
494
495 status_t replyStatus = OK;
496 sp<IBinder> target;
497 if (!addr.isZero()) {
498 std::lock_guard<std::mutex> _l(mNodeMutex);
499
500 auto it = mNodeForAddress.find(addr);
501 if (it == mNodeForAddress.end()) {
502 ALOGE("Unknown binder address %s.", addr.toString().c_str());
503 dump();
504 replyStatus = BAD_VALUE;
505 } else {
506 target = it->second.binder.promote();
507 if (target == nullptr) {
508 // This can happen if the binder is remote in this process, and
509 // another thread has called the last decStrong on this binder.
510 // However, for local binders, it indicates a misbehaving client
511 // (any binder which is being transacted on should be holding a
512 // strong ref count), so in either case, terminating the
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000513 // session.
Steven Moreland5553ac42020-11-11 02:14:45 +0000514 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
515 addr.toString().c_str());
516 terminate();
517 replyStatus = BAD_VALUE;
518 } else if (target->localBinder() == nullptr) {
519 ALOGE("Transactions can only go to local binders, not address %s. Terminating!",
520 addr.toString().c_str());
521 terminate();
522 replyStatus = BAD_VALUE;
523 } else if (transaction->flags & IBinder::FLAG_ONEWAY) {
524 if (transaction->asyncNumber != it->second.asyncNumber) {
525 // we need to process some other asynchronous transaction
526 // first
527 // TODO(b/183140903): limit enqueues/detect overfill for bad client
528 // TODO(b/183140903): detect when an object is deleted when it still has
529 // pending async transactions
530 it->second.asyncTodo.push(BinderNode::AsyncTodo{
531 .data = std::move(transactionData),
532 .asyncNumber = transaction->asyncNumber,
533 });
534 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s", transaction->asyncNumber,
535 addr.toString().c_str());
536 return OK;
537 }
538 }
539 }
540 }
541
Steven Moreland5553ac42020-11-11 02:14:45 +0000542 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000543 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000544
545 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000546 Parcel data;
547 // transaction->data is owned by this function. Parcel borrows this data and
548 // only holds onto it for the duration of this function call. Parcel will be
549 // deleted before the 'transactionData' object.
550 data.ipcSetDataReference(transaction->data,
551 transactionData.size() - offsetof(RpcWireTransaction, data),
552 nullptr /*object*/, 0 /*objectCount*/,
553 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000554 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000555
Steven Moreland5553ac42020-11-11 02:14:45 +0000556 if (target) {
557 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
558 } else {
559 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000560
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000561 sp<RpcServer> server = session->server().promote();
Steven Morelandf137de92021-04-24 01:54:26 +0000562 if (server) {
563 // special case for 'zero' address (special server commands)
564 switch (transaction->code) {
565 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
566 replyStatus = reply.writeStrongBinder(server->getRootObject());
567 break;
568 }
569 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
570 replyStatus = reply.writeInt32(server->getMaxThreads());
571 break;
572 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000573 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
574 // only sessions w/ services can be the source of a
575 // session ID (so still guarded by non-null server)
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000576 //
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000577 // sessions associated with servers must have an ID
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000578 // (hence abort)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000579 int32_t id = session->getPrivateAccessorForId().get().value();
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000580 replyStatus = reply.writeInt32(id);
581 break;
582 }
Steven Morelandf137de92021-04-24 01:54:26 +0000583 default: {
584 replyStatus = UNKNOWN_TRANSACTION;
585 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000586 }
Steven Morelandf137de92021-04-24 01:54:26 +0000587 } else {
588 ALOGE("Special command sent, but no server object attached.");
Steven Moreland5553ac42020-11-11 02:14:45 +0000589 }
590 }
591 }
592
593 if (transaction->flags & IBinder::FLAG_ONEWAY) {
594 if (replyStatus != OK) {
595 ALOGW("Oneway call failed with error: %d", replyStatus);
596 }
597
598 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
599 addr.toString().c_str());
600
601 // Check to see if there is another asynchronous transaction to process.
602 // This behavior differs from binder behavior, since in the binder
603 // driver, asynchronous transactions will be processed after existing
604 // pending binder transactions on the queue. The downside of this is
605 // that asynchronous transactions can be drowned out by synchronous
606 // transactions. However, we have no easy way to queue these
607 // transactions after the synchronous transactions we may want to read
608 // from the wire. So, in socket binder here, we have the opposite
609 // downside: asynchronous transactions may drown out synchronous
610 // transactions.
611 {
612 std::unique_lock<std::mutex> _l(mNodeMutex);
613 auto it = mNodeForAddress.find(addr);
614 // last refcount dropped after this transaction happened
615 if (it == mNodeForAddress.end()) return OK;
616
617 // note - only updated now, instead of later, so that other threads
618 // will queue any later transactions
619
620 // TODO(b/183140903): support > 2**64 async transactions
621 // (we can do this by allowing asyncNumber to wrap, since we
622 // don't expect more than 2**64 simultaneous transactions)
623 it->second.asyncNumber++;
624
625 if (it->second.asyncTodo.size() == 0) return OK;
626 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
627 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
628 it->second.asyncNumber, addr.toString().c_str());
629
630 // justification for const_cast (consider avoiding priority_queue):
631 // - AsyncTodo operator< doesn't depend on 'data' object
632 // - gotta go fast
633 std::vector<uint8_t> data = std::move(
634 const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top()).data);
635 it->second.asyncTodo.pop();
636 _l.unlock();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000637 return processTransactInternal(fd, session, std::move(data));
Steven Moreland5553ac42020-11-11 02:14:45 +0000638 }
639 }
640 return OK;
641 }
642
643 RpcWireReply rpcReply{
644 .status = replyStatus,
645 };
646
647 std::vector<uint8_t> replyData(sizeof(RpcWireReply) + reply.dataSize());
648 memcpy(replyData.data() + 0, &rpcReply, sizeof(RpcWireReply));
649 memcpy(replyData.data() + sizeof(RpcWireReply), reply.data(), reply.dataSize());
650
651 if (replyData.size() > std::numeric_limits<uint32_t>::max()) {
652 ALOGE("Reply size too big %zu", transactionData.size());
653 terminate();
654 return BAD_VALUE;
655 }
656
657 RpcWireHeader cmdReply{
658 .command = RPC_COMMAND_REPLY,
659 .bodySize = static_cast<uint32_t>(replyData.size()),
660 };
661
662 if (!rpcSend(fd, "reply header", &cmdReply, sizeof(RpcWireHeader))) {
663 return DEAD_OBJECT;
664 }
665 if (!rpcSend(fd, "reply body", replyData.data(), replyData.size())) {
666 return DEAD_OBJECT;
667 }
668 return OK;
669}
670
671status_t RpcState::processDecStrong(const base::unique_fd& fd, const RpcWireHeader& command) {
672 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
673
674 std::vector<uint8_t> commandData(command.bodySize);
675 if (!rpcRec(fd, "dec ref body", commandData.data(), commandData.size())) {
676 return DEAD_OBJECT;
677 }
678
679 if (command.bodySize < sizeof(RpcWireAddress)) {
680 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
681 sizeof(RpcWireAddress), command.bodySize);
682 terminate();
683 return BAD_VALUE;
684 }
685 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
686
687 // TODO(b/182939933): heap allocation just for lookup
688 auto addr = RpcAddress::fromRawEmbedded(address);
689 std::unique_lock<std::mutex> _l(mNodeMutex);
690 auto it = mNodeForAddress.find(addr);
691 if (it == mNodeForAddress.end()) {
692 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
693 dump();
694 return OK;
695 }
696
697 sp<IBinder> target = it->second.binder.promote();
698 if (target == nullptr) {
699 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
700 addr.toString().c_str());
701 terminate();
702 return BAD_VALUE;
703 }
704
705 if (it->second.timesSent == 0) {
706 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
707 return OK;
708 }
709
710 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
711 addr.toString().c_str());
712
713 sp<IBinder> tempHold;
714
715 it->second.timesSent--;
716 if (it->second.timesSent == 0) {
717 tempHold = it->second.sentRef;
718 it->second.sentRef = nullptr;
719
720 if (it->second.timesRecd == 0) {
721 mNodeForAddress.erase(it);
722 }
723 }
724
725 _l.unlock();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000726 tempHold = nullptr; // destructor may make binder calls on this session
Steven Moreland5553ac42020-11-11 02:14:45 +0000727
728 return OK;
729}
730
731} // namespace android