blob: a3efa56e3bca7b8dfabac9221d9f01c82f623b25 [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 Moreland659416d2021-05-11 00:47:50 +000062void RpcSession::setMaxReverseConnections(size_t connections) {
63 {
64 std::lock_guard<std::mutex> _l(mMutex);
65 LOG_ALWAYS_FATAL_IF(mClientConnections.size() != 0,
66 "Must setup reverse connections before setting up client connections, "
67 "but already has %zu clients",
68 mClientConnections.size());
69 }
70 mMaxReverseConnections = connections;
71}
72
Steven Morelandbdb53ab2021-05-05 17:57:41 +000073bool RpcSession::setupUnixDomainClient(const char* path) {
74 return setupSocketClient(UnixSocketAddress(path));
75}
76
Steven Morelandbdb53ab2021-05-05 17:57:41 +000077bool RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
78 return setupSocketClient(VsockSocketAddress(cid, port));
79}
80
Steven Morelandbdb53ab2021-05-05 17:57:41 +000081bool RpcSession::setupInetClient(const char* addr, unsigned int port) {
82 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
83 if (aiStart == nullptr) return false;
84 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
85 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
86 if (setupSocketClient(socketAddress)) return true;
87 }
88 ALOGE("None of the socket address resolved for %s:%u can be added as inet client.", addr, port);
89 return false;
90}
91
92bool RpcSession::addNullDebuggingClient() {
93 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
94
95 if (serverFd == -1) {
96 ALOGE("Could not connect to /dev/null: %s", strerror(errno));
97 return false;
98 }
99
Steven Morelandb0dd1182021-05-25 01:56:46 +0000100 return addClientConnection(std::move(serverFd));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000101}
102
103sp<IBinder> RpcSession::getRootObject() {
104 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
105 return state()->getRootObject(connection.fd(), sp<RpcSession>::fromExisting(this));
106}
107
Steven Moreland1be91352021-05-11 22:12:15 +0000108status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000109 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
110 return state()->getMaxThreads(connection.fd(), sp<RpcSession>::fromExisting(this), maxThreads);
111}
112
Steven Moreland659416d2021-05-11 00:47:50 +0000113bool RpcSession::shutdown() {
114 std::unique_lock<std::mutex> _l(mMutex);
115 LOG_ALWAYS_FATAL_IF(mForServer.promote() != nullptr, "Can only shut down client session");
116 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
117 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
118
119 mShutdownTrigger->trigger();
120 mShutdownListener->waitForShutdown(_l);
121 mState->terminate();
122
123 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
124 return true;
125}
126
Steven Morelandf5174272021-05-25 00:39:28 +0000127status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000128 Parcel* reply, uint32_t flags) {
129 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this),
130 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
131 : ConnectionUse::CLIENT);
Steven Morelandf5174272021-05-25 00:39:28 +0000132 return state()->transact(connection.fd(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000133 sp<RpcSession>::fromExisting(this), reply, flags);
134}
135
136status_t RpcSession::sendDecStrong(const RpcAddress& address) {
137 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this),
138 ConnectionUse::CLIENT_REFCOUNT);
139 return state()->sendDecStrong(connection.fd(), address);
140}
141
Steven Morelande47511f2021-05-20 00:07:41 +0000142std::unique_ptr<RpcSession::FdTrigger> RpcSession::FdTrigger::make() {
143 auto ret = std::make_unique<RpcSession::FdTrigger>();
144 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) return nullptr;
145 return ret;
146}
147
148void RpcSession::FdTrigger::trigger() {
149 mWrite.reset();
150}
151
Steven Moreland2b4f3802021-05-22 01:46:27 +0000152status_t RpcSession::FdTrigger::triggerablePollRead(base::borrowed_fd fd) {
Steven Moreland4ec3c432021-05-20 00:32:47 +0000153 while (true) {
Steven Morelanddfe3be92021-05-22 00:24:29 +0000154 pollfd pfd[]{{.fd = fd.get(), .events = POLLIN | POLLHUP, .revents = 0},
Steven Moreland4ec3c432021-05-20 00:32:47 +0000155 {.fd = mRead.get(), .events = POLLHUP, .revents = 0}};
156 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
157 if (ret < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000158 return -errno;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000159 }
160 if (ret == 0) {
161 continue;
162 }
163 if (pfd[1].revents & POLLHUP) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000164 return -ECANCELED;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000165 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000166 return pfd[0].revents & POLLIN ? OK : DEAD_OBJECT;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000167 }
168}
169
Steven Moreland2b4f3802021-05-22 01:46:27 +0000170status_t RpcSession::FdTrigger::interruptableReadFully(base::borrowed_fd fd, void* data,
171 size_t size) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000172 uint8_t* buffer = reinterpret_cast<uint8_t*>(data);
173 uint8_t* end = buffer + size;
174
Steven Moreland2b4f3802021-05-22 01:46:27 +0000175 status_t status;
176 while ((status = triggerablePollRead(fd)) == OK) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000177 ssize_t readSize = TEMP_FAILURE_RETRY(recv(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
Steven Moreland2b4f3802021-05-22 01:46:27 +0000178 if (readSize == 0) return DEAD_OBJECT; // EOF
Steven Morelanddfe3be92021-05-22 00:24:29 +0000179
Steven Moreland9d11b922021-05-20 01:22:58 +0000180 if (readSize < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000181 return -errno;
Steven Moreland9d11b922021-05-20 01:22:58 +0000182 }
183 buffer += readSize;
Steven Moreland2b4f3802021-05-22 01:46:27 +0000184 if (buffer == end) return OK;
Steven Moreland9d11b922021-05-20 01:22:58 +0000185 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000186 return status;
Steven Moreland9d11b922021-05-20 01:22:58 +0000187}
188
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000189status_t RpcSession::readId() {
190 {
191 std::lock_guard<std::mutex> _l(mMutex);
192 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
193 }
194
195 int32_t id;
196
197 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
198 status_t status =
199 state()->getSessionId(connection.fd(), sp<RpcSession>::fromExisting(this), &id);
200 if (status != OK) return status;
201
202 LOG_RPC_DETAIL("RpcSession %p has id %d", this, id);
203 mId = id;
204 return OK;
205}
206
Steven Moreland659416d2021-05-11 00:47:50 +0000207void RpcSession::WaitForShutdownListener::onSessionLockedAllServerThreadsEnded(
208 const sp<RpcSession>& session) {
209 (void)session;
210 mShutdown = true;
211}
212
213void RpcSession::WaitForShutdownListener::onSessionServerThreadEnded() {
214 mCv.notify_all();
215}
216
217void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
218 while (!mShutdown) {
219 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
220 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
221 }
222 }
223}
224
Steven Moreland5802c2b2021-05-12 20:13:04 +0000225void RpcSession::preJoin(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000226 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000227
Steven Morelanda63ff932021-05-12 00:03:15 +0000228 {
229 std::lock_guard<std::mutex> _l(mMutex);
230 mThreads[thread.get_id()] = std::move(thread);
231 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000232}
Steven Morelanda63ff932021-05-12 00:03:15 +0000233
Steven Moreland659416d2021-05-11 00:47:50 +0000234void RpcSession::join(sp<RpcSession>&& session, unique_fd client) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000235 // must be registered to allow arbitrary client code executing commands to
236 // be able to do nested calls (we can't only read from it)
Steven Moreland659416d2021-05-11 00:47:50 +0000237 sp<RpcConnection> connection = session->assignServerToThisThread(std::move(client));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000238
239 while (true) {
Steven Moreland659416d2021-05-11 00:47:50 +0000240 status_t error = session->state()->getAndExecuteCommand(connection->fd, session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000241
242 if (error != OK) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000243 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
244 statusToString(error).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000245 break;
246 }
247 }
248
Steven Moreland659416d2021-05-11 00:47:50 +0000249 LOG_ALWAYS_FATAL_IF(!session->removeServerConnection(connection),
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000250 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000251
Steven Moreland659416d2021-05-11 00:47:50 +0000252 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000253 {
Steven Moreland659416d2021-05-11 00:47:50 +0000254 std::lock_guard<std::mutex> _l(session->mMutex);
255 auto it = session->mThreads.find(std::this_thread::get_id());
256 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000257 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000258 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000259
Steven Moreland659416d2021-05-11 00:47:50 +0000260 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000261 }
262
Steven Moreland659416d2021-05-11 00:47:50 +0000263 session = nullptr;
264
265 if (listener != nullptr) {
266 listener->onSessionServerThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000267 }
268}
269
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000270wp<RpcServer> RpcSession::server() {
271 return mForServer;
272}
273
274bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
275 {
276 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000277 LOG_ALWAYS_FATAL_IF(mClientConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000278 "Must only setup session once, but already has %zu clients",
Steven Morelandbb543a82021-05-11 02:31:50 +0000279 mClientConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000280 }
281
Steven Moreland659416d2021-05-11 00:47:50 +0000282 if (!setupOneSocketConnection(addr, RPC_SESSION_ID_NEW, false /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000283
284 // TODO(b/185167543): we should add additional sessions dynamically
285 // instead of all at once.
286 // TODO(b/186470974): first risk of blocking
287 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000288 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000289 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
290 statusToString(status).c_str());
291 return false;
292 }
293
294 if (status_t status = readId(); status != OK) {
295 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
296 statusToString(status).c_str());
297 return false;
298 }
299
300 // we've already setup one client
301 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000302 // TODO(b/185167543): shutdown existing connections?
Steven Moreland659416d2021-05-11 00:47:50 +0000303 if (!setupOneSocketConnection(addr, mId.value(), false /*reverse*/)) return false;
304 }
305
306 // TODO(b/185167543): we should add additional sessions dynamically
307 // instead of all at once - the other side should be responsible for setting
308 // up additional connections. We need to create at least one (unless 0 are
309 // requested to be set) in order to allow the other side to reliably make
310 // any requests at all.
311
312 for (size_t i = 0; i < mMaxReverseConnections; i++) {
313 if (!setupOneSocketConnection(addr, mId.value(), true /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000314 }
315
316 return true;
317}
318
Steven Moreland659416d2021-05-11 00:47:50 +0000319bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, int32_t id, bool reverse) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000320 for (size_t tries = 0; tries < 5; tries++) {
321 if (tries > 0) usleep(10000);
322
323 unique_fd serverFd(
324 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
325 if (serverFd == -1) {
326 int savedErrno = errno;
327 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
328 strerror(savedErrno));
329 return false;
330 }
331
332 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
333 if (errno == ECONNRESET) {
334 ALOGW("Connection reset on %s", addr.toString().c_str());
335 continue;
336 }
337 int savedErrno = errno;
338 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
339 strerror(savedErrno));
340 return false;
341 }
342
Steven Moreland659416d2021-05-11 00:47:50 +0000343 RpcConnectionHeader header{
344 .sessionId = id,
345 };
346 if (reverse) header.options |= RPC_CONNECTION_OPTION_REVERSE;
347
348 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000349 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000350 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000351 strerror(savedErrno));
352 return false;
353 }
354
355 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
356
Steven Moreland659416d2021-05-11 00:47:50 +0000357 if (reverse) {
358 std::mutex mutex;
359 std::condition_variable joinCv;
360 std::unique_lock<std::mutex> lock(mutex);
361 std::thread thread;
362 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
363 bool ownershipTransferred = false;
364 thread = std::thread([&]() {
365 std::unique_lock<std::mutex> threadLock(mutex);
366 unique_fd fd = std::move(serverFd);
367 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
368 sp<RpcSession> session = thiz;
369 session->preJoin(std::move(thread));
370 ownershipTransferred = true;
371 joinCv.notify_one();
372
373 threadLock.unlock();
374 // do not use & vars below
375
376 RpcSession::join(std::move(session), std::move(fd));
377 });
378 joinCv.wait(lock, [&] { return ownershipTransferred; });
379 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
380 return true;
381 } else {
382 return addClientConnection(std::move(serverFd));
383 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000384 }
385
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000386 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
387 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000388}
389
Steven Morelandb0dd1182021-05-25 01:56:46 +0000390bool RpcSession::addClientConnection(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000391 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000392
Steven Moreland659416d2021-05-11 00:47:50 +0000393 // first client connection added, but setForServer not called, so
394 // initializaing for a client.
Steven Morelandee3f4662021-05-22 01:07:33 +0000395 if (mShutdownTrigger == nullptr) {
396 mShutdownTrigger = FdTrigger::make();
Steven Moreland659416d2021-05-11 00:47:50 +0000397 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
Steven Morelandb0dd1182021-05-25 01:56:46 +0000398 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000399 }
400
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000401 sp<RpcConnection> session = sp<RpcConnection>::make();
402 session->fd = std::move(fd);
Steven Morelandbb543a82021-05-11 02:31:50 +0000403 mClientConnections.push_back(session);
Steven Morelandb0dd1182021-05-25 01:56:46 +0000404 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000405}
406
Steven Moreland659416d2021-05-11 00:47:50 +0000407void RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
408 int32_t sessionId,
Steven Morelandee3f4662021-05-22 01:07:33 +0000409 const std::shared_ptr<FdTrigger>& shutdownTrigger) {
Steven Moreland659416d2021-05-11 00:47:50 +0000410 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
411 LOG_ALWAYS_FATAL_IF(server == nullptr);
412 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
413 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000414 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
415 LOG_ALWAYS_FATAL_IF(shutdownTrigger == nullptr);
416
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000417 mId = sessionId;
418 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000419 mEventListener = eventListener;
Steven Morelandee3f4662021-05-22 01:07:33 +0000420 mShutdownTrigger = shutdownTrigger;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000421}
422
423sp<RpcSession::RpcConnection> RpcSession::assignServerToThisThread(unique_fd fd) {
424 std::lock_guard<std::mutex> _l(mMutex);
425 sp<RpcConnection> session = sp<RpcConnection>::make();
426 session->fd = std::move(fd);
427 session->exclusiveTid = gettid();
Steven Morelandbb543a82021-05-11 02:31:50 +0000428 mServerConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000429
430 return session;
431}
432
433bool RpcSession::removeServerConnection(const sp<RpcConnection>& connection) {
434 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000435 if (auto it = std::find(mServerConnections.begin(), mServerConnections.end(), connection);
436 it != mServerConnections.end()) {
437 mServerConnections.erase(it);
438 if (mServerConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000439 sp<EventListener> listener = mEventListener.promote();
440 if (listener) {
441 listener->onSessionLockedAllServerThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000442 }
Steven Morelandee78e762021-05-05 21:12:51 +0000443 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000444 return true;
445 }
446 return false;
447}
448
449RpcSession::ExclusiveConnection::ExclusiveConnection(const sp<RpcSession>& session,
450 ConnectionUse use)
451 : mSession(session) {
452 pid_t tid = gettid();
453 std::unique_lock<std::mutex> _l(mSession->mMutex);
454
455 mSession->mWaitingThreads++;
456 while (true) {
457 sp<RpcConnection> exclusive;
458 sp<RpcConnection> available;
459
460 // CHECK FOR DEDICATED CLIENT SOCKET
461 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000462 // A server/looper should always use a dedicated connection if available
Steven Morelandbb543a82021-05-11 02:31:50 +0000463 findConnection(tid, &exclusive, &available, mSession->mClientConnections,
464 mSession->mClientConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000465
466 // WARNING: this assumes a server cannot request its client to send
Steven Morelandbb543a82021-05-11 02:31:50 +0000467 // a transaction, as mServerConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000468 //
469 // Imagine we have more than one thread in play, and a single thread
470 // sends a synchronous, then an asynchronous command. Imagine the
471 // asynchronous command is sent on the first client connection. Then, if
472 // we naively send a synchronous command to that same connection, the
473 // thread on the far side might be busy processing the asynchronous
474 // command. So, we move to considering the second available thread
475 // for subsequent calls.
476 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelandbb543a82021-05-11 02:31:50 +0000477 mSession->mClientConnectionsOffset =
478 (mSession->mClientConnectionsOffset + 1) % mSession->mClientConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000479 }
480
481 // USE SERVING SOCKET (for nested transaction)
482 //
483 // asynchronous calls cannot be nested
484 if (use != ConnectionUse::CLIENT_ASYNC) {
485 // server connections are always assigned to a thread
Steven Morelandbb543a82021-05-11 02:31:50 +0000486 findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServerConnections,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000487 0 /* index hint */);
488 }
489
Steven Moreland85e067b2021-05-26 17:43:53 +0000490 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000491 if (exclusive != nullptr) {
492 mConnection = exclusive;
493 mReentrant = true;
494 break;
495 } else if (available != nullptr) {
496 mConnection = available;
497 mConnection->exclusiveTid = tid;
498 break;
499 }
500
Steven Moreland659416d2021-05-11 00:47:50 +0000501 // TODO(b/185167543): this should return an error, rather than crash a
502 // server
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000503 // in regular binder, this would usually be a deadlock :)
Steven Morelandbb543a82021-05-11 02:31:50 +0000504 LOG_ALWAYS_FATAL_IF(mSession->mClientConnections.size() == 0,
Steven Moreland85e067b2021-05-26 17:43:53 +0000505 "Session has no client connections. This is required for an RPC server "
506 "to make any non-nested (e.g. oneway or on another thread) calls.");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000507
Steven Moreland85e067b2021-05-26 17:43:53 +0000508 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelandbb543a82021-05-11 02:31:50 +0000509 mSession->mClientConnections.size(), mSession->mServerConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000510 mSession->mAvailableConnectionCv.wait(_l);
511 }
512 mSession->mWaitingThreads--;
513}
514
515void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
516 sp<RpcConnection>* available,
517 std::vector<sp<RpcConnection>>& sockets,
518 size_t socketsIndexHint) {
519 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
520 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
521
522 if (*exclusive != nullptr) return; // consistent with break below
523
524 for (size_t i = 0; i < sockets.size(); i++) {
525 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
526
Steven Moreland85e067b2021-05-26 17:43:53 +0000527 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000528 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
529 *available = socket;
530 continue;
531 }
532
Steven Moreland85e067b2021-05-26 17:43:53 +0000533 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000534 // (nested transactions)
535 if (exclusive && socket->exclusiveTid == tid) {
536 *exclusive = socket;
537 break; // consistent with return above
538 }
539 }
540}
541
542RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000543 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000544 // is using this fd, and it retains the right to it. So, we don't give up
545 // exclusive ownership, and no thread is freed.
546 if (!mReentrant) {
547 std::unique_lock<std::mutex> _l(mSession->mMutex);
548 mConnection->exclusiveTid = std::nullopt;
549 if (mSession->mWaitingThreads > 0) {
550 _l.unlock();
551 mSession->mAvailableConnectionCv.notify_one();
552 }
553 }
554}
555
556} // namespace android