blob: 976351c6c4bf66bf8833667e095ad86fb36fc846 [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
Steven Morelande8393342021-05-05 23:27:53 +0000329 ByteVec transactionData(sizeof(RpcWireTransaction) + data.dataSize());
330 if (!transactionData.valid()) {
331 return NO_MEMORY;
332 }
333
Steven Moreland5553ac42020-11-11 02:14:45 +0000334 memcpy(transactionData.data() + 0, &transaction, sizeof(RpcWireTransaction));
335 memcpy(transactionData.data() + sizeof(RpcWireTransaction), data.data(), data.dataSize());
336
337 if (transactionData.size() > std::numeric_limits<uint32_t>::max()) {
338 ALOGE("Transaction size too big %zu", transactionData.size());
339 return BAD_VALUE;
340 }
341
342 RpcWireHeader command{
343 .command = RPC_COMMAND_TRANSACT,
344 .bodySize = static_cast<uint32_t>(transactionData.size()),
345 };
346
347 if (!rpcSend(fd, "transact header", &command, sizeof(command))) {
348 return DEAD_OBJECT;
349 }
350 if (!rpcSend(fd, "command body", transactionData.data(), transactionData.size())) {
351 return DEAD_OBJECT;
352 }
353
354 if (flags & IBinder::FLAG_ONEWAY) {
355 return OK; // do not wait for result
356 }
357
358 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
359
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000360 return waitForReply(fd, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000361}
362
Steven Moreland438cce82021-04-02 18:04:08 +0000363static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
364 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000365 (void)p;
366 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
367 (void)dataSize;
368 LOG_ALWAYS_FATAL_IF(objects != nullptr);
369 LOG_ALWAYS_FATAL_IF(objectsCount, 0);
370}
371
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000372status_t RpcState::waitForReply(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000373 Parcel* reply) {
374 RpcWireHeader command;
375 while (true) {
376 if (!rpcRec(fd, "command header", &command, sizeof(command))) {
377 return DEAD_OBJECT;
378 }
379
380 if (command.command == RPC_COMMAND_REPLY) break;
381
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000382 status_t status = processServerCommand(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000383 if (status != OK) return status;
384 }
385
Steven Morelande8393342021-05-05 23:27:53 +0000386 ByteVec data(command.bodySize);
387 if (!data.valid()) {
388 return NO_MEMORY;
389 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000390
Steven Morelande8393342021-05-05 23:27:53 +0000391 if (!rpcRec(fd, "reply body", data.data(), command.bodySize)) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000392 return DEAD_OBJECT;
393 }
394
395 if (command.bodySize < sizeof(RpcWireReply)) {
396 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
397 sizeof(RpcWireReply), command.bodySize);
398 terminate();
399 return BAD_VALUE;
400 }
Steven Morelande8393342021-05-05 23:27:53 +0000401 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000402 if (rpcReply->status != OK) return rpcReply->status;
403
Steven Morelande8393342021-05-05 23:27:53 +0000404 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000405 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000406 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000407
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000408 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000409
410 return OK;
411}
412
413status_t RpcState::sendDecStrong(const base::unique_fd& fd, const RpcAddress& addr) {
414 {
415 std::lock_guard<std::mutex> _l(mNodeMutex);
416 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
417 auto it = mNodeForAddress.find(addr);
418 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
419 addr.toString().c_str());
420 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
421 addr.toString().c_str());
422
423 it->second.timesRecd--;
424 if (it->second.timesRecd == 0 && it->second.timesSent == 0) {
425 mNodeForAddress.erase(it);
426 }
427 }
428
429 RpcWireHeader cmd = {
430 .command = RPC_COMMAND_DEC_STRONG,
431 .bodySize = sizeof(RpcWireAddress),
432 };
433 if (!rpcSend(fd, "dec ref header", &cmd, sizeof(cmd))) return DEAD_OBJECT;
434 if (!rpcSend(fd, "dec ref body", &addr.viewRawEmbedded(), sizeof(RpcWireAddress)))
435 return DEAD_OBJECT;
436 return OK;
437}
438
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000439status_t RpcState::getAndExecuteCommand(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000440 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", fd.get());
441
442 RpcWireHeader command;
443 if (!rpcRec(fd, "command header", &command, sizeof(command))) {
444 return DEAD_OBJECT;
445 }
446
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000447 return processServerCommand(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000448}
449
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000450status_t RpcState::processServerCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000451 const RpcWireHeader& command) {
452 switch (command.command) {
453 case RPC_COMMAND_TRANSACT:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000454 return processTransact(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000455 case RPC_COMMAND_DEC_STRONG:
456 return processDecStrong(fd, command);
457 }
458
459 // We should always know the version of the opposing side, and since the
460 // RPC-binder-level wire protocol is not self synchronizing, we have no way
461 // to understand where the current command ends and the next one begins. We
462 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000463 // to kill us, so ending the session for misbehaving client.
464 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000465 terminate();
466 return DEAD_OBJECT;
467}
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000468status_t RpcState::processTransact(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000469 const RpcWireHeader& command) {
470 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
471
Steven Morelande8393342021-05-05 23:27:53 +0000472 ByteVec transactionData(command.bodySize);
473 if (!transactionData.valid()) {
474 return NO_MEMORY;
475 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000476 if (!rpcRec(fd, "transaction body", transactionData.data(), transactionData.size())) {
477 return DEAD_OBJECT;
478 }
479
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000480 return processTransactInternal(fd, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000481}
482
Steven Moreland438cce82021-04-02 18:04:08 +0000483static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
484 const binder_size_t* objects, size_t objectsCount) {
485 (void)p;
486 (void)data;
487 (void)dataSize;
488 (void)objects;
489 (void)objectsCount;
490}
491
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000492status_t RpcState::processTransactInternal(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Morelande8393342021-05-05 23:27:53 +0000493 ByteVec transactionData) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000494 if (transactionData.size() < sizeof(RpcWireTransaction)) {
495 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
496 sizeof(RpcWireTransaction), transactionData.size());
497 terminate();
498 return BAD_VALUE;
499 }
500 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
501
502 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
503 // maybe add an RpcAddress 'view' if the type remains 'heavy'
504 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
505
506 status_t replyStatus = OK;
507 sp<IBinder> target;
508 if (!addr.isZero()) {
509 std::lock_guard<std::mutex> _l(mNodeMutex);
510
511 auto it = mNodeForAddress.find(addr);
512 if (it == mNodeForAddress.end()) {
513 ALOGE("Unknown binder address %s.", addr.toString().c_str());
514 dump();
515 replyStatus = BAD_VALUE;
516 } else {
517 target = it->second.binder.promote();
518 if (target == nullptr) {
519 // This can happen if the binder is remote in this process, and
520 // another thread has called the last decStrong on this binder.
521 // However, for local binders, it indicates a misbehaving client
522 // (any binder which is being transacted on should be holding a
523 // strong ref count), so in either case, terminating the
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000524 // session.
Steven Moreland5553ac42020-11-11 02:14:45 +0000525 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
526 addr.toString().c_str());
527 terminate();
528 replyStatus = BAD_VALUE;
529 } else if (target->localBinder() == nullptr) {
530 ALOGE("Transactions can only go to local binders, not address %s. Terminating!",
531 addr.toString().c_str());
532 terminate();
533 replyStatus = BAD_VALUE;
534 } else if (transaction->flags & IBinder::FLAG_ONEWAY) {
535 if (transaction->asyncNumber != it->second.asyncNumber) {
536 // we need to process some other asynchronous transaction
537 // first
538 // TODO(b/183140903): limit enqueues/detect overfill for bad client
539 // TODO(b/183140903): detect when an object is deleted when it still has
540 // pending async transactions
541 it->second.asyncTodo.push(BinderNode::AsyncTodo{
542 .data = std::move(transactionData),
543 .asyncNumber = transaction->asyncNumber,
544 });
545 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s", transaction->asyncNumber,
546 addr.toString().c_str());
547 return OK;
548 }
549 }
550 }
551 }
552
Steven Moreland5553ac42020-11-11 02:14:45 +0000553 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000554 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000555
556 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000557 Parcel data;
558 // transaction->data is owned by this function. Parcel borrows this data and
559 // only holds onto it for the duration of this function call. Parcel will be
560 // deleted before the 'transactionData' object.
561 data.ipcSetDataReference(transaction->data,
562 transactionData.size() - offsetof(RpcWireTransaction, data),
563 nullptr /*object*/, 0 /*objectCount*/,
564 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000565 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000566
Steven Moreland5553ac42020-11-11 02:14:45 +0000567 if (target) {
568 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
569 } else {
570 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000571
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000572 sp<RpcServer> server = session->server().promote();
Steven Morelandf137de92021-04-24 01:54:26 +0000573 if (server) {
574 // special case for 'zero' address (special server commands)
575 switch (transaction->code) {
576 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
577 replyStatus = reply.writeStrongBinder(server->getRootObject());
578 break;
579 }
580 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
581 replyStatus = reply.writeInt32(server->getMaxThreads());
582 break;
583 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000584 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
585 // only sessions w/ services can be the source of a
586 // session ID (so still guarded by non-null server)
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000587 //
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000588 // sessions associated with servers must have an ID
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000589 // (hence abort)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000590 int32_t id = session->getPrivateAccessorForId().get().value();
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000591 replyStatus = reply.writeInt32(id);
592 break;
593 }
Steven Morelandf137de92021-04-24 01:54:26 +0000594 default: {
595 replyStatus = UNKNOWN_TRANSACTION;
596 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000597 }
Steven Morelandf137de92021-04-24 01:54:26 +0000598 } else {
599 ALOGE("Special command sent, but no server object attached.");
Steven Moreland5553ac42020-11-11 02:14:45 +0000600 }
601 }
602 }
603
604 if (transaction->flags & IBinder::FLAG_ONEWAY) {
605 if (replyStatus != OK) {
606 ALOGW("Oneway call failed with error: %d", replyStatus);
607 }
608
609 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
610 addr.toString().c_str());
611
612 // Check to see if there is another asynchronous transaction to process.
613 // This behavior differs from binder behavior, since in the binder
614 // driver, asynchronous transactions will be processed after existing
615 // pending binder transactions on the queue. The downside of this is
616 // that asynchronous transactions can be drowned out by synchronous
617 // transactions. However, we have no easy way to queue these
618 // transactions after the synchronous transactions we may want to read
619 // from the wire. So, in socket binder here, we have the opposite
620 // downside: asynchronous transactions may drown out synchronous
621 // transactions.
622 {
623 std::unique_lock<std::mutex> _l(mNodeMutex);
624 auto it = mNodeForAddress.find(addr);
625 // last refcount dropped after this transaction happened
626 if (it == mNodeForAddress.end()) return OK;
627
628 // note - only updated now, instead of later, so that other threads
629 // will queue any later transactions
630
631 // TODO(b/183140903): support > 2**64 async transactions
632 // (we can do this by allowing asyncNumber to wrap, since we
633 // don't expect more than 2**64 simultaneous transactions)
634 it->second.asyncNumber++;
635
636 if (it->second.asyncTodo.size() == 0) return OK;
637 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
638 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
639 it->second.asyncNumber, addr.toString().c_str());
640
641 // justification for const_cast (consider avoiding priority_queue):
642 // - AsyncTodo operator< doesn't depend on 'data' object
643 // - gotta go fast
Steven Morelande8393342021-05-05 23:27:53 +0000644 ByteVec data = std::move(
Steven Moreland5553ac42020-11-11 02:14:45 +0000645 const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top()).data);
646 it->second.asyncTodo.pop();
647 _l.unlock();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000648 return processTransactInternal(fd, session, std::move(data));
Steven Moreland5553ac42020-11-11 02:14:45 +0000649 }
650 }
651 return OK;
652 }
653
654 RpcWireReply rpcReply{
655 .status = replyStatus,
656 };
657
Steven Morelande8393342021-05-05 23:27:53 +0000658 ByteVec replyData(sizeof(RpcWireReply) + reply.dataSize());
659 if (!replyData.valid()) {
660 return NO_MEMORY;
661 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000662 memcpy(replyData.data() + 0, &rpcReply, sizeof(RpcWireReply));
663 memcpy(replyData.data() + sizeof(RpcWireReply), reply.data(), reply.dataSize());
664
665 if (replyData.size() > std::numeric_limits<uint32_t>::max()) {
666 ALOGE("Reply size too big %zu", transactionData.size());
667 terminate();
668 return BAD_VALUE;
669 }
670
671 RpcWireHeader cmdReply{
672 .command = RPC_COMMAND_REPLY,
673 .bodySize = static_cast<uint32_t>(replyData.size()),
674 };
675
676 if (!rpcSend(fd, "reply header", &cmdReply, sizeof(RpcWireHeader))) {
677 return DEAD_OBJECT;
678 }
679 if (!rpcSend(fd, "reply body", replyData.data(), replyData.size())) {
680 return DEAD_OBJECT;
681 }
682 return OK;
683}
684
685status_t RpcState::processDecStrong(const base::unique_fd& fd, const RpcWireHeader& command) {
686 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
687
Steven Morelande8393342021-05-05 23:27:53 +0000688 ByteVec commandData(command.bodySize);
689 if (!commandData.valid()) {
690 return NO_MEMORY;
691 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000692 if (!rpcRec(fd, "dec ref body", commandData.data(), commandData.size())) {
693 return DEAD_OBJECT;
694 }
695
696 if (command.bodySize < sizeof(RpcWireAddress)) {
697 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
698 sizeof(RpcWireAddress), command.bodySize);
699 terminate();
700 return BAD_VALUE;
701 }
702 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
703
704 // TODO(b/182939933): heap allocation just for lookup
705 auto addr = RpcAddress::fromRawEmbedded(address);
706 std::unique_lock<std::mutex> _l(mNodeMutex);
707 auto it = mNodeForAddress.find(addr);
708 if (it == mNodeForAddress.end()) {
709 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
710 dump();
711 return OK;
712 }
713
714 sp<IBinder> target = it->second.binder.promote();
715 if (target == nullptr) {
716 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
717 addr.toString().c_str());
718 terminate();
719 return BAD_VALUE;
720 }
721
722 if (it->second.timesSent == 0) {
723 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
724 return OK;
725 }
726
727 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
728 addr.toString().c_str());
729
730 sp<IBinder> tempHold;
731
732 it->second.timesSent--;
733 if (it->second.timesSent == 0) {
734 tempHold = it->second.sentRef;
735 it->second.sentRef = nullptr;
736
737 if (it->second.timesRecd == 0) {
738 mNodeForAddress.erase(it);
739 }
740 }
741
742 _l.unlock();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000743 tempHold = nullptr; // destructor may make binder calls on this session
Steven Moreland5553ac42020-11-11 02:14:45 +0000744
745 return OK;
746}
747
748} // namespace android