blob: a8017296fa24082e5b8804631541bd18f45321b6 [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 Moreland1e4c2b82021-05-25 01:51:31 +0000210status_t RpcState::rpcSend(const base::unique_fd& fd, const char* what, const void* data,
211 size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000212 LOG_RPC_DETAIL("Sending %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
213
214 if (size > std::numeric_limits<ssize_t>::max()) {
215 ALOGE("Cannot send %s at size %zu (too big)", what, size);
216 terminate();
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000217 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000218 }
219
Steven Morelandc6ddf362021-04-02 01:13:36 +0000220 ssize_t sent = TEMP_FAILURE_RETRY(send(fd.get(), data, size, MSG_NOSIGNAL));
Steven Moreland5553ac42020-11-11 02:14:45 +0000221
222 if (sent < 0 || sent != static_cast<ssize_t>(size)) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000223 int savedErrno = errno;
Steven Moreland5553ac42020-11-11 02:14:45 +0000224 ALOGE("Failed to send %s (sent %zd of %zu bytes) on fd %d, error: %s", what, sent, size,
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000225 fd.get(), strerror(savedErrno));
Steven Moreland5553ac42020-11-11 02:14:45 +0000226
227 terminate();
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000228 return -savedErrno;
Steven Moreland5553ac42020-11-11 02:14:45 +0000229 }
230
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000231 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000232}
233
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000234status_t RpcState::rpcRec(const base::unique_fd& fd, const sp<RpcSession>& session,
235 const char* what, void* data, size_t size) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000236 if (size > std::numeric_limits<ssize_t>::max()) {
237 ALOGE("Cannot rec %s at size %zu (too big)", what, size);
238 terminate();
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000239 return BAD_VALUE;
Steven Moreland5553ac42020-11-11 02:14:45 +0000240 }
241
Steven Morelandee3f4662021-05-22 01:07:33 +0000242 if (status_t status = session->mShutdownTrigger->interruptableReadFully(fd.get(), data, size);
243 status != OK) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000244 if (status != -ECANCELED) {
245 ALOGE("Failed to read %s (%zu bytes) on fd %d, error: %s", what, size, fd.get(),
246 statusToString(status).c_str());
247 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000248 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000249 }
250
Steven Morelandee3f4662021-05-22 01:07:33 +0000251 LOG_RPC_DETAIL("Received %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000252 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000253}
254
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000255sp<IBinder> RpcState::getRootObject(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000256 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000257 data.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000258 Parcel reply;
259
Steven Morelandf5174272021-05-25 00:39:28 +0000260 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_ROOT, data,
261 session, &reply, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000262 if (status != OK) {
263 ALOGE("Error getting root object: %s", statusToString(status).c_str());
264 return nullptr;
265 }
266
267 return reply.readStrongBinder();
268}
269
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000270status_t RpcState::getMaxThreads(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000271 size_t* maxThreadsOut) {
Steven Morelandf137de92021-04-24 01:54:26 +0000272 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000273 data.markForRpc(session);
Steven Morelandf137de92021-04-24 01:54:26 +0000274 Parcel reply;
275
Steven Morelandf5174272021-05-25 00:39:28 +0000276 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_MAX_THREADS,
277 data, session, &reply, 0);
Steven Morelandf137de92021-04-24 01:54:26 +0000278 if (status != OK) {
279 ALOGE("Error getting max threads: %s", statusToString(status).c_str());
280 return status;
281 }
282
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000283 int32_t maxThreads;
284 status = reply.readInt32(&maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000285 if (status != OK) return status;
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000286 if (maxThreads <= 0) {
287 ALOGE("Error invalid max maxThreads: %d", maxThreads);
Steven Morelandf137de92021-04-24 01:54:26 +0000288 return BAD_VALUE;
289 }
290
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000291 *maxThreadsOut = maxThreads;
292 return OK;
293}
294
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000295status_t RpcState::getSessionId(const base::unique_fd& fd, const sp<RpcSession>& session,
296 int32_t* sessionIdOut) {
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000297 Parcel data;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000298 data.markForRpc(session);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000299 Parcel reply;
300
Steven Morelandf5174272021-05-25 00:39:28 +0000301 status_t status = transactAddress(fd, RpcAddress::zero(), RPC_SPECIAL_TRANSACT_GET_SESSION_ID,
302 data, session, &reply, 0);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000303 if (status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000304 ALOGE("Error getting session ID: %s", statusToString(status).c_str());
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000305 return status;
306 }
307
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000308 int32_t sessionId;
309 status = reply.readInt32(&sessionId);
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000310 if (status != OK) return status;
311
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000312 *sessionIdOut = sessionId;
Steven Morelandf137de92021-04-24 01:54:26 +0000313 return OK;
314}
315
Steven Morelandf5174272021-05-25 00:39:28 +0000316status_t RpcState::transact(const base::unique_fd& fd, const sp<IBinder>& binder, uint32_t code,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000317 const Parcel& data, const sp<RpcSession>& session, Parcel* reply,
Steven Moreland5553ac42020-11-11 02:14:45 +0000318 uint32_t flags) {
Steven Morelandf5174272021-05-25 00:39:28 +0000319 if (!data.isForRpc()) {
320 ALOGE("Refusing to send RPC with parcel not crafted for RPC");
321 return BAD_TYPE;
322 }
323
324 if (data.objectsCount() != 0) {
325 ALOGE("Parcel at %p has attached objects but is being used in an RPC call", &data);
326 return BAD_TYPE;
327 }
328
329 RpcAddress address = RpcAddress::zero();
330 if (status_t status = onBinderLeaving(session, binder, &address); status != OK) return status;
331
332 return transactAddress(fd, address, code, data, session, reply, flags);
333}
334
335status_t RpcState::transactAddress(const base::unique_fd& fd, const RpcAddress& address,
336 uint32_t code, const Parcel& data, const sp<RpcSession>& session,
337 Parcel* reply, uint32_t flags) {
338 LOG_ALWAYS_FATAL_IF(!data.isForRpc());
339 LOG_ALWAYS_FATAL_IF(data.objectsCount() != 0);
340
Steven Moreland5553ac42020-11-11 02:14:45 +0000341 uint64_t asyncNumber = 0;
342
343 if (!address.isZero()) {
344 std::lock_guard<std::mutex> _l(mNodeMutex);
345 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
346 auto it = mNodeForAddress.find(address);
347 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending transact on unknown address %s",
348 address.toString().c_str());
349
350 if (flags & IBinder::FLAG_ONEWAY) {
351 asyncNumber = it->second.asyncNumber++;
352 }
353 }
354
Steven Moreland5553ac42020-11-11 02:14:45 +0000355 RpcWireTransaction transaction{
356 .address = address.viewRawEmbedded(),
357 .code = code,
358 .flags = flags,
359 .asyncNumber = asyncNumber,
360 };
361
Steven Morelanddbe71832021-05-12 23:31:00 +0000362 CommandData transactionData(sizeof(RpcWireTransaction) + data.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000363 if (!transactionData.valid()) {
364 return NO_MEMORY;
365 }
366
Steven Moreland5553ac42020-11-11 02:14:45 +0000367 memcpy(transactionData.data() + 0, &transaction, sizeof(RpcWireTransaction));
368 memcpy(transactionData.data() + sizeof(RpcWireTransaction), data.data(), data.dataSize());
369
370 if (transactionData.size() > std::numeric_limits<uint32_t>::max()) {
371 ALOGE("Transaction size too big %zu", transactionData.size());
372 return BAD_VALUE;
373 }
374
375 RpcWireHeader command{
376 .command = RPC_COMMAND_TRANSACT,
377 .bodySize = static_cast<uint32_t>(transactionData.size()),
378 };
379
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000380 if (status_t status = rpcSend(fd, "transact header", &command, sizeof(command)); status != OK)
381 return status;
382 if (status_t status =
383 rpcSend(fd, "command body", transactionData.data(), transactionData.size());
384 status != OK)
385 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000386
387 if (flags & IBinder::FLAG_ONEWAY) {
388 return OK; // do not wait for result
389 }
390
391 LOG_ALWAYS_FATAL_IF(reply == nullptr, "Reply parcel must be used for synchronous transaction.");
392
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000393 return waitForReply(fd, session, reply);
Steven Moreland5553ac42020-11-11 02:14:45 +0000394}
395
Steven Moreland438cce82021-04-02 18:04:08 +0000396static void cleanup_reply_data(Parcel* p, const uint8_t* data, size_t dataSize,
397 const binder_size_t* objects, size_t objectsCount) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000398 (void)p;
399 delete[] const_cast<uint8_t*>(data - offsetof(RpcWireReply, data));
400 (void)dataSize;
401 LOG_ALWAYS_FATAL_IF(objects != nullptr);
402 LOG_ALWAYS_FATAL_IF(objectsCount, 0);
403}
404
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000405status_t RpcState::waitForReply(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000406 Parcel* reply) {
407 RpcWireHeader command;
408 while (true) {
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000409 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
410 status != OK)
411 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000412
413 if (command.command == RPC_COMMAND_REPLY) break;
414
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000415 if (status_t status = processServerCommand(fd, session, command); status != OK)
416 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000417 }
418
Steven Morelanddbe71832021-05-12 23:31:00 +0000419 CommandData data(command.bodySize);
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000420 if (!data.valid()) return NO_MEMORY;
Steven Moreland5553ac42020-11-11 02:14:45 +0000421
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000422 if (status_t status = rpcRec(fd, session, "reply body", data.data(), command.bodySize);
423 status != OK)
424 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000425
426 if (command.bodySize < sizeof(RpcWireReply)) {
427 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireReply. Terminating!",
428 sizeof(RpcWireReply), command.bodySize);
429 terminate();
430 return BAD_VALUE;
431 }
Steven Morelande8393342021-05-05 23:27:53 +0000432 RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
Steven Moreland5553ac42020-11-11 02:14:45 +0000433 if (rpcReply->status != OK) return rpcReply->status;
434
Steven Morelande8393342021-05-05 23:27:53 +0000435 data.release();
Steven Moreland5553ac42020-11-11 02:14:45 +0000436 reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
Steven Moreland438cce82021-04-02 18:04:08 +0000437 nullptr, 0, cleanup_reply_data);
Steven Moreland5553ac42020-11-11 02:14:45 +0000438
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000439 reply->markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000440
441 return OK;
442}
443
444status_t RpcState::sendDecStrong(const base::unique_fd& fd, const RpcAddress& addr) {
445 {
446 std::lock_guard<std::mutex> _l(mNodeMutex);
447 if (mTerminated) return DEAD_OBJECT; // avoid fatal only, otherwise races
448 auto it = mNodeForAddress.find(addr);
449 LOG_ALWAYS_FATAL_IF(it == mNodeForAddress.end(), "Sending dec strong on unknown address %s",
450 addr.toString().c_str());
451 LOG_ALWAYS_FATAL_IF(it->second.timesRecd <= 0, "Bad dec strong %s",
452 addr.toString().c_str());
453
454 it->second.timesRecd--;
455 if (it->second.timesRecd == 0 && it->second.timesSent == 0) {
456 mNodeForAddress.erase(it);
457 }
458 }
459
460 RpcWireHeader cmd = {
461 .command = RPC_COMMAND_DEC_STRONG,
462 .bodySize = sizeof(RpcWireAddress),
463 };
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000464 if (status_t status = rpcSend(fd, "dec ref header", &cmd, sizeof(cmd)); status != OK)
465 return status;
466 if (status_t status =
467 rpcSend(fd, "dec ref body", &addr.viewRawEmbedded(), sizeof(RpcWireAddress));
468 status != OK)
469 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000470 return OK;
471}
472
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000473status_t RpcState::getAndExecuteCommand(const base::unique_fd& fd, const sp<RpcSession>& session) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000474 LOG_RPC_DETAIL("getAndExecuteCommand on fd %d", fd.get());
475
476 RpcWireHeader command;
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000477 if (status_t status = rpcRec(fd, session, "command header", &command, sizeof(command));
478 status != OK)
479 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000480
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000481 return processServerCommand(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000482}
483
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000484status_t RpcState::processServerCommand(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000485 const RpcWireHeader& command) {
Steven Morelandd7302072021-05-15 01:32:04 +0000486 IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
487 IPCThreadState::SpGuard spGuard{
488 .address = __builtin_frame_address(0),
489 .context = "processing binder RPC command",
490 };
491 const IPCThreadState::SpGuard* origGuard;
492 if (kernelBinderState != nullptr) {
493 origGuard = kernelBinderState->pushGetCallingSpGuard(&spGuard);
494 }
495 ScopeGuard guardUnguard = [&]() {
496 if (kernelBinderState != nullptr) {
497 kernelBinderState->restoreGetCallingSpGuard(origGuard);
498 }
499 };
500
Steven Moreland5553ac42020-11-11 02:14:45 +0000501 switch (command.command) {
502 case RPC_COMMAND_TRANSACT:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000503 return processTransact(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000504 case RPC_COMMAND_DEC_STRONG:
Steven Morelandee3f4662021-05-22 01:07:33 +0000505 return processDecStrong(fd, session, command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000506 }
507
508 // We should always know the version of the opposing side, and since the
509 // RPC-binder-level wire protocol is not self synchronizing, we have no way
510 // to understand where the current command ends and the next one begins. We
511 // also can't consider it a fatal error because this would allow any client
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000512 // to kill us, so ending the session for misbehaving client.
513 ALOGE("Unknown RPC command %d - terminating session", command.command);
Steven Moreland5553ac42020-11-11 02:14:45 +0000514 terminate();
515 return DEAD_OBJECT;
516}
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000517status_t RpcState::processTransact(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Moreland5553ac42020-11-11 02:14:45 +0000518 const RpcWireHeader& command) {
519 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
520
Steven Morelanddbe71832021-05-12 23:31:00 +0000521 CommandData transactionData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000522 if (!transactionData.valid()) {
523 return NO_MEMORY;
524 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000525 if (status_t status = rpcRec(fd, session, "transaction body", transactionData.data(),
526 transactionData.size());
527 status != OK)
528 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000529
Steven Morelandf5174272021-05-25 00:39:28 +0000530 return processTransactInternal(fd, session, std::move(transactionData), nullptr /*targetRef*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000531}
532
Steven Moreland438cce82021-04-02 18:04:08 +0000533static void do_nothing_to_transact_data(Parcel* p, const uint8_t* data, size_t dataSize,
534 const binder_size_t* objects, size_t objectsCount) {
535 (void)p;
536 (void)data;
537 (void)dataSize;
538 (void)objects;
539 (void)objectsCount;
540}
541
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000542status_t RpcState::processTransactInternal(const base::unique_fd& fd, const sp<RpcSession>& session,
Steven Morelandf5174272021-05-25 00:39:28 +0000543 CommandData transactionData, sp<IBinder>&& targetRef) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000544 if (transactionData.size() < sizeof(RpcWireTransaction)) {
545 ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
546 sizeof(RpcWireTransaction), transactionData.size());
547 terminate();
548 return BAD_VALUE;
549 }
550 RpcWireTransaction* transaction = reinterpret_cast<RpcWireTransaction*>(transactionData.data());
551
552 // TODO(b/182939933): heap allocation just for lookup in mNodeForAddress,
553 // maybe add an RpcAddress 'view' if the type remains 'heavy'
554 auto addr = RpcAddress::fromRawEmbedded(&transaction->address);
555
556 status_t replyStatus = OK;
557 sp<IBinder> target;
558 if (!addr.isZero()) {
Steven Morelandf5174272021-05-25 00:39:28 +0000559 if (!targetRef) {
560 target = onBinderEntering(session, addr);
Steven Moreland5553ac42020-11-11 02:14:45 +0000561 } else {
Steven Morelandf5174272021-05-25 00:39:28 +0000562 target = targetRef;
563 }
564
565 if (target == nullptr) {
566 // This can happen if the binder is remote in this process, and
567 // another thread has called the last decStrong on this binder.
568 // However, for local binders, it indicates a misbehaving client
569 // (any binder which is being transacted on should be holding a
570 // strong ref count), so in either case, terminating the
571 // session.
572 ALOGE("While transacting, binder has been deleted at address %s. Terminating!",
573 addr.toString().c_str());
574 terminate();
575 replyStatus = BAD_VALUE;
576 } else if (target->localBinder() == nullptr) {
577 ALOGE("Unknown binder address or non-local binder, not address %s. Terminating!",
578 addr.toString().c_str());
579 terminate();
580 replyStatus = BAD_VALUE;
581 } else if (transaction->flags & IBinder::FLAG_ONEWAY) {
582 std::lock_guard<std::mutex> _l(mNodeMutex);
583 auto it = mNodeForAddress.find(addr);
584 if (it->second.binder.promote() != target) {
585 ALOGE("Binder became invalid during transaction. Bad client? %s",
Steven Moreland5553ac42020-11-11 02:14:45 +0000586 addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000587 replyStatus = BAD_VALUE;
Steven Morelandf5174272021-05-25 00:39:28 +0000588 } else if (transaction->asyncNumber != it->second.asyncNumber) {
589 // we need to process some other asynchronous transaction
590 // first
591 // TODO(b/183140903): limit enqueues/detect overfill for bad client
592 // TODO(b/183140903): detect when an object is deleted when it still has
593 // pending async transactions
594 it->second.asyncTodo.push(BinderNode::AsyncTodo{
595 .ref = target,
596 .data = std::move(transactionData),
597 .asyncNumber = transaction->asyncNumber,
598 });
599 LOG_RPC_DETAIL("Enqueuing %" PRId64 " on %s", transaction->asyncNumber,
600 addr.toString().c_str());
601 return OK;
Steven Moreland5553ac42020-11-11 02:14:45 +0000602 }
603 }
604 }
605
Steven Moreland5553ac42020-11-11 02:14:45 +0000606 Parcel reply;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000607 reply.markForRpc(session);
Steven Moreland5553ac42020-11-11 02:14:45 +0000608
609 if (replyStatus == OK) {
Steven Morelandeff77c12021-04-15 00:37:19 +0000610 Parcel data;
611 // transaction->data is owned by this function. Parcel borrows this data and
612 // only holds onto it for the duration of this function call. Parcel will be
613 // deleted before the 'transactionData' object.
614 data.ipcSetDataReference(transaction->data,
615 transactionData.size() - offsetof(RpcWireTransaction, data),
616 nullptr /*object*/, 0 /*objectCount*/,
617 do_nothing_to_transact_data);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000618 data.markForRpc(session);
Steven Morelandeff77c12021-04-15 00:37:19 +0000619
Steven Moreland5553ac42020-11-11 02:14:45 +0000620 if (target) {
621 replyStatus = target->transact(transaction->code, data, &reply, transaction->flags);
622 } else {
623 LOG_RPC_DETAIL("Got special transaction %u", transaction->code);
Steven Moreland5553ac42020-11-11 02:14:45 +0000624
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000625 sp<RpcServer> server = session->server().promote();
Steven Morelandf137de92021-04-24 01:54:26 +0000626 if (server) {
627 // special case for 'zero' address (special server commands)
628 switch (transaction->code) {
629 case RPC_SPECIAL_TRANSACT_GET_ROOT: {
630 replyStatus = reply.writeStrongBinder(server->getRootObject());
631 break;
632 }
633 case RPC_SPECIAL_TRANSACT_GET_MAX_THREADS: {
634 replyStatus = reply.writeInt32(server->getMaxThreads());
635 break;
636 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000637 case RPC_SPECIAL_TRANSACT_GET_SESSION_ID: {
638 // only sessions w/ services can be the source of a
639 // session ID (so still guarded by non-null server)
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000640 //
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000641 // sessions associated with servers must have an ID
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000642 // (hence abort)
Steven Morelandee3f4662021-05-22 01:07:33 +0000643 int32_t id = session->mId.value();
Steven Moreland7c5e6c22021-05-01 02:55:20 +0000644 replyStatus = reply.writeInt32(id);
645 break;
646 }
Steven Morelandf137de92021-04-24 01:54:26 +0000647 default: {
648 replyStatus = UNKNOWN_TRANSACTION;
649 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000650 }
Steven Morelandf137de92021-04-24 01:54:26 +0000651 } else {
652 ALOGE("Special command sent, but no server object attached.");
Steven Moreland5553ac42020-11-11 02:14:45 +0000653 }
654 }
655 }
656
657 if (transaction->flags & IBinder::FLAG_ONEWAY) {
658 if (replyStatus != OK) {
659 ALOGW("Oneway call failed with error: %d", replyStatus);
660 }
661
662 LOG_RPC_DETAIL("Processed async transaction %" PRId64 " on %s", transaction->asyncNumber,
663 addr.toString().c_str());
664
665 // Check to see if there is another asynchronous transaction to process.
666 // This behavior differs from binder behavior, since in the binder
667 // driver, asynchronous transactions will be processed after existing
668 // pending binder transactions on the queue. The downside of this is
669 // that asynchronous transactions can be drowned out by synchronous
670 // transactions. However, we have no easy way to queue these
671 // transactions after the synchronous transactions we may want to read
672 // from the wire. So, in socket binder here, we have the opposite
673 // downside: asynchronous transactions may drown out synchronous
674 // transactions.
675 {
676 std::unique_lock<std::mutex> _l(mNodeMutex);
677 auto it = mNodeForAddress.find(addr);
678 // last refcount dropped after this transaction happened
679 if (it == mNodeForAddress.end()) return OK;
680
681 // note - only updated now, instead of later, so that other threads
682 // will queue any later transactions
683
684 // TODO(b/183140903): support > 2**64 async transactions
685 // (we can do this by allowing asyncNumber to wrap, since we
686 // don't expect more than 2**64 simultaneous transactions)
687 it->second.asyncNumber++;
688
689 if (it->second.asyncTodo.size() == 0) return OK;
690 if (it->second.asyncTodo.top().asyncNumber == it->second.asyncNumber) {
691 LOG_RPC_DETAIL("Found next async transaction %" PRId64 " on %s",
692 it->second.asyncNumber, addr.toString().c_str());
693
694 // justification for const_cast (consider avoiding priority_queue):
Steven Morelandf5174272021-05-25 00:39:28 +0000695 // - AsyncTodo operator< doesn't depend on 'data' or 'ref' objects
Steven Moreland5553ac42020-11-11 02:14:45 +0000696 // - gotta go fast
Steven Morelandf5174272021-05-25 00:39:28 +0000697 auto& todo = const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top());
698
699 CommandData nextData = std::move(todo.data);
700 sp<IBinder> nextRef = std::move(todo.ref);
701
Steven Moreland5553ac42020-11-11 02:14:45 +0000702 it->second.asyncTodo.pop();
703 _l.unlock();
Steven Morelandf5174272021-05-25 00:39:28 +0000704 return processTransactInternal(fd, session, std::move(nextData),
705 std::move(nextRef));
Steven Moreland5553ac42020-11-11 02:14:45 +0000706 }
707 }
708 return OK;
709 }
710
711 RpcWireReply rpcReply{
712 .status = replyStatus,
713 };
714
Steven Morelanddbe71832021-05-12 23:31:00 +0000715 CommandData replyData(sizeof(RpcWireReply) + reply.dataSize());
Steven Morelande8393342021-05-05 23:27:53 +0000716 if (!replyData.valid()) {
717 return NO_MEMORY;
718 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000719 memcpy(replyData.data() + 0, &rpcReply, sizeof(RpcWireReply));
720 memcpy(replyData.data() + sizeof(RpcWireReply), reply.data(), reply.dataSize());
721
722 if (replyData.size() > std::numeric_limits<uint32_t>::max()) {
723 ALOGE("Reply size too big %zu", transactionData.size());
724 terminate();
725 return BAD_VALUE;
726 }
727
728 RpcWireHeader cmdReply{
729 .command = RPC_COMMAND_REPLY,
730 .bodySize = static_cast<uint32_t>(replyData.size()),
731 };
732
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000733 if (status_t status = rpcSend(fd, "reply header", &cmdReply, sizeof(RpcWireHeader));
734 status != OK)
735 return status;
736 if (status_t status = rpcSend(fd, "reply body", replyData.data(), replyData.size());
737 status != OK)
738 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000739 return OK;
740}
741
Steven Morelandee3f4662021-05-22 01:07:33 +0000742status_t RpcState::processDecStrong(const base::unique_fd& fd, const sp<RpcSession>& session,
743 const RpcWireHeader& command) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000744 LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
745
Steven Morelanddbe71832021-05-12 23:31:00 +0000746 CommandData commandData(command.bodySize);
Steven Morelande8393342021-05-05 23:27:53 +0000747 if (!commandData.valid()) {
748 return NO_MEMORY;
749 }
Steven Moreland1e4c2b82021-05-25 01:51:31 +0000750 if (status_t status =
751 rpcRec(fd, session, "dec ref body", commandData.data(), commandData.size());
752 status != OK)
753 return status;
Steven Moreland5553ac42020-11-11 02:14:45 +0000754
755 if (command.bodySize < sizeof(RpcWireAddress)) {
756 ALOGE("Expecting %zu but got %" PRId32 " bytes for RpcWireAddress. Terminating!",
757 sizeof(RpcWireAddress), command.bodySize);
758 terminate();
759 return BAD_VALUE;
760 }
761 RpcWireAddress* address = reinterpret_cast<RpcWireAddress*>(commandData.data());
762
763 // TODO(b/182939933): heap allocation just for lookup
764 auto addr = RpcAddress::fromRawEmbedded(address);
765 std::unique_lock<std::mutex> _l(mNodeMutex);
766 auto it = mNodeForAddress.find(addr);
767 if (it == mNodeForAddress.end()) {
768 ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
Steven Moreland5553ac42020-11-11 02:14:45 +0000769 return OK;
770 }
771
772 sp<IBinder> target = it->second.binder.promote();
773 if (target == nullptr) {
774 ALOGE("While requesting dec strong, binder has been deleted at address %s. Terminating!",
775 addr.toString().c_str());
776 terminate();
777 return BAD_VALUE;
778 }
779
780 if (it->second.timesSent == 0) {
781 ALOGE("No record of sending binder, but requested decStrong: %s", addr.toString().c_str());
782 return OK;
783 }
784
785 LOG_ALWAYS_FATAL_IF(it->second.sentRef == nullptr, "Inconsistent state, lost ref for %s",
786 addr.toString().c_str());
787
788 sp<IBinder> tempHold;
789
790 it->second.timesSent--;
791 if (it->second.timesSent == 0) {
792 tempHold = it->second.sentRef;
793 it->second.sentRef = nullptr;
794
795 if (it->second.timesRecd == 0) {
796 mNodeForAddress.erase(it);
797 }
798 }
799
800 _l.unlock();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000801 tempHold = nullptr; // destructor may make binder calls on this session
Steven Moreland5553ac42020-11-11 02:14:45 +0000802
803 return OK;
804}
805
806} // namespace android