blob: a27dff5c8f602312a2c85731f6b73519b23b22bc [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 Moreland659416d2021-05-11 00:47:50 +0000243 status_t error = session->state()->getAndExecuteCommand(connection->fd, session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000244
245 if (error != OK) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000246 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
247 statusToString(error).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000248 break;
249 }
250 }
251
Steven Moreland659416d2021-05-11 00:47:50 +0000252 LOG_ALWAYS_FATAL_IF(!session->removeServerConnection(connection),
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000253 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000254
Steven Moreland659416d2021-05-11 00:47:50 +0000255 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000256 {
Steven Moreland659416d2021-05-11 00:47:50 +0000257 std::lock_guard<std::mutex> _l(session->mMutex);
258 auto it = session->mThreads.find(std::this_thread::get_id());
259 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000260 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000261 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000262
Steven Moreland659416d2021-05-11 00:47:50 +0000263 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000264 }
265
Steven Moreland659416d2021-05-11 00:47:50 +0000266 session = nullptr;
267
268 if (listener != nullptr) {
269 listener->onSessionServerThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000270 }
271}
272
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000273wp<RpcServer> RpcSession::server() {
274 return mForServer;
275}
276
277bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
278 {
279 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000280 LOG_ALWAYS_FATAL_IF(mClientConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000281 "Must only setup session once, but already has %zu clients",
Steven Morelandbb543a82021-05-11 02:31:50 +0000282 mClientConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000283 }
284
Steven Moreland659416d2021-05-11 00:47:50 +0000285 if (!setupOneSocketConnection(addr, RPC_SESSION_ID_NEW, false /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000286
287 // TODO(b/185167543): we should add additional sessions dynamically
288 // instead of all at once.
289 // TODO(b/186470974): first risk of blocking
290 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000291 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000292 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
293 statusToString(status).c_str());
294 return false;
295 }
296
297 if (status_t status = readId(); status != OK) {
298 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
299 statusToString(status).c_str());
300 return false;
301 }
302
303 // we've already setup one client
304 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000305 // TODO(b/185167543): shutdown existing connections?
Steven Moreland659416d2021-05-11 00:47:50 +0000306 if (!setupOneSocketConnection(addr, mId.value(), false /*reverse*/)) return false;
307 }
308
309 // TODO(b/185167543): we should add additional sessions dynamically
310 // instead of all at once - the other side should be responsible for setting
311 // up additional connections. We need to create at least one (unless 0 are
312 // requested to be set) in order to allow the other side to reliably make
313 // any requests at all.
314
Steven Moreland103424e2021-06-02 18:16:19 +0000315 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland659416d2021-05-11 00:47:50 +0000316 if (!setupOneSocketConnection(addr, mId.value(), true /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000317 }
318
319 return true;
320}
321
Steven Moreland659416d2021-05-11 00:47:50 +0000322bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, int32_t id, bool reverse) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000323 for (size_t tries = 0; tries < 5; tries++) {
324 if (tries > 0) usleep(10000);
325
326 unique_fd serverFd(
327 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
328 if (serverFd == -1) {
329 int savedErrno = errno;
330 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
331 strerror(savedErrno));
332 return false;
333 }
334
335 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
336 if (errno == ECONNRESET) {
337 ALOGW("Connection reset on %s", addr.toString().c_str());
338 continue;
339 }
340 int savedErrno = errno;
341 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
342 strerror(savedErrno));
343 return false;
344 }
345
Steven Moreland659416d2021-05-11 00:47:50 +0000346 RpcConnectionHeader header{
347 .sessionId = id,
348 };
349 if (reverse) header.options |= RPC_CONNECTION_OPTION_REVERSE;
350
351 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000352 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000353 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000354 strerror(savedErrno));
355 return false;
356 }
357
358 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
359
Steven Moreland659416d2021-05-11 00:47:50 +0000360 if (reverse) {
361 std::mutex mutex;
362 std::condition_variable joinCv;
363 std::unique_lock<std::mutex> lock(mutex);
364 std::thread thread;
365 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
366 bool ownershipTransferred = false;
367 thread = std::thread([&]() {
368 std::unique_lock<std::mutex> threadLock(mutex);
369 unique_fd fd = std::move(serverFd);
370 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
371 sp<RpcSession> session = thiz;
372 session->preJoin(std::move(thread));
373 ownershipTransferred = true;
374 joinCv.notify_one();
375
376 threadLock.unlock();
377 // do not use & vars below
378
379 RpcSession::join(std::move(session), std::move(fd));
380 });
381 joinCv.wait(lock, [&] { return ownershipTransferred; });
382 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
383 return true;
384 } else {
385 return addClientConnection(std::move(serverFd));
386 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000387 }
388
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000389 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
390 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000391}
392
Steven Morelandb0dd1182021-05-25 01:56:46 +0000393bool RpcSession::addClientConnection(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000394 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000395
Steven Moreland659416d2021-05-11 00:47:50 +0000396 // first client connection added, but setForServer not called, so
397 // initializaing for a client.
Steven Morelandee3f4662021-05-22 01:07:33 +0000398 if (mShutdownTrigger == nullptr) {
399 mShutdownTrigger = FdTrigger::make();
Steven Moreland659416d2021-05-11 00:47:50 +0000400 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
Steven Morelandb0dd1182021-05-25 01:56:46 +0000401 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000402 }
403
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000404 sp<RpcConnection> session = sp<RpcConnection>::make();
405 session->fd = std::move(fd);
Steven Morelandbb543a82021-05-11 02:31:50 +0000406 mClientConnections.push_back(session);
Steven Morelandb0dd1182021-05-25 01:56:46 +0000407 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000408}
409
Steven Moreland659416d2021-05-11 00:47:50 +0000410void RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
411 int32_t sessionId,
Steven Morelandee3f4662021-05-22 01:07:33 +0000412 const std::shared_ptr<FdTrigger>& shutdownTrigger) {
Steven Moreland659416d2021-05-11 00:47:50 +0000413 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
414 LOG_ALWAYS_FATAL_IF(server == nullptr);
415 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
416 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000417 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
418 LOG_ALWAYS_FATAL_IF(shutdownTrigger == nullptr);
419
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000420 mId = sessionId;
421 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000422 mEventListener = eventListener;
Steven Morelandee3f4662021-05-22 01:07:33 +0000423 mShutdownTrigger = shutdownTrigger;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000424}
425
426sp<RpcSession::RpcConnection> RpcSession::assignServerToThisThread(unique_fd fd) {
427 std::lock_guard<std::mutex> _l(mMutex);
428 sp<RpcConnection> session = sp<RpcConnection>::make();
429 session->fd = std::move(fd);
430 session->exclusiveTid = gettid();
Steven Morelandbb543a82021-05-11 02:31:50 +0000431 mServerConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000432
433 return session;
434}
435
436bool RpcSession::removeServerConnection(const sp<RpcConnection>& connection) {
437 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000438 if (auto it = std::find(mServerConnections.begin(), mServerConnections.end(), connection);
439 it != mServerConnections.end()) {
440 mServerConnections.erase(it);
441 if (mServerConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000442 sp<EventListener> listener = mEventListener.promote();
443 if (listener) {
444 listener->onSessionLockedAllServerThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000445 }
Steven Morelandee78e762021-05-05 21:12:51 +0000446 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000447 return true;
448 }
449 return false;
450}
451
452RpcSession::ExclusiveConnection::ExclusiveConnection(const sp<RpcSession>& session,
453 ConnectionUse use)
454 : mSession(session) {
455 pid_t tid = gettid();
456 std::unique_lock<std::mutex> _l(mSession->mMutex);
457
458 mSession->mWaitingThreads++;
459 while (true) {
460 sp<RpcConnection> exclusive;
461 sp<RpcConnection> available;
462
463 // CHECK FOR DEDICATED CLIENT SOCKET
464 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000465 // A server/looper should always use a dedicated connection if available
Steven Morelandbb543a82021-05-11 02:31:50 +0000466 findConnection(tid, &exclusive, &available, mSession->mClientConnections,
467 mSession->mClientConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000468
469 // WARNING: this assumes a server cannot request its client to send
Steven Morelandbb543a82021-05-11 02:31:50 +0000470 // a transaction, as mServerConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000471 //
472 // Imagine we have more than one thread in play, and a single thread
473 // sends a synchronous, then an asynchronous command. Imagine the
474 // asynchronous command is sent on the first client connection. Then, if
475 // we naively send a synchronous command to that same connection, the
476 // thread on the far side might be busy processing the asynchronous
477 // command. So, we move to considering the second available thread
478 // for subsequent calls.
479 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelandbb543a82021-05-11 02:31:50 +0000480 mSession->mClientConnectionsOffset =
481 (mSession->mClientConnectionsOffset + 1) % mSession->mClientConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000482 }
483
484 // USE SERVING SOCKET (for nested transaction)
485 //
486 // asynchronous calls cannot be nested
487 if (use != ConnectionUse::CLIENT_ASYNC) {
488 // server connections are always assigned to a thread
Steven Morelandbb543a82021-05-11 02:31:50 +0000489 findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServerConnections,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000490 0 /* index hint */);
491 }
492
Steven Moreland85e067b2021-05-26 17:43:53 +0000493 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000494 if (exclusive != nullptr) {
495 mConnection = exclusive;
496 mReentrant = true;
497 break;
498 } else if (available != nullptr) {
499 mConnection = available;
500 mConnection->exclusiveTid = tid;
501 break;
502 }
503
Steven Moreland659416d2021-05-11 00:47:50 +0000504 // TODO(b/185167543): this should return an error, rather than crash a
505 // server
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000506 // in regular binder, this would usually be a deadlock :)
Steven Morelandbb543a82021-05-11 02:31:50 +0000507 LOG_ALWAYS_FATAL_IF(mSession->mClientConnections.size() == 0,
Steven Moreland85e067b2021-05-26 17:43:53 +0000508 "Session has no client connections. This is required for an RPC server "
509 "to make any non-nested (e.g. oneway or on another thread) calls.");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000510
Steven Moreland85e067b2021-05-26 17:43:53 +0000511 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelandbb543a82021-05-11 02:31:50 +0000512 mSession->mClientConnections.size(), mSession->mServerConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000513 mSession->mAvailableConnectionCv.wait(_l);
514 }
515 mSession->mWaitingThreads--;
516}
517
518void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
519 sp<RpcConnection>* available,
520 std::vector<sp<RpcConnection>>& sockets,
521 size_t socketsIndexHint) {
522 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
523 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
524
525 if (*exclusive != nullptr) return; // consistent with break below
526
527 for (size_t i = 0; i < sockets.size(); i++) {
528 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
529
Steven Moreland85e067b2021-05-26 17:43:53 +0000530 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000531 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
532 *available = socket;
533 continue;
534 }
535
Steven Moreland85e067b2021-05-26 17:43:53 +0000536 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000537 // (nested transactions)
538 if (exclusive && socket->exclusiveTid == tid) {
539 *exclusive = socket;
540 break; // consistent with return above
541 }
542 }
543}
544
545RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000546 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000547 // is using this fd, and it retains the right to it. So, we don't give up
548 // exclusive ownership, and no thread is freed.
549 if (!mReentrant) {
550 std::unique_lock<std::mutex> _l(mSession->mMutex);
551 mConnection->exclusiveTid = std::nullopt;
552 if (mSession->mWaitingThreads > 0) {
553 _l.unlock();
554 mSession->mAvailableConnectionCv.notify_one();
555 }
556 }
557}
558
559} // namespace android