blob: 93e04f7558dd964fcd793a6f261929d3e334fc53 [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>();
Steven Morelanda8b44292021-06-08 01:27:53 +0000147 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) {
148 ALOGE("Could not create pipe %s", strerror(errno));
149 return nullptr;
150 }
Steven Morelande47511f2021-05-20 00:07:41 +0000151 return ret;
152}
153
154void RpcSession::FdTrigger::trigger() {
155 mWrite.reset();
156}
157
Steven Morelanda8b44292021-06-08 01:27:53 +0000158bool RpcSession::FdTrigger::isTriggered() {
159 return mWrite == -1;
160}
161
Steven Moreland2b4f3802021-05-22 01:46:27 +0000162status_t RpcSession::FdTrigger::triggerablePollRead(base::borrowed_fd fd) {
Steven Moreland4ec3c432021-05-20 00:32:47 +0000163 while (true) {
Steven Morelanddfe3be92021-05-22 00:24:29 +0000164 pollfd pfd[]{{.fd = fd.get(), .events = POLLIN | POLLHUP, .revents = 0},
Steven Moreland4ec3c432021-05-20 00:32:47 +0000165 {.fd = mRead.get(), .events = POLLHUP, .revents = 0}};
166 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
167 if (ret < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000168 return -errno;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000169 }
170 if (ret == 0) {
171 continue;
172 }
173 if (pfd[1].revents & POLLHUP) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000174 return -ECANCELED;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000175 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000176 return pfd[0].revents & POLLIN ? OK : DEAD_OBJECT;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000177 }
178}
179
Steven Moreland2b4f3802021-05-22 01:46:27 +0000180status_t RpcSession::FdTrigger::interruptableReadFully(base::borrowed_fd fd, void* data,
181 size_t size) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000182 uint8_t* buffer = reinterpret_cast<uint8_t*>(data);
183 uint8_t* end = buffer + size;
184
Steven Moreland2b4f3802021-05-22 01:46:27 +0000185 status_t status;
186 while ((status = triggerablePollRead(fd)) == OK) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000187 ssize_t readSize = TEMP_FAILURE_RETRY(recv(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
Steven Moreland2b4f3802021-05-22 01:46:27 +0000188 if (readSize == 0) return DEAD_OBJECT; // EOF
Steven Morelanddfe3be92021-05-22 00:24:29 +0000189
Steven Moreland9d11b922021-05-20 01:22:58 +0000190 if (readSize < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000191 return -errno;
Steven Moreland9d11b922021-05-20 01:22:58 +0000192 }
193 buffer += readSize;
Steven Moreland2b4f3802021-05-22 01:46:27 +0000194 if (buffer == end) return OK;
Steven Moreland9d11b922021-05-20 01:22:58 +0000195 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000196 return status;
Steven Moreland9d11b922021-05-20 01:22:58 +0000197}
198
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000199status_t RpcSession::readId() {
200 {
201 std::lock_guard<std::mutex> _l(mMutex);
202 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
203 }
204
205 int32_t id;
206
207 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
208 status_t status =
209 state()->getSessionId(connection.fd(), sp<RpcSession>::fromExisting(this), &id);
210 if (status != OK) return status;
211
212 LOG_RPC_DETAIL("RpcSession %p has id %d", this, id);
213 mId = id;
214 return OK;
215}
216
Steven Moreland659416d2021-05-11 00:47:50 +0000217void RpcSession::WaitForShutdownListener::onSessionLockedAllServerThreadsEnded(
218 const sp<RpcSession>& session) {
219 (void)session;
220 mShutdown = true;
221}
222
223void RpcSession::WaitForShutdownListener::onSessionServerThreadEnded() {
224 mCv.notify_all();
225}
226
227void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
228 while (!mShutdown) {
229 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
230 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
231 }
232 }
233}
234
Steven Moreland5802c2b2021-05-12 20:13:04 +0000235void RpcSession::preJoin(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000236 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000237
Steven Morelanda63ff932021-05-12 00:03:15 +0000238 {
239 std::lock_guard<std::mutex> _l(mMutex);
240 mThreads[thread.get_id()] = std::move(thread);
241 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000242}
Steven Morelanda63ff932021-05-12 00:03:15 +0000243
Steven Moreland659416d2021-05-11 00:47:50 +0000244void RpcSession::join(sp<RpcSession>&& session, unique_fd client) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000245 // must be registered to allow arbitrary client code executing commands to
246 // be able to do nested calls (we can't only read from it)
Steven Moreland659416d2021-05-11 00:47:50 +0000247 sp<RpcConnection> connection = session->assignServerToThisThread(std::move(client));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000248
249 while (true) {
Steven Moreland52eee942021-06-03 00:59:28 +0000250 status_t error = session->state()->getAndExecuteCommand(connection->fd, session,
251 RpcState::CommandType::ANY);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000252
253 if (error != OK) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000254 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
255 statusToString(error).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000256 break;
257 }
258 }
259
Steven Moreland659416d2021-05-11 00:47:50 +0000260 LOG_ALWAYS_FATAL_IF(!session->removeServerConnection(connection),
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000261 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000262
Steven Moreland659416d2021-05-11 00:47:50 +0000263 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000264 {
Steven Moreland659416d2021-05-11 00:47:50 +0000265 std::lock_guard<std::mutex> _l(session->mMutex);
266 auto it = session->mThreads.find(std::this_thread::get_id());
267 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000268 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000269 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000270
Steven Moreland659416d2021-05-11 00:47:50 +0000271 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000272 }
273
Steven Moreland659416d2021-05-11 00:47:50 +0000274 session = nullptr;
275
276 if (listener != nullptr) {
277 listener->onSessionServerThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000278 }
279}
280
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000281wp<RpcServer> RpcSession::server() {
282 return mForServer;
283}
284
285bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
286 {
287 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000288 LOG_ALWAYS_FATAL_IF(mClientConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000289 "Must only setup session once, but already has %zu clients",
Steven Morelandbb543a82021-05-11 02:31:50 +0000290 mClientConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000291 }
292
Steven Moreland659416d2021-05-11 00:47:50 +0000293 if (!setupOneSocketConnection(addr, RPC_SESSION_ID_NEW, false /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000294
295 // TODO(b/185167543): we should add additional sessions dynamically
296 // instead of all at once.
297 // TODO(b/186470974): first risk of blocking
298 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000299 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000300 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
301 statusToString(status).c_str());
302 return false;
303 }
304
305 if (status_t status = readId(); status != OK) {
306 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
307 statusToString(status).c_str());
308 return false;
309 }
310
311 // we've already setup one client
312 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000313 // TODO(b/185167543): shutdown existing connections?
Steven Moreland659416d2021-05-11 00:47:50 +0000314 if (!setupOneSocketConnection(addr, mId.value(), false /*reverse*/)) return false;
315 }
316
317 // TODO(b/185167543): we should add additional sessions dynamically
318 // instead of all at once - the other side should be responsible for setting
319 // up additional connections. We need to create at least one (unless 0 are
320 // requested to be set) in order to allow the other side to reliably make
321 // any requests at all.
322
Steven Moreland103424e2021-06-02 18:16:19 +0000323 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland659416d2021-05-11 00:47:50 +0000324 if (!setupOneSocketConnection(addr, mId.value(), true /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000325 }
326
327 return true;
328}
329
Steven Moreland659416d2021-05-11 00:47:50 +0000330bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, int32_t id, bool reverse) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000331 for (size_t tries = 0; tries < 5; tries++) {
332 if (tries > 0) usleep(10000);
333
334 unique_fd serverFd(
335 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
336 if (serverFd == -1) {
337 int savedErrno = errno;
338 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
339 strerror(savedErrno));
340 return false;
341 }
342
343 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
344 if (errno == ECONNRESET) {
345 ALOGW("Connection reset on %s", addr.toString().c_str());
346 continue;
347 }
348 int savedErrno = errno;
349 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
350 strerror(savedErrno));
351 return false;
352 }
353
Steven Moreland659416d2021-05-11 00:47:50 +0000354 RpcConnectionHeader header{
355 .sessionId = id,
356 };
357 if (reverse) header.options |= RPC_CONNECTION_OPTION_REVERSE;
358
359 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000360 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000361 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000362 strerror(savedErrno));
363 return false;
364 }
365
366 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
367
Steven Moreland659416d2021-05-11 00:47:50 +0000368 if (reverse) {
369 std::mutex mutex;
370 std::condition_variable joinCv;
371 std::unique_lock<std::mutex> lock(mutex);
372 std::thread thread;
373 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
374 bool ownershipTransferred = false;
375 thread = std::thread([&]() {
376 std::unique_lock<std::mutex> threadLock(mutex);
377 unique_fd fd = std::move(serverFd);
378 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
379 sp<RpcSession> session = thiz;
380 session->preJoin(std::move(thread));
381 ownershipTransferred = true;
382 joinCv.notify_one();
383
384 threadLock.unlock();
385 // do not use & vars below
386
387 RpcSession::join(std::move(session), std::move(fd));
388 });
389 joinCv.wait(lock, [&] { return ownershipTransferred; });
390 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
391 return true;
392 } else {
393 return addClientConnection(std::move(serverFd));
394 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000395 }
396
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000397 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
398 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000399}
400
Steven Morelandb0dd1182021-05-25 01:56:46 +0000401bool RpcSession::addClientConnection(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000402 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000403
Steven Moreland659416d2021-05-11 00:47:50 +0000404 // first client connection added, but setForServer not called, so
405 // initializaing for a client.
Steven Morelandee3f4662021-05-22 01:07:33 +0000406 if (mShutdownTrigger == nullptr) {
407 mShutdownTrigger = FdTrigger::make();
Steven Moreland659416d2021-05-11 00:47:50 +0000408 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
Steven Morelandb0dd1182021-05-25 01:56:46 +0000409 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000410 }
411
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000412 sp<RpcConnection> session = sp<RpcConnection>::make();
413 session->fd = std::move(fd);
Steven Morelandbb543a82021-05-11 02:31:50 +0000414 mClientConnections.push_back(session);
Steven Morelandb0dd1182021-05-25 01:56:46 +0000415 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000416}
417
Steven Morelanda8b44292021-06-08 01:27:53 +0000418bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
419 int32_t sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000420 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
421 LOG_ALWAYS_FATAL_IF(server == nullptr);
422 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
423 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000424 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000425
426 mShutdownTrigger = FdTrigger::make();
427 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000428
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000429 mId = sessionId;
430 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000431 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000432 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000433}
434
435sp<RpcSession::RpcConnection> RpcSession::assignServerToThisThread(unique_fd fd) {
436 std::lock_guard<std::mutex> _l(mMutex);
437 sp<RpcConnection> session = sp<RpcConnection>::make();
438 session->fd = std::move(fd);
439 session->exclusiveTid = gettid();
Steven Morelandbb543a82021-05-11 02:31:50 +0000440 mServerConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000441
442 return session;
443}
444
445bool RpcSession::removeServerConnection(const sp<RpcConnection>& connection) {
446 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000447 if (auto it = std::find(mServerConnections.begin(), mServerConnections.end(), connection);
448 it != mServerConnections.end()) {
449 mServerConnections.erase(it);
450 if (mServerConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000451 sp<EventListener> listener = mEventListener.promote();
452 if (listener) {
453 listener->onSessionLockedAllServerThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000454 }
Steven Morelandee78e762021-05-05 21:12:51 +0000455 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000456 return true;
457 }
458 return false;
459}
460
461RpcSession::ExclusiveConnection::ExclusiveConnection(const sp<RpcSession>& session,
462 ConnectionUse use)
463 : mSession(session) {
464 pid_t tid = gettid();
465 std::unique_lock<std::mutex> _l(mSession->mMutex);
466
467 mSession->mWaitingThreads++;
468 while (true) {
469 sp<RpcConnection> exclusive;
470 sp<RpcConnection> available;
471
472 // CHECK FOR DEDICATED CLIENT SOCKET
473 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000474 // A server/looper should always use a dedicated connection if available
Steven Morelandbb543a82021-05-11 02:31:50 +0000475 findConnection(tid, &exclusive, &available, mSession->mClientConnections,
476 mSession->mClientConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000477
478 // WARNING: this assumes a server cannot request its client to send
Steven Morelandbb543a82021-05-11 02:31:50 +0000479 // a transaction, as mServerConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000480 //
481 // Imagine we have more than one thread in play, and a single thread
482 // sends a synchronous, then an asynchronous command. Imagine the
483 // asynchronous command is sent on the first client connection. Then, if
484 // we naively send a synchronous command to that same connection, the
485 // thread on the far side might be busy processing the asynchronous
486 // command. So, we move to considering the second available thread
487 // for subsequent calls.
488 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelandbb543a82021-05-11 02:31:50 +0000489 mSession->mClientConnectionsOffset =
490 (mSession->mClientConnectionsOffset + 1) % mSession->mClientConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000491 }
492
493 // USE SERVING SOCKET (for nested transaction)
494 //
495 // asynchronous calls cannot be nested
496 if (use != ConnectionUse::CLIENT_ASYNC) {
497 // server connections are always assigned to a thread
Steven Morelandbb543a82021-05-11 02:31:50 +0000498 findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServerConnections,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000499 0 /* index hint */);
500 }
501
Steven Moreland85e067b2021-05-26 17:43:53 +0000502 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000503 if (exclusive != nullptr) {
504 mConnection = exclusive;
505 mReentrant = true;
506 break;
507 } else if (available != nullptr) {
508 mConnection = available;
509 mConnection->exclusiveTid = tid;
510 break;
511 }
512
Steven Moreland659416d2021-05-11 00:47:50 +0000513 // TODO(b/185167543): this should return an error, rather than crash a
514 // server
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000515 // in regular binder, this would usually be a deadlock :)
Steven Morelandbb543a82021-05-11 02:31:50 +0000516 LOG_ALWAYS_FATAL_IF(mSession->mClientConnections.size() == 0,
Steven Moreland85e067b2021-05-26 17:43:53 +0000517 "Session has no client connections. This is required for an RPC server "
518 "to make any non-nested (e.g. oneway or on another thread) calls.");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000519
Steven Moreland85e067b2021-05-26 17:43:53 +0000520 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelandbb543a82021-05-11 02:31:50 +0000521 mSession->mClientConnections.size(), mSession->mServerConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000522 mSession->mAvailableConnectionCv.wait(_l);
523 }
524 mSession->mWaitingThreads--;
525}
526
527void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
528 sp<RpcConnection>* available,
529 std::vector<sp<RpcConnection>>& sockets,
530 size_t socketsIndexHint) {
531 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
532 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
533
534 if (*exclusive != nullptr) return; // consistent with break below
535
536 for (size_t i = 0; i < sockets.size(); i++) {
537 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
538
Steven Moreland85e067b2021-05-26 17:43:53 +0000539 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000540 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
541 *available = socket;
542 continue;
543 }
544
Steven Moreland85e067b2021-05-26 17:43:53 +0000545 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000546 // (nested transactions)
547 if (exclusive && socket->exclusiveTid == tid) {
548 *exclusive = socket;
549 break; // consistent with return above
550 }
551 }
552}
553
554RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000555 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000556 // is using this fd, and it retains the right to it. So, we don't give up
557 // exclusive ownership, and no thread is freed.
558 if (!mReentrant) {
559 std::unique_lock<std::mutex> _l(mSession->mMutex);
560 mConnection->exclusiveTid = std::nullopt;
561 if (mSession->mWaitingThreads > 0) {
562 _l.unlock();
563 mSession->mAvailableConnectionCv.notify_one();
564 }
565 }
566}
567
568} // namespace android