blob: 230de6f0ef8628ecbf1ec9c1777e529598dc619f [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
232bool RpcState::rpcRec(const base::unique_fd& fd, const char* what, void* data, size_t size) {
233 if (size > std::numeric_limits<ssize_t>::max()) {
234 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
235 terminate();
236 return false;
237 }
238
Steven Morelandc6ddf362021-04-02 01:13:36 +0000239 ssize_t recd = TEMP_FAILURE_RETRY(recv(fd.get(), data, size, MSG_WAITALL | MSG_NOSIGNAL));
Steven Moreland5553ac42020-11-11 02:14:45 +0000240
241 if (recd < 0 || recd != static_cast<ssize_t>(size)) {
242 terminate();
243
244 if (recd == 0 && errno == 0) {
245 LOG_RPC_DETAIL("No more data when trying to read %s on fd %d", what, fd.get());
246 return false;
247 }
248
249 ALOGE("Failed to read %s (received %zd of %zu bytes) on fd %d, error: %s", what, recd, size,
250 fd.get(), strerror(errno));
251 return false;
252 } else {
253 LOG_RPC_DETAIL("Received %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
254 }
255
256 return true;
257}
258
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000259sp<IBinder> RpcState::getRootObject(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000260 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000261 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000262 Parcel reply;
263
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000264 status_t status = transact(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT, data, session,
265 &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000266 if (status != OK) {
267 ALOGE("Error getting root object: %s", statusToString(status).c_str());
268 return nullptr;
269 }
270
271 return reply.readStrongBinder();
272}
273
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000274status_t RpcState::getMaxThreads(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000275 size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000276 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000277 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000278 Parcel reply;
279
280 status_t status = transact(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000281 session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000282 if (status != OK) {
283 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
284 return status;
285 }
286
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000287 int32_t maxThreads;
288 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000289 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000290 if (maxThreads <= 0) {
291 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000292 return BAD_VALUE;
293 }
294
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000295 *maxThreadsOut = maxThreads;
296 return OK;
297}
298
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000299status_t RpcState::getSessionId(const base::unique_fd& fd, const sp<RpcSession>& session,
300 int32_t* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000301 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000302 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000303 Parcel reply;
304
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000305 status_t status = transact(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_SESSION_ID, data,
306 session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000307 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000308 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000309 return status;
310 }
311
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000312 int32_t sessionId;
313 status = reply.readInt32(&sessionId);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000314 if (status != OK) return status;
315
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000316 *sessionIdOut = sessionId;
Steven Morelandf137de92021-04-24 01:54:26 +0000317 return OK;
318}
319
Steven Moreland5553ac42020-11-11 02:14:45 +0000320status_t RpcState::transact(const base::unique_fd& fd, const RpcAddress& address, uint32_t code,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000321 const Parcel& data, const sp<RpcSession>& session, Parcel* reply,
Steven Moreland5553ac42020-11-11 02:14:45 +0000322 uint32_t flags) {
323 uint64_t asyncNumber = 0;
324
325 if (!address.isZero()) {
326 std::lock_guard<std::mutex> _l(mNodeMutex);
327 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
328 auto it = mNodeForAddress.find(address);
329 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
330 address.toString().c_str());
331
332 if (flags & IBinder::FLAG_ONEWAY) {
333 asyncNumber = it->second.asyncNumber++;
334 }
335 }
336
337 if (!data.isForRpc()) {
338 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
339 return BAD_TYPE;
340 }
341
342 if (data.objectsCount() != 0) {
343 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
344 return BAD_TYPE;
345 }
346
347 RpcWireTransaction transaction{
348 .address = address.viewRawEmbedded(),
349 .code = code,
350 .flags = flags,
351 .asyncNumber = asyncNumber,
352 };
353
Steven Morelanddbe71832021-05-12 23:31:00 +0000354 CommandData transactionData(sizeof(RpcWireTransaction) + data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000355 if (!transactionData.valid()) {
356 return NO_MEMORY;
357 }
358
Steven Moreland5553ac42020-11-11 02:14:45 +0000359 memcpy(transactionData.data() + 0, &transaction, sizeof(RpcWireTransaction));
360 memcpy(transactionData.data() + sizeof(RpcWireTransaction), data.data(), data.dataSize());
361
362 if (transactionData.size() > std::numeric_limits<uint32_t>::max()) {
363 ALOGE("Transaction size too big %zu", transactionData.size());
364 return BAD_VALUE;
365 }
366
367 RpcWireHeader command{
368 .command = RPC_COMMAND_TRANSACT,
369 .bodySize = static_cast<uint32_t>(transactionData.size()),
370 };
371
372 if (!rpcSend(fd, "transact header", &command, sizeof(command))) {
373 return DEAD_OBJECT;
374 }
375 if (!rpcSend(fd, "command body", transactionData.data(), transactionData.size())) {
376 return DEAD_OBJECT;
377 }
378
379 if (flags & IBinder::FLAG_ONEWAY) {
380 return OK; // do not wait for result
381 }
382
383 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
384
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000385 return waitForReply(fd, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000386}
387
Steven Moreland438cce82021-04-02 18:04:08 +0000388static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
389 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000390 (void)p;
391 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
392 (void)dataSize;
393 LOG_ALWAYS_FATAL_IF(objects != nullptr);
394 LOG_ALWAYS_FATAL_IF(objectsCount, 0);
395}
396
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000397status_t RpcState::waitForReply(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000398 Parcel* reply) {
399 RpcWireHeader command;
400 while (true) {
401 if (!rpcRec(fd, "command header", &command, sizeof(command))) {
402 return DEAD_OBJECT;
403 }
404
405 if (command.command == RPC_COMMAND_REPLY) break;
406
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000407 status_t status = processServerCommand(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000408 if (status != OK) return status;
409 }
410
Steven Morelanddbe71832021-05-12 23:31:00 +0000411 CommandData data(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000412 if (!data.valid()) {
413 return NO_MEMORY;
414 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000415
Steven Morelande8393342021-05-05 23:27:53 +0000416 if (!rpcRec(fd, "reply body", data.data(), command.bodySize)) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000417 return DEAD_OBJECT;
418 }
419
420 if (command.bodySize < sizeof(RpcWireReply)) {
421 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
422 sizeof(RpcWireReply), command.bodySize);
423 terminate();
424 return BAD_VALUE;
425 }
Steven Morelande8393342021-05-05 23:27:53 +0000426 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000427 if (rpcReply->status != OK) return rpcReply->status;
428
Steven Morelande8393342021-05-05 23:27:53 +0000429 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000430 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000431 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000432
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000433 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000434
435 return OK;
436}
437
438status_t RpcState::sendDecStrong(const base::unique_fd& fd, const RpcAddress& addr) {
439 {
440 std::lock_guard<std::mutex> _l(mNodeMutex);
441 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
442 auto it = mNodeForAddress.find(addr);
443 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
444 addr.toString().c_str());
445 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
446 addr.toString().c_str());
447
448 it->second.timesRecd--;
449 if (it->second.timesRecd == 0 && it->second.timesSent == 0) {
450 mNodeForAddress.erase(it);
451 }
452 }
453
454 RpcWireHeader cmd = {
455 .command = RPC_COMMAND_DEC_STRONG,
456 .bodySize = sizeof(RpcWireAddress),
457 };
458 if (!rpcSend(fd, "dec ref header", &cmd, sizeof(cmd))) return DEAD_OBJECT;
459 if (!rpcSend(fd, "dec ref body", &addr.viewRawEmbedded(), sizeof(RpcWireAddress)))
460 return DEAD_OBJECT;
461 return OK;
462}
463
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000464status_t RpcState::getAndExecuteCommand(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000465 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", fd.get());
466
467 RpcWireHeader command;
468 if (!rpcRec(fd, "command header", &command, sizeof(command))) {
469 return DEAD_OBJECT;
470 }
471
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000472 return processServerCommand(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000473}
474
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000475status_t RpcState::processServerCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000476 const RpcWireHeader& command) {
Steven Morelandd7302072021-05-15 01:32:04 +0000477 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
478 IPCThreadState::SpGuard spGuard{
479 .address = __builtin_frame_address(0),
480 .context = "processing binder RPC command",
481 };
482 const IPCThreadState::SpGuard* origGuard;
483 if (kernelBinderState != nullptr) {
484 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
485 }
486 ScopeGuard guardUnguard = [&]() {
487 if (kernelBinderState != nullptr) {
488 kernelBinderState->restoreGetCallingSpGuard(origGuard);
489 }
490 };
491
Steven Moreland5553ac42020-11-11 02:14:45 +0000492 switch (command.command) {
493 case RPC_COMMAND_TRANSACT:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000494 return processTransact(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000495 case RPC_COMMAND_DEC_STRONG:
496 return processDecStrong(fd, command);
497 }
498
499 // We should always know the version of the opposing side, and since the
500 // RPC-binder-level wire protocol is not self synchronizing, we have no way
501 // to understand where the current command ends and the next one begins. We
502 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000503 // to kill us, so ending the session for misbehaving client.
504 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000505 terminate();
506 return DEAD_OBJECT;
507}
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000508status_t RpcState::processTransact(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000509 const RpcWireHeader& command) {
510 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
511
Steven Morelanddbe71832021-05-12 23:31:00 +0000512 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000513 if (!transactionData.valid()) {
514 return NO_MEMORY;
515 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000516 if (!rpcRec(fd, "transaction body", transactionData.data(), transactionData.size())) {
517 return DEAD_OBJECT;
518 }
519
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000520 return processTransactInternal(fd, session, std::move(transactionData));
Steven Moreland5553ac42020-11-11 02:14:45 +0000521}
522
Steven Moreland438cce82021-04-02 18:04:08 +0000523static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
524 const binder_size_t* objects, size_t objectsCount) {
525 (void)p;
526 (void)data;
527 (void)dataSize;
528 (void)objects;
529 (void)objectsCount;
530}
531
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000532status_t RpcState::processTransactInternal(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Morelanddbe71832021-05-12 23:31:00 +0000533 CommandData transactionData) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000534 if (transactionData.size() < sizeof(RpcWireTransaction)) {
535 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
536 sizeof(RpcWireTransaction), transactionData.size());
537 terminate();
538 return BAD_VALUE;
539 }
540 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
541
542 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
543 // maybe add an RpcAddress 'view' if the type remains 'heavy'
544 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
545
546 status_t replyStatus = OK;
547 sp<IBinder> target;
548 if (!addr.isZero()) {
549 std::lock_guard<std::mutex> _l(mNodeMutex);
550
551 auto it = mNodeForAddress.find(addr);
552 if (it == mNodeForAddress.end()) {
553 ALOGE("Unknown binder address %s.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000554 replyStatus = BAD_VALUE;
555 } else {
556 target = it->second.binder.promote();
557 if (target == nullptr) {
558 // This can happen if the binder is remote in this process, and
559 // another thread has called the last decStrong on this binder.
560 // However, for local binders, it indicates a misbehaving client
561 // (any binder which is being transacted on should be holding a
562 // strong ref count), so in either case, terminating the
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000563 // session.
Steven Moreland5553ac42020-11-11 02:14:45 +0000564 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
565 addr.toString().c_str());
566 terminate();
567 replyStatus = BAD_VALUE;
568 } else if (target->localBinder() == nullptr) {
569 ALOGE("Transactions can only go to local binders, not address %s. Terminating!",
570 addr.toString().c_str());
571 terminate();
572 replyStatus = BAD_VALUE;
573 } else if (transaction->flags & IBinder::FLAG_ONEWAY) {
574 if (transaction->asyncNumber != it->second.asyncNumber) {
575 // we need to process some other asynchronous transaction
576 // first
577 // TODO(b/183140903): limit enqueues/detect overfill for bad client
578 // TODO(b/183140903): detect when an object is deleted when it still has
579 // pending async transactions
580 it->second.asyncTodo.push(BinderNode::AsyncTodo{
581 .data = std::move(transactionData),
582 .asyncNumber = transaction->asyncNumber,
583 });
584 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s", transaction->asyncNumber,
585 addr.toString().c_str());
586 return OK;
587 }
588 }
589 }
590 }
591
Steven Moreland5553ac42020-11-11 02:14:45 +0000592 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000593 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000594
595 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000596 Parcel data;
597 // transaction->data is owned by this function. Parcel borrows this data and
598 // only holds onto it for the duration of this function call. Parcel will be
599 // deleted before the 'transactionData' object.
600 data.ipcSetDataReference(transaction->data,
601 transactionData.size() - offsetof(RpcWireTransaction, data),
602 nullptr /*object*/, 0 /*objectCount*/,
603 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000604 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000605
Steven Moreland5553ac42020-11-11 02:14:45 +0000606 if (target) {
607 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
608 } else {
609 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000610
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000611 sp<RpcServer> server = session->server().promote();
Steven Morelandf137de92021-04-24 01:54:26 +0000612 if (server) {
613 // special case for 'zero' address (special server commands)
614 switch (transaction->code) {
615 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
616 replyStatus = reply.writeStrongBinder(server->getRootObject());
617 break;
618 }
619 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
620 replyStatus = reply.writeInt32(server->getMaxThreads());
621 break;
622 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000623 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
624 // only sessions w/ services can be the source of a
625 // session ID (so still guarded by non-null server)
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000626 //
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000627 // sessions associated with servers must have an ID
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000628 // (hence abort)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000629 int32_t id = session->getPrivateAccessorForId().get().value();
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000630 replyStatus = reply.writeInt32(id);
631 break;
632 }
Steven Morelandf137de92021-04-24 01:54:26 +0000633 default: {
634 replyStatus = UNKNOWN_TRANSACTION;
635 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000636 }
Steven Morelandf137de92021-04-24 01:54:26 +0000637 } else {
638 ALOGE("Special command sent, but no server object attached.");
Steven Moreland5553ac42020-11-11 02:14:45 +0000639 }
640 }
641 }
642
643 if (transaction->flags & IBinder::FLAG_ONEWAY) {
644 if (replyStatus != OK) {
645 ALOGW("Oneway call failed with error: %d", replyStatus);
646 }
647
648 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
649 addr.toString().c_str());
650
651 // Check to see if there is another asynchronous transaction to process.
652 // This behavior differs from binder behavior, since in the binder
653 // driver, asynchronous transactions will be processed after existing
654 // pending binder transactions on the queue. The downside of this is
655 // that asynchronous transactions can be drowned out by synchronous
656 // transactions. However, we have no easy way to queue these
657 // transactions after the synchronous transactions we may want to read
658 // from the wire. So, in socket binder here, we have the opposite
659 // downside: asynchronous transactions may drown out synchronous
660 // transactions.
661 {
662 std::unique_lock<std::mutex> _l(mNodeMutex);
663 auto it = mNodeForAddress.find(addr);
664 // last refcount dropped after this transaction happened
665 if (it == mNodeForAddress.end()) return OK;
666
667 // note - only updated now, instead of later, so that other threads
668 // will queue any later transactions
669
670 // TODO(b/183140903): support > 2**64 async transactions
671 // (we can do this by allowing asyncNumber to wrap, since we
672 // don't expect more than 2**64 simultaneous transactions)
673 it->second.asyncNumber++;
674
675 if (it->second.asyncTodo.size() == 0) return OK;
676 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
677 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
678 it->second.asyncNumber, addr.toString().c_str());
679
680 // justification for const_cast (consider avoiding priority_queue):
681 // - AsyncTodo operator< doesn't depend on 'data' object
682 // - gotta go fast
Steven Morelanddbe71832021-05-12 23:31:00 +0000683 CommandData data = std::move(
Steven Moreland5553ac42020-11-11 02:14:45 +0000684 const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top()).data);
685 it->second.asyncTodo.pop();
686 _l.unlock();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000687 return processTransactInternal(fd, session, std::move(data));
Steven Moreland5553ac42020-11-11 02:14:45 +0000688 }
689 }
690 return OK;
691 }
692
693 RpcWireReply rpcReply{
694 .status = replyStatus,
695 };
696
Steven Morelanddbe71832021-05-12 23:31:00 +0000697 CommandData replyData(sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000698 if (!replyData.valid()) {
699 return NO_MEMORY;
700 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000701 memcpy(replyData.data() + 0, &rpcReply, sizeof(RpcWireReply));
702 memcpy(replyData.data() + sizeof(RpcWireReply), reply.data(), reply.dataSize());
703
704 if (replyData.size() > std::numeric_limits<uint32_t>::max()) {
705 ALOGE("Reply size too big %zu", transactionData.size());
706 terminate();
707 return BAD_VALUE;
708 }
709
710 RpcWireHeader cmdReply{
711 .command = RPC_COMMAND_REPLY,
712 .bodySize = static_cast<uint32_t>(replyData.size()),
713 };
714
715 if (!rpcSend(fd, "reply header", &cmdReply, sizeof(RpcWireHeader))) {
716 return DEAD_OBJECT;
717 }
718 if (!rpcSend(fd, "reply body", replyData.data(), replyData.size())) {
719 return DEAD_OBJECT;
720 }
721 return OK;
722}
723
724status_t RpcState::processDecStrong(const base::unique_fd& fd, const RpcWireHeader& command) {
725 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
726
Steven Morelanddbe71832021-05-12 23:31:00 +0000727 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000728 if (!commandData.valid()) {
729 return NO_MEMORY;
730 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000731 if (!rpcRec(fd, "dec ref body", commandData.data(), commandData.size())) {
732 return DEAD_OBJECT;
733 }
734
735 if (command.bodySize < sizeof(RpcWireAddress)) {
736 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
737 sizeof(RpcWireAddress), command.bodySize);
738 terminate();
739 return BAD_VALUE;
740 }
741 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
742
743 // TODO(b/182939933): heap allocation just for lookup
744 auto addr = RpcAddress::fromRawEmbedded(address);
745 std::unique_lock<std::mutex> _l(mNodeMutex);
746 auto it = mNodeForAddress.find(addr);
747 if (it == mNodeForAddress.end()) {
748 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000749 return OK;
750 }
751
752 sp<IBinder> target = it->second.binder.promote();
753 if (target == nullptr) {
754 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
755 addr.toString().c_str());
756 terminate();
757 return BAD_VALUE;
758 }
759
760 if (it->second.timesSent == 0) {
761 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
762 return OK;
763 }
764
765 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
766 addr.toString().c_str());
767
768 sp<IBinder> tempHold;
769
770 it->second.timesSent--;
771 if (it->second.timesSent == 0) {
772 tempHold = it->second.sentRef;
773 it->second.sentRef = nullptr;
774
775 if (it->second.timesRecd == 0) {
776 mNodeForAddress.erase(it);
777 }
778 }
779
780 _l.unlock();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000781 tempHold = nullptr; // destructor may make binder calls on this session
Steven Moreland5553ac42020-11-11 02:14:45 +0000782
783 return OK;
784}
785
786} // namespace android