blob: a2fe3b91ba124c8df062452d873af9e93e705732 [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 Moreland52eee942021-06-03 00:59:28 +0000240 status_t error = session->state()->getAndExecuteCommand(connection->fd, session,
241 RpcState::CommandType::ANY);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000242
243 if (error != OK) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000244 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
245 statusToString(error).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000246 break;
247 }
248 }
249
Steven Moreland659416d2021-05-11 00:47:50 +0000250 LOG_ALWAYS_FATAL_IF(!session->removeServerConnection(connection),
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000251 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000252
Steven Moreland659416d2021-05-11 00:47:50 +0000253 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000254 {
Steven Moreland659416d2021-05-11 00:47:50 +0000255 std::lock_guard<std::mutex> _l(session->mMutex);
256 auto it = session->mThreads.find(std::this_thread::get_id());
257 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000258 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000259 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000260
Steven Moreland659416d2021-05-11 00:47:50 +0000261 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000262 }
263
Steven Moreland659416d2021-05-11 00:47:50 +0000264 session = nullptr;
265
266 if (listener != nullptr) {
267 listener->onSessionServerThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000268 }
269}
270
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000271wp<RpcServer> RpcSession::server() {
272 return mForServer;
273}
274
275bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
276 {
277 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000278 LOG_ALWAYS_FATAL_IF(mClientConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000279 "Must only setup session once, but already has %zu clients",
Steven Morelandbb543a82021-05-11 02:31:50 +0000280 mClientConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000281 }
282
Steven Moreland659416d2021-05-11 00:47:50 +0000283 if (!setupOneSocketConnection(addr, RPC_SESSION_ID_NEW, false /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000284
285 // TODO(b/185167543): we should add additional sessions dynamically
286 // instead of all at once.
287 // TODO(b/186470974): first risk of blocking
288 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000289 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000290 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
291 statusToString(status).c_str());
292 return false;
293 }
294
295 if (status_t status = readId(); status != OK) {
296 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
297 statusToString(status).c_str());
298 return false;
299 }
300
301 // we've already setup one client
302 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000303 // TODO(b/185167543): shutdown existing connections?
Steven Moreland659416d2021-05-11 00:47:50 +0000304 if (!setupOneSocketConnection(addr, mId.value(), false /*reverse*/)) return false;
305 }
306
307 // TODO(b/185167543): we should add additional sessions dynamically
308 // instead of all at once - the other side should be responsible for setting
309 // up additional connections. We need to create at least one (unless 0 are
310 // requested to be set) in order to allow the other side to reliably make
311 // any requests at all.
312
313 for (size_t i = 0; i < mMaxReverseConnections; i++) {
314 if (!setupOneSocketConnection(addr, mId.value(), true /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000315 }
316
317 return true;
318}
319
Steven Moreland659416d2021-05-11 00:47:50 +0000320bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, int32_t id, bool reverse) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000321 for (size_t tries = 0; tries < 5; tries++) {
322 if (tries > 0) usleep(10000);
323
324 unique_fd serverFd(
325 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
326 if (serverFd == -1) {
327 int savedErrno = errno;
328 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
329 strerror(savedErrno));
330 return false;
331 }
332
333 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
334 if (errno == ECONNRESET) {
335 ALOGW("Connection reset on %s", addr.toString().c_str());
336 continue;
337 }
338 int savedErrno = errno;
339 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
340 strerror(savedErrno));
341 return false;
342 }
343
Steven Moreland659416d2021-05-11 00:47:50 +0000344 RpcConnectionHeader header{
345 .sessionId = id,
346 };
347 if (reverse) header.options |= RPC_CONNECTION_OPTION_REVERSE;
348
349 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000350 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000351 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000352 strerror(savedErrno));
353 return false;
354 }
355
356 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
357
Steven Moreland659416d2021-05-11 00:47:50 +0000358 if (reverse) {
359 std::mutex mutex;
360 std::condition_variable joinCv;
361 std::unique_lock<std::mutex> lock(mutex);
362 std::thread thread;
363 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
364 bool ownershipTransferred = false;
365 thread = std::thread([&]() {
366 std::unique_lock<std::mutex> threadLock(mutex);
367 unique_fd fd = std::move(serverFd);
368 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
369 sp<RpcSession> session = thiz;
370 session->preJoin(std::move(thread));
371 ownershipTransferred = true;
372 joinCv.notify_one();
373
374 threadLock.unlock();
375 // do not use & vars below
376
377 RpcSession::join(std::move(session), std::move(fd));
378 });
379 joinCv.wait(lock, [&] { return ownershipTransferred; });
380 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
381 return true;
382 } else {
383 return addClientConnection(std::move(serverFd));
384 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000385 }
386
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000387 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
388 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000389}
390
Steven Morelandb0dd1182021-05-25 01:56:46 +0000391bool RpcSession::addClientConnection(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000392 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000393
Steven Moreland659416d2021-05-11 00:47:50 +0000394 // first client connection added, but setForServer not called, so
395 // initializaing for a client.
Steven Morelandee3f4662021-05-22 01:07:33 +0000396 if (mShutdownTrigger == nullptr) {
397 mShutdownTrigger = FdTrigger::make();
Steven Moreland659416d2021-05-11 00:47:50 +0000398 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
Steven Morelandb0dd1182021-05-25 01:56:46 +0000399 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000400 }
401
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000402 sp<RpcConnection> session = sp<RpcConnection>::make();
403 session->fd = std::move(fd);
Steven Morelandbb543a82021-05-11 02:31:50 +0000404 mClientConnections.push_back(session);
Steven Morelandb0dd1182021-05-25 01:56:46 +0000405 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000406}
407
Steven Moreland659416d2021-05-11 00:47:50 +0000408void RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
409 int32_t sessionId,
Steven Morelandee3f4662021-05-22 01:07:33 +0000410 const std::shared_ptr<FdTrigger>& shutdownTrigger) {
Steven Moreland659416d2021-05-11 00:47:50 +0000411 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
412 LOG_ALWAYS_FATAL_IF(server == nullptr);
413 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
414 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000415 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
416 LOG_ALWAYS_FATAL_IF(shutdownTrigger == nullptr);
417
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000418 mId = sessionId;
419 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000420 mEventListener = eventListener;
Steven Morelandee3f4662021-05-22 01:07:33 +0000421 mShutdownTrigger = shutdownTrigger;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000422}
423
424sp<RpcSession::RpcConnection> RpcSession::assignServerToThisThread(unique_fd fd) {
425 std::lock_guard<std::mutex> _l(mMutex);
426 sp<RpcConnection> session = sp<RpcConnection>::make();
427 session->fd = std::move(fd);
428 session->exclusiveTid = gettid();
Steven Morelandbb543a82021-05-11 02:31:50 +0000429 mServerConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000430
431 return session;
432}
433
434bool RpcSession::removeServerConnection(const sp<RpcConnection>& connection) {
435 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000436 if (auto it = std::find(mServerConnections.begin(), mServerConnections.end(), connection);
437 it != mServerConnections.end()) {
438 mServerConnections.erase(it);
439 if (mServerConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000440 sp<EventListener> listener = mEventListener.promote();
441 if (listener) {
442 listener->onSessionLockedAllServerThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000443 }
Steven Morelandee78e762021-05-05 21:12:51 +0000444 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000445 return true;
446 }
447 return false;
448}
449
450RpcSession::ExclusiveConnection::ExclusiveConnection(const sp<RpcSession>& session,
451 ConnectionUse use)
452 : mSession(session) {
453 pid_t tid = gettid();
454 std::unique_lock<std::mutex> _l(mSession->mMutex);
455
456 mSession->mWaitingThreads++;
457 while (true) {
458 sp<RpcConnection> exclusive;
459 sp<RpcConnection> available;
460
461 // CHECK FOR DEDICATED CLIENT SOCKET
462 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000463 // A server/looper should always use a dedicated connection if available
Steven Morelandbb543a82021-05-11 02:31:50 +0000464 findConnection(tid, &exclusive, &available, mSession->mClientConnections,
465 mSession->mClientConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000466
467 // WARNING: this assumes a server cannot request its client to send
Steven Morelandbb543a82021-05-11 02:31:50 +0000468 // a transaction, as mServerConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000469 //
470 // Imagine we have more than one thread in play, and a single thread
471 // sends a synchronous, then an asynchronous command. Imagine the
472 // asynchronous command is sent on the first client connection. Then, if
473 // we naively send a synchronous command to that same connection, the
474 // thread on the far side might be busy processing the asynchronous
475 // command. So, we move to considering the second available thread
476 // for subsequent calls.
477 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelandbb543a82021-05-11 02:31:50 +0000478 mSession->mClientConnectionsOffset =
479 (mSession->mClientConnectionsOffset + 1) % mSession->mClientConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000480 }
481
482 // USE SERVING SOCKET (for nested transaction)
483 //
484 // asynchronous calls cannot be nested
485 if (use != ConnectionUse::CLIENT_ASYNC) {
486 // server connections are always assigned to a thread
Steven Morelandbb543a82021-05-11 02:31:50 +0000487 findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServerConnections,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000488 0 /* index hint */);
489 }
490
Steven Moreland85e067b2021-05-26 17:43:53 +0000491 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000492 if (exclusive != nullptr) {
493 mConnection = exclusive;
494 mReentrant = true;
495 break;
496 } else if (available != nullptr) {
497 mConnection = available;
498 mConnection->exclusiveTid = tid;
499 break;
500 }
501
Steven Moreland659416d2021-05-11 00:47:50 +0000502 // TODO(b/185167543): this should return an error, rather than crash a
503 // server
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000504 // in regular binder, this would usually be a deadlock :)
Steven Morelandbb543a82021-05-11 02:31:50 +0000505 LOG_ALWAYS_FATAL_IF(mSession->mClientConnections.size() == 0,
Steven Moreland85e067b2021-05-26 17:43:53 +0000506 "Session has no client connections. This is required for an RPC server "
507 "to make any non-nested (e.g. oneway or on another thread) calls.");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000508
Steven Moreland85e067b2021-05-26 17:43:53 +0000509 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelandbb543a82021-05-11 02:31:50 +0000510 mSession->mClientConnections.size(), mSession->mServerConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000511 mSession->mAvailableConnectionCv.wait(_l);
512 }
513 mSession->mWaitingThreads--;
514}
515
516void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
517 sp<RpcConnection>* available,
518 std::vector<sp<RpcConnection>>& sockets,
519 size_t socketsIndexHint) {
520 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
521 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
522
523 if (*exclusive != nullptr) return; // consistent with break below
524
525 for (size_t i = 0; i < sockets.size(); i++) {
526 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
527
Steven Moreland85e067b2021-05-26 17:43:53 +0000528 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000529 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
530 *available = socket;
531 continue;
532 }
533
Steven Moreland85e067b2021-05-26 17:43:53 +0000534 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000535 // (nested transactions)
536 if (exclusive && socket->exclusiveTid == tid) {
537 *exclusive = socket;
538 break; // consistent with return above
539 }
540 }
541}
542
543RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000544 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000545 // is using this fd, and it retains the right to it. So, we don't give up
546 // exclusive ownership, and no thread is freed.
547 if (!mReentrant) {
548 std::unique_lock<std::mutex> _l(mSession->mMutex);
549 mConnection->exclusiveTid = std::nullopt;
550 if (mSession->mWaitingThreads > 0) {
551 _l.unlock();
552 mSession->mAvailableConnectionCv.notify_one();
553 }
554 }
555}
556
557} // namespace android