blob: c5633771d0ecca2c61465c46c9b517265413fdfb [file] [log] [blame]
Steven Morelandbdb53ab2021-05-05 17:57:41 +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 "RpcSession"
18
19#include <binder/RpcSession.h>
20
21#include <inttypes.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000022#include <poll.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000023#include <unistd.h>
24
25#include <string_view>
26
Steven Moreland4ec3c432021-05-20 00:32:47 +000027#include <android-base/macros.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000028#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000029#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000030#include <binder/Stability.h>
31#include <utils/String8.h>
32
33#include "RpcSocketAddress.h"
34#include "RpcState.h"
35#include "RpcWireFormat.h"
36
37#ifdef __GLIBC__
38extern "C" pid_t gettid();
39#endif
40
41namespace android {
42
43using base::unique_fd;
44
45RpcSession::RpcSession() {
46 LOG_RPC_DETAIL("RpcSession created %p", this);
47
48 mState = std::make_unique<RpcState>();
49}
50RpcSession::~RpcSession() {
51 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
52
53 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +000054 LOG_ALWAYS_FATAL_IF(mServerConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000055 "Should not be able to destroy a session with servers in use.");
56}
57
58sp<RpcSession> RpcSession::make() {
59 return sp<RpcSession>::make();
60}
61
Steven Moreland103424e2021-06-02 18:16:19 +000062void RpcSession::setMaxThreads(size_t threads) {
63 std::lock_guard<std::mutex> _l(mMutex);
64 LOG_ALWAYS_FATAL_IF(!mClientConnections.empty() || !mServerConnections.empty(),
65 "Must set max threads before setting up connections, but has %zu client(s) "
66 "and %zu server(s)",
67 mClientConnections.size(), mServerConnections.size());
68 mMaxThreads = threads;
69}
70
71size_t RpcSession::getMaxThreads() {
72 std::lock_guard<std::mutex> _l(mMutex);
73 return mMaxThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000074}
75
Steven Morelandbdb53ab2021-05-05 17:57:41 +000076bool RpcSession::setupUnixDomainClient(const char* path) {
77 return setupSocketClient(UnixSocketAddress(path));
78}
79
Steven Morelandbdb53ab2021-05-05 17:57:41 +000080bool RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
81 return setupSocketClient(VsockSocketAddress(cid, port));
82}
83
Steven Morelandbdb53ab2021-05-05 17:57:41 +000084bool RpcSession::setupInetClient(const char* addr, unsigned int port) {
85 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
86 if (aiStart == nullptr) return false;
87 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
88 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
89 if (setupSocketClient(socketAddress)) return true;
90 }
91 ALOGE("None of the socket address resolved for %s:%u can be added as inet client.", addr, port);
92 return false;
93}
94
95bool RpcSession::addNullDebuggingClient() {
96 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
97
98 if (serverFd == -1) {
99 ALOGE("Could not connect to /dev/null: %s", strerror(errno));
100 return false;
101 }
102
Steven Morelandb0dd1182021-05-25 01:56:46 +0000103 return addClientConnection(std::move(serverFd));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000104}
105
106sp<IBinder> RpcSession::getRootObject() {
107 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
108 return state()->getRootObject(connection.fd(), sp<RpcSession>::fromExisting(this));
109}
110
Steven Moreland1be91352021-05-11 22:12:15 +0000111status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000112 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
113 return state()->getMaxThreads(connection.fd(), sp<RpcSession>::fromExisting(this), maxThreads);
114}
115
Steven Moreland659416d2021-05-11 00:47:50 +0000116bool RpcSession::shutdown() {
117 std::unique_lock<std::mutex> _l(mMutex);
118 LOG_ALWAYS_FATAL_IF(mForServer.promote() != nullptr, "Can only shut down client session");
119 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
120 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
121
122 mShutdownTrigger->trigger();
123 mShutdownListener->waitForShutdown(_l);
124 mState->terminate();
125
126 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
127 return true;
128}
129
Steven Morelandf5174272021-05-25 00:39:28 +0000130status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000131 Parcel* reply, uint32_t flags) {
132 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this),
133 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
134 : ConnectionUse::CLIENT);
Steven Morelandf5174272021-05-25 00:39:28 +0000135 return state()->transact(connection.fd(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000136 sp<RpcSession>::fromExisting(this), reply, flags);
137}
138
139status_t RpcSession::sendDecStrong(const RpcAddress& address) {
140 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this),
141 ConnectionUse::CLIENT_REFCOUNT);
142 return state()->sendDecStrong(connection.fd(), address);
143}
144
Steven Morelande47511f2021-05-20 00:07:41 +0000145std::unique_ptr<RpcSession::FdTrigger> RpcSession::FdTrigger::make() {
146 auto ret = std::make_unique<RpcSession::FdTrigger>();
147 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) return nullptr;
148 return ret;
149}
150
151void RpcSession::FdTrigger::trigger() {
152 mWrite.reset();
153}
154
Steven Moreland2b4f3802021-05-22 01:46:27 +0000155status_t RpcSession::FdTrigger::triggerablePollRead(base::borrowed_fd fd) {
Steven Moreland4ec3c432021-05-20 00:32:47 +0000156 while (true) {
Steven Morelanddfe3be92021-05-22 00:24:29 +0000157 pollfd pfd[]{{.fd = fd.get(), .events = POLLIN | POLLHUP, .revents = 0},
Steven Moreland4ec3c432021-05-20 00:32:47 +0000158 {.fd = mRead.get(), .events = POLLHUP, .revents = 0}};
159 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
160 if (ret < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000161 return -errno;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000162 }
163 if (ret == 0) {
164 continue;
165 }
166 if (pfd[1].revents & POLLHUP) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000167 return -ECANCELED;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000168 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000169 return pfd[0].revents & POLLIN ? OK : DEAD_OBJECT;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000170 }
171}
172
Steven Moreland2b4f3802021-05-22 01:46:27 +0000173status_t RpcSession::FdTrigger::interruptableReadFully(base::borrowed_fd fd, void* data,
174 size_t size) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000175 uint8_t* buffer = reinterpret_cast<uint8_t*>(data);
176 uint8_t* end = buffer + size;
177
Steven Moreland2b4f3802021-05-22 01:46:27 +0000178 status_t status;
179 while ((status = triggerablePollRead(fd)) == OK) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000180 ssize_t readSize = TEMP_FAILURE_RETRY(recv(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
Steven Moreland2b4f3802021-05-22 01:46:27 +0000181 if (readSize == 0) return DEAD_OBJECT; // EOF
Steven Morelanddfe3be92021-05-22 00:24:29 +0000182
Steven Moreland9d11b922021-05-20 01:22:58 +0000183 if (readSize < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000184 return -errno;
Steven Moreland9d11b922021-05-20 01:22:58 +0000185 }
186 buffer += readSize;
Steven Moreland2b4f3802021-05-22 01:46:27 +0000187 if (buffer == end) return OK;
Steven Moreland9d11b922021-05-20 01:22:58 +0000188 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000189 return status;
Steven Moreland9d11b922021-05-20 01:22:58 +0000190}
191
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000192status_t RpcSession::readId() {
193 {
194 std::lock_guard<std::mutex> _l(mMutex);
195 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
196 }
197
198 int32_t id;
199
200 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
201 status_t status =
202 state()->getSessionId(connection.fd(), sp<RpcSession>::fromExisting(this), &id);
203 if (status != OK) return status;
204
205 LOG_RPC_DETAIL("RpcSession %p has id %d", this, id);
206 mId = id;
207 return OK;
208}
209
Steven Moreland659416d2021-05-11 00:47:50 +0000210void RpcSession::WaitForShutdownListener::onSessionLockedAllServerThreadsEnded(
211 const sp<RpcSession>& session) {
212 (void)session;
213 mShutdown = true;
214}
215
216void RpcSession::WaitForShutdownListener::onSessionServerThreadEnded() {
217 mCv.notify_all();
218}
219
220void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
221 while (!mShutdown) {
222 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
223 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
224 }
225 }
226}
227
Steven Moreland5802c2b2021-05-12 20:13:04 +0000228void RpcSession::preJoin(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000229 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000230
Steven Morelanda63ff932021-05-12 00:03:15 +0000231 {
232 std::lock_guard<std::mutex> _l(mMutex);
233 mThreads[thread.get_id()] = std::move(thread);
234 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000235}
Steven Morelanda63ff932021-05-12 00:03:15 +0000236
Steven Moreland659416d2021-05-11 00:47:50 +0000237void RpcSession::join(sp<RpcSession>&& session, unique_fd client) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000238 // must be registered to allow arbitrary client code executing commands to
239 // be able to do nested calls (we can't only read from it)
Steven Moreland659416d2021-05-11 00:47:50 +0000240 sp<RpcConnection> connection = session->assignServerToThisThread(std::move(client));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000241
242 while (true) {
Steven Moreland52eee942021-06-03 00:59:28 +0000243 status_t error = session->state()->getAndExecuteCommand(connection->fd, session,
244 RpcState::CommandType::ANY);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000245
246 if (error != OK) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000247 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
248 statusToString(error).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000249 break;
250 }
251 }
252
Steven Moreland659416d2021-05-11 00:47:50 +0000253 LOG_ALWAYS_FATAL_IF(!session->removeServerConnection(connection),
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000254 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000255
Steven Moreland659416d2021-05-11 00:47:50 +0000256 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000257 {
Steven Moreland659416d2021-05-11 00:47:50 +0000258 std::lock_guard<std::mutex> _l(session->mMutex);
259 auto it = session->mThreads.find(std::this_thread::get_id());
260 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000261 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000262 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000263
Steven Moreland659416d2021-05-11 00:47:50 +0000264 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000265 }
266
Steven Moreland659416d2021-05-11 00:47:50 +0000267 session = nullptr;
268
269 if (listener != nullptr) {
270 listener->onSessionServerThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000271 }
272}
273
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000274wp<RpcServer> RpcSession::server() {
275 return mForServer;
276}
277
278bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
279 {
280 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000281 LOG_ALWAYS_FATAL_IF(mClientConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000282 "Must only setup session once, but already has %zu clients",
Steven Morelandbb543a82021-05-11 02:31:50 +0000283 mClientConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000284 }
285
Steven Moreland659416d2021-05-11 00:47:50 +0000286 if (!setupOneSocketConnection(addr, RPC_SESSION_ID_NEW, false /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000287
288 // TODO(b/185167543): we should add additional sessions dynamically
289 // instead of all at once.
290 // TODO(b/186470974): first risk of blocking
291 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000292 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000293 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
294 statusToString(status).c_str());
295 return false;
296 }
297
298 if (status_t status = readId(); status != OK) {
299 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
300 statusToString(status).c_str());
301 return false;
302 }
303
304 // we've already setup one client
305 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000306 // TODO(b/185167543): shutdown existing connections?
Steven Moreland659416d2021-05-11 00:47:50 +0000307 if (!setupOneSocketConnection(addr, mId.value(), false /*reverse*/)) return false;
308 }
309
310 // TODO(b/185167543): we should add additional sessions dynamically
311 // instead of all at once - the other side should be responsible for setting
312 // up additional connections. We need to create at least one (unless 0 are
313 // requested to be set) in order to allow the other side to reliably make
314 // any requests at all.
315
Steven Moreland103424e2021-06-02 18:16:19 +0000316 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland659416d2021-05-11 00:47:50 +0000317 if (!setupOneSocketConnection(addr, mId.value(), true /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000318 }
319
320 return true;
321}
322
Steven Moreland659416d2021-05-11 00:47:50 +0000323bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, int32_t id, bool reverse) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000324 for (size_t tries = 0; tries < 5; tries++) {
325 if (tries > 0) usleep(10000);
326
327 unique_fd serverFd(
328 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
329 if (serverFd == -1) {
330 int savedErrno = errno;
331 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
332 strerror(savedErrno));
333 return false;
334 }
335
336 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
337 if (errno == ECONNRESET) {
338 ALOGW("Connection reset on %s", addr.toString().c_str());
339 continue;
340 }
341 int savedErrno = errno;
342 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
343 strerror(savedErrno));
344 return false;
345 }
346
Steven Moreland659416d2021-05-11 00:47:50 +0000347 RpcConnectionHeader header{
348 .sessionId = id,
349 };
350 if (reverse) header.options |= RPC_CONNECTION_OPTION_REVERSE;
351
352 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000353 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000354 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000355 strerror(savedErrno));
356 return false;
357 }
358
359 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
360
Steven Moreland659416d2021-05-11 00:47:50 +0000361 if (reverse) {
362 std::mutex mutex;
363 std::condition_variable joinCv;
364 std::unique_lock<std::mutex> lock(mutex);
365 std::thread thread;
366 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
367 bool ownershipTransferred = false;
368 thread = std::thread([&]() {
369 std::unique_lock<std::mutex> threadLock(mutex);
370 unique_fd fd = std::move(serverFd);
371 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
372 sp<RpcSession> session = thiz;
373 session->preJoin(std::move(thread));
374 ownershipTransferred = true;
375 joinCv.notify_one();
376
377 threadLock.unlock();
378 // do not use & vars below
379
380 RpcSession::join(std::move(session), std::move(fd));
381 });
382 joinCv.wait(lock, [&] { return ownershipTransferred; });
383 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
384 return true;
385 } else {
386 return addClientConnection(std::move(serverFd));
387 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000388 }
389
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000390 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
391 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000392}
393
Steven Morelandb0dd1182021-05-25 01:56:46 +0000394bool RpcSession::addClientConnection(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000395 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000396
Steven Moreland659416d2021-05-11 00:47:50 +0000397 // first client connection added, but setForServer not called, so
398 // initializaing for a client.
Steven Morelandee3f4662021-05-22 01:07:33 +0000399 if (mShutdownTrigger == nullptr) {
400 mShutdownTrigger = FdTrigger::make();
Steven Moreland659416d2021-05-11 00:47:50 +0000401 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
Steven Morelandb0dd1182021-05-25 01:56:46 +0000402 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000403 }
404
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000405 sp<RpcConnection> session = sp<RpcConnection>::make();
406 session->fd = std::move(fd);
Steven Morelandbb543a82021-05-11 02:31:50 +0000407 mClientConnections.push_back(session);
Steven Morelandb0dd1182021-05-25 01:56:46 +0000408 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409}
410
Steven Moreland659416d2021-05-11 00:47:50 +0000411void RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
412 int32_t sessionId,
Steven Morelandee3f4662021-05-22 01:07:33 +0000413 const std::shared_ptr<FdTrigger>& shutdownTrigger) {
Steven Moreland659416d2021-05-11 00:47:50 +0000414 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
415 LOG_ALWAYS_FATAL_IF(server == nullptr);
416 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
417 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000418 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
419 LOG_ALWAYS_FATAL_IF(shutdownTrigger == nullptr);
420
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000421 mId = sessionId;
422 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000423 mEventListener = eventListener;
Steven Morelandee3f4662021-05-22 01:07:33 +0000424 mShutdownTrigger = shutdownTrigger;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000425}
426
427sp<RpcSession::RpcConnection> RpcSession::assignServerToThisThread(unique_fd fd) {
428 std::lock_guard<std::mutex> _l(mMutex);
429 sp<RpcConnection> session = sp<RpcConnection>::make();
430 session->fd = std::move(fd);
431 session->exclusiveTid = gettid();
Steven Morelandbb543a82021-05-11 02:31:50 +0000432 mServerConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000433
434 return session;
435}
436
437bool RpcSession::removeServerConnection(const sp<RpcConnection>& connection) {
438 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000439 if (auto it = std::find(mServerConnections.begin(), mServerConnections.end(), connection);
440 it != mServerConnections.end()) {
441 mServerConnections.erase(it);
442 if (mServerConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000443 sp<EventListener> listener = mEventListener.promote();
444 if (listener) {
445 listener->onSessionLockedAllServerThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000446 }
Steven Morelandee78e762021-05-05 21:12:51 +0000447 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000448 return true;
449 }
450 return false;
451}
452
453RpcSession::ExclusiveConnection::ExclusiveConnection(const sp<RpcSession>& session,
454 ConnectionUse use)
455 : mSession(session) {
456 pid_t tid = gettid();
457 std::unique_lock<std::mutex> _l(mSession->mMutex);
458
459 mSession->mWaitingThreads++;
460 while (true) {
461 sp<RpcConnection> exclusive;
462 sp<RpcConnection> available;
463
464 // CHECK FOR DEDICATED CLIENT SOCKET
465 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000466 // A server/looper should always use a dedicated connection if available
Steven Morelandbb543a82021-05-11 02:31:50 +0000467 findConnection(tid, &exclusive, &available, mSession->mClientConnections,
468 mSession->mClientConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000469
470 // WARNING: this assumes a server cannot request its client to send
Steven Morelandbb543a82021-05-11 02:31:50 +0000471 // a transaction, as mServerConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000472 //
473 // Imagine we have more than one thread in play, and a single thread
474 // sends a synchronous, then an asynchronous command. Imagine the
475 // asynchronous command is sent on the first client connection. Then, if
476 // we naively send a synchronous command to that same connection, the
477 // thread on the far side might be busy processing the asynchronous
478 // command. So, we move to considering the second available thread
479 // for subsequent calls.
480 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelandbb543a82021-05-11 02:31:50 +0000481 mSession->mClientConnectionsOffset =
482 (mSession->mClientConnectionsOffset + 1) % mSession->mClientConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000483 }
484
485 // USE SERVING SOCKET (for nested transaction)
486 //
487 // asynchronous calls cannot be nested
488 if (use != ConnectionUse::CLIENT_ASYNC) {
489 // server connections are always assigned to a thread
Steven Morelandbb543a82021-05-11 02:31:50 +0000490 findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServerConnections,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000491 0 /* index hint */);
492 }
493
Steven Moreland85e067b2021-05-26 17:43:53 +0000494 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000495 if (exclusive != nullptr) {
496 mConnection = exclusive;
497 mReentrant = true;
498 break;
499 } else if (available != nullptr) {
500 mConnection = available;
501 mConnection->exclusiveTid = tid;
502 break;
503 }
504
Steven Moreland659416d2021-05-11 00:47:50 +0000505 // TODO(b/185167543): this should return an error, rather than crash a
506 // server
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000507 // in regular binder, this would usually be a deadlock :)
Steven Morelandbb543a82021-05-11 02:31:50 +0000508 LOG_ALWAYS_FATAL_IF(mSession->mClientConnections.size() == 0,
Steven Moreland85e067b2021-05-26 17:43:53 +0000509 "Session has no client connections. This is required for an RPC server "
510 "to make any non-nested (e.g. oneway or on another thread) calls.");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000511
Steven Moreland85e067b2021-05-26 17:43:53 +0000512 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelandbb543a82021-05-11 02:31:50 +0000513 mSession->mClientConnections.size(), mSession->mServerConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000514 mSession->mAvailableConnectionCv.wait(_l);
515 }
516 mSession->mWaitingThreads--;
517}
518
519void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
520 sp<RpcConnection>* available,
521 std::vector<sp<RpcConnection>>& sockets,
522 size_t socketsIndexHint) {
523 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
524 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
525
526 if (*exclusive != nullptr) return; // consistent with break below
527
528 for (size_t i = 0; i < sockets.size(); i++) {
529 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
530
Steven Moreland85e067b2021-05-26 17:43:53 +0000531 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000532 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
533 *available = socket;
534 continue;
535 }
536
Steven Moreland85e067b2021-05-26 17:43:53 +0000537 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000538 // (nested transactions)
539 if (exclusive && socket->exclusiveTid == tid) {
540 *exclusive = socket;
541 break; // consistent with return above
542 }
543 }
544}
545
546RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000547 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000548 // is using this fd, and it retains the right to it. So, we don't give up
549 // exclusive ownership, and no thread is freed.
550 if (!mReentrant) {
551 std::unique_lock<std::mutex> _l(mSession->mMutex);
552 mConnection->exclusiveTid = std::nullopt;
553 if (mSession->mWaitingThreads > 0) {
554 _l.unlock();
555 mSession->mAvailableConnectionCv.notify_one();
556 }
557 }
558}
559
560} // namespace android