blob: 62118ffddcdaae1f61f04906f8faa896e546f80b [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 Morelandc9d7b532021-06-04 20:57:41 +0000116bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000117 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000118 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000119
120 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000121
Steven Morelandc9d7b532021-06-04 20:57:41 +0000122 if (wait) {
123 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
124 mShutdownListener->waitForShutdown(_l);
125 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
126 }
127
128 _l.unlock();
129 mState->clear();
130
Steven Moreland659416d2021-05-11 00:47:50 +0000131 return true;
132}
133
Steven Morelandf5174272021-05-25 00:39:28 +0000134status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000135 Parcel* reply, uint32_t flags) {
136 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this),
137 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
138 : ConnectionUse::CLIENT);
Steven Morelandf5174272021-05-25 00:39:28 +0000139 return state()->transact(connection.fd(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000140 sp<RpcSession>::fromExisting(this), reply, flags);
141}
142
143status_t RpcSession::sendDecStrong(const RpcAddress& address) {
144 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this),
145 ConnectionUse::CLIENT_REFCOUNT);
Steven Morelandc9d7b532021-06-04 20:57:41 +0000146 return state()->sendDecStrong(connection.fd(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000147}
148
Steven Morelande47511f2021-05-20 00:07:41 +0000149std::unique_ptr<RpcSession::FdTrigger> RpcSession::FdTrigger::make() {
150 auto ret = std::make_unique<RpcSession::FdTrigger>();
Steven Morelanda8b44292021-06-08 01:27:53 +0000151 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) {
152 ALOGE("Could not create pipe %s", strerror(errno));
153 return nullptr;
154 }
Steven Morelande47511f2021-05-20 00:07:41 +0000155 return ret;
156}
157
158void RpcSession::FdTrigger::trigger() {
159 mWrite.reset();
160}
161
Steven Morelanda8b44292021-06-08 01:27:53 +0000162bool RpcSession::FdTrigger::isTriggered() {
163 return mWrite == -1;
164}
165
Steven Moreland2b4f3802021-05-22 01:46:27 +0000166status_t RpcSession::FdTrigger::triggerablePollRead(base::borrowed_fd fd) {
Steven Moreland4ec3c432021-05-20 00:32:47 +0000167 while (true) {
Steven Morelanddfe3be92021-05-22 00:24:29 +0000168 pollfd pfd[]{{.fd = fd.get(), .events = POLLIN | POLLHUP, .revents = 0},
Steven Moreland4ec3c432021-05-20 00:32:47 +0000169 {.fd = mRead.get(), .events = POLLHUP, .revents = 0}};
170 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
171 if (ret < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000172 return -errno;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000173 }
174 if (ret == 0) {
175 continue;
176 }
177 if (pfd[1].revents & POLLHUP) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000178 return -ECANCELED;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000179 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000180 return pfd[0].revents & POLLIN ? OK : DEAD_OBJECT;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000181 }
182}
183
Steven Moreland2b4f3802021-05-22 01:46:27 +0000184status_t RpcSession::FdTrigger::interruptableReadFully(base::borrowed_fd fd, void* data,
185 size_t size) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000186 uint8_t* buffer = reinterpret_cast<uint8_t*>(data);
187 uint8_t* end = buffer + size;
188
Steven Moreland2b4f3802021-05-22 01:46:27 +0000189 status_t status;
190 while ((status = triggerablePollRead(fd)) == OK) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000191 ssize_t readSize = TEMP_FAILURE_RETRY(recv(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
Steven Moreland2b4f3802021-05-22 01:46:27 +0000192 if (readSize == 0) return DEAD_OBJECT; // EOF
Steven Morelanddfe3be92021-05-22 00:24:29 +0000193
Steven Moreland9d11b922021-05-20 01:22:58 +0000194 if (readSize < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000195 return -errno;
Steven Moreland9d11b922021-05-20 01:22:58 +0000196 }
197 buffer += readSize;
Steven Moreland2b4f3802021-05-22 01:46:27 +0000198 if (buffer == end) return OK;
Steven Moreland9d11b922021-05-20 01:22:58 +0000199 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000200 return status;
Steven Moreland9d11b922021-05-20 01:22:58 +0000201}
202
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000203status_t RpcSession::readId() {
204 {
205 std::lock_guard<std::mutex> _l(mMutex);
206 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
207 }
208
209 int32_t id;
210
211 ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
212 status_t status =
213 state()->getSessionId(connection.fd(), sp<RpcSession>::fromExisting(this), &id);
214 if (status != OK) return status;
215
216 LOG_RPC_DETAIL("RpcSession %p has id %d", this, id);
217 mId = id;
218 return OK;
219}
220
Steven Moreland659416d2021-05-11 00:47:50 +0000221void RpcSession::WaitForShutdownListener::onSessionLockedAllServerThreadsEnded(
222 const sp<RpcSession>& session) {
223 (void)session;
224 mShutdown = true;
225}
226
227void RpcSession::WaitForShutdownListener::onSessionServerThreadEnded() {
228 mCv.notify_all();
229}
230
231void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
232 while (!mShutdown) {
233 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
234 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
235 }
236 }
237}
238
Steven Moreland5802c2b2021-05-12 20:13:04 +0000239void RpcSession::preJoin(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000240 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000241
Steven Morelanda63ff932021-05-12 00:03:15 +0000242 {
243 std::lock_guard<std::mutex> _l(mMutex);
244 mThreads[thread.get_id()] = std::move(thread);
245 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000246}
Steven Morelanda63ff932021-05-12 00:03:15 +0000247
Steven Moreland659416d2021-05-11 00:47:50 +0000248void RpcSession::join(sp<RpcSession>&& session, unique_fd client) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000249 // must be registered to allow arbitrary client code executing commands to
250 // be able to do nested calls (we can't only read from it)
Steven Moreland659416d2021-05-11 00:47:50 +0000251 sp<RpcConnection> connection = session->assignServerToThisThread(std::move(client));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000252
253 while (true) {
Steven Moreland52eee942021-06-03 00:59:28 +0000254 status_t error = session->state()->getAndExecuteCommand(connection->fd, session,
255 RpcState::CommandType::ANY);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000256
257 if (error != OK) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000258 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
259 statusToString(error).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000260 break;
261 }
262 }
263
Steven Moreland659416d2021-05-11 00:47:50 +0000264 LOG_ALWAYS_FATAL_IF(!session->removeServerConnection(connection),
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000265 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000266
Steven Moreland659416d2021-05-11 00:47:50 +0000267 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000268 {
Steven Moreland659416d2021-05-11 00:47:50 +0000269 std::lock_guard<std::mutex> _l(session->mMutex);
270 auto it = session->mThreads.find(std::this_thread::get_id());
271 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000272 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000273 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000274
Steven Moreland659416d2021-05-11 00:47:50 +0000275 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000276 }
277
Steven Moreland659416d2021-05-11 00:47:50 +0000278 session = nullptr;
279
280 if (listener != nullptr) {
281 listener->onSessionServerThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000282 }
283}
284
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000285wp<RpcServer> RpcSession::server() {
286 return mForServer;
287}
288
289bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
290 {
291 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000292 LOG_ALWAYS_FATAL_IF(mClientConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000293 "Must only setup session once, but already has %zu clients",
Steven Morelandbb543a82021-05-11 02:31:50 +0000294 mClientConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000295 }
296
Steven Moreland659416d2021-05-11 00:47:50 +0000297 if (!setupOneSocketConnection(addr, RPC_SESSION_ID_NEW, false /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000298
299 // TODO(b/185167543): we should add additional sessions dynamically
300 // instead of all at once.
301 // TODO(b/186470974): first risk of blocking
302 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000303 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000304 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
305 statusToString(status).c_str());
306 return false;
307 }
308
309 if (status_t status = readId(); status != OK) {
310 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
311 statusToString(status).c_str());
312 return false;
313 }
314
315 // we've already setup one client
316 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000317 // TODO(b/185167543): shutdown existing connections?
Steven Moreland659416d2021-05-11 00:47:50 +0000318 if (!setupOneSocketConnection(addr, mId.value(), false /*reverse*/)) return false;
319 }
320
321 // TODO(b/185167543): we should add additional sessions dynamically
322 // instead of all at once - the other side should be responsible for setting
323 // up additional connections. We need to create at least one (unless 0 are
324 // requested to be set) in order to allow the other side to reliably make
325 // any requests at all.
326
Steven Moreland103424e2021-06-02 18:16:19 +0000327 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland659416d2021-05-11 00:47:50 +0000328 if (!setupOneSocketConnection(addr, mId.value(), true /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000329 }
330
331 return true;
332}
333
Steven Moreland659416d2021-05-11 00:47:50 +0000334bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, int32_t id, bool reverse) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000335 for (size_t tries = 0; tries < 5; tries++) {
336 if (tries > 0) usleep(10000);
337
338 unique_fd serverFd(
339 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
340 if (serverFd == -1) {
341 int savedErrno = errno;
342 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
343 strerror(savedErrno));
344 return false;
345 }
346
347 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
348 if (errno == ECONNRESET) {
349 ALOGW("Connection reset on %s", addr.toString().c_str());
350 continue;
351 }
352 int savedErrno = errno;
353 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
354 strerror(savedErrno));
355 return false;
356 }
357
Steven Moreland659416d2021-05-11 00:47:50 +0000358 RpcConnectionHeader header{
359 .sessionId = id,
360 };
361 if (reverse) header.options |= RPC_CONNECTION_OPTION_REVERSE;
362
363 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000364 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000365 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000366 strerror(savedErrno));
367 return false;
368 }
369
370 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
371
Steven Moreland659416d2021-05-11 00:47:50 +0000372 if (reverse) {
373 std::mutex mutex;
374 std::condition_variable joinCv;
375 std::unique_lock<std::mutex> lock(mutex);
376 std::thread thread;
377 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
378 bool ownershipTransferred = false;
379 thread = std::thread([&]() {
380 std::unique_lock<std::mutex> threadLock(mutex);
381 unique_fd fd = std::move(serverFd);
382 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
383 sp<RpcSession> session = thiz;
384 session->preJoin(std::move(thread));
385 ownershipTransferred = true;
386 joinCv.notify_one();
387
388 threadLock.unlock();
389 // do not use & vars below
390
391 RpcSession::join(std::move(session), std::move(fd));
392 });
393 joinCv.wait(lock, [&] { return ownershipTransferred; });
394 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
395 return true;
396 } else {
397 return addClientConnection(std::move(serverFd));
398 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000399 }
400
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000401 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
402 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000403}
404
Steven Morelandb0dd1182021-05-25 01:56:46 +0000405bool RpcSession::addClientConnection(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000406 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000407
Steven Moreland659416d2021-05-11 00:47:50 +0000408 // first client connection added, but setForServer not called, so
409 // initializaing for a client.
Steven Morelandee3f4662021-05-22 01:07:33 +0000410 if (mShutdownTrigger == nullptr) {
411 mShutdownTrigger = FdTrigger::make();
Steven Moreland659416d2021-05-11 00:47:50 +0000412 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
Steven Morelandb0dd1182021-05-25 01:56:46 +0000413 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000414 }
415
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000416 sp<RpcConnection> session = sp<RpcConnection>::make();
417 session->fd = std::move(fd);
Steven Morelandbb543a82021-05-11 02:31:50 +0000418 mClientConnections.push_back(session);
Steven Morelandb0dd1182021-05-25 01:56:46 +0000419 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000420}
421
Steven Morelanda8b44292021-06-08 01:27:53 +0000422bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
423 int32_t sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000424 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
425 LOG_ALWAYS_FATAL_IF(server == nullptr);
426 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
427 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000428 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000429
430 mShutdownTrigger = FdTrigger::make();
431 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000432
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000433 mId = sessionId;
434 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000435 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000436 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000437}
438
439sp<RpcSession::RpcConnection> RpcSession::assignServerToThisThread(unique_fd fd) {
440 std::lock_guard<std::mutex> _l(mMutex);
441 sp<RpcConnection> session = sp<RpcConnection>::make();
442 session->fd = std::move(fd);
443 session->exclusiveTid = gettid();
Steven Morelandbb543a82021-05-11 02:31:50 +0000444 mServerConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000445
446 return session;
447}
448
449bool RpcSession::removeServerConnection(const sp<RpcConnection>& connection) {
450 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000451 if (auto it = std::find(mServerConnections.begin(), mServerConnections.end(), connection);
452 it != mServerConnections.end()) {
453 mServerConnections.erase(it);
454 if (mServerConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000455 sp<EventListener> listener = mEventListener.promote();
456 if (listener) {
457 listener->onSessionLockedAllServerThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000458 }
Steven Morelandee78e762021-05-05 21:12:51 +0000459 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000460 return true;
461 }
462 return false;
463}
464
465RpcSession::ExclusiveConnection::ExclusiveConnection(const sp<RpcSession>& session,
466 ConnectionUse use)
467 : mSession(session) {
468 pid_t tid = gettid();
469 std::unique_lock<std::mutex> _l(mSession->mMutex);
470
471 mSession->mWaitingThreads++;
472 while (true) {
473 sp<RpcConnection> exclusive;
474 sp<RpcConnection> available;
475
476 // CHECK FOR DEDICATED CLIENT SOCKET
477 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000478 // A server/looper should always use a dedicated connection if available
Steven Morelandbb543a82021-05-11 02:31:50 +0000479 findConnection(tid, &exclusive, &available, mSession->mClientConnections,
480 mSession->mClientConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000481
482 // WARNING: this assumes a server cannot request its client to send
Steven Morelandbb543a82021-05-11 02:31:50 +0000483 // a transaction, as mServerConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000484 //
485 // Imagine we have more than one thread in play, and a single thread
486 // sends a synchronous, then an asynchronous command. Imagine the
487 // asynchronous command is sent on the first client connection. Then, if
488 // we naively send a synchronous command to that same connection, the
489 // thread on the far side might be busy processing the asynchronous
490 // command. So, we move to considering the second available thread
491 // for subsequent calls.
492 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelandbb543a82021-05-11 02:31:50 +0000493 mSession->mClientConnectionsOffset =
494 (mSession->mClientConnectionsOffset + 1) % mSession->mClientConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000495 }
496
497 // USE SERVING SOCKET (for nested transaction)
498 //
499 // asynchronous calls cannot be nested
500 if (use != ConnectionUse::CLIENT_ASYNC) {
501 // server connections are always assigned to a thread
Steven Morelandbb543a82021-05-11 02:31:50 +0000502 findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServerConnections,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000503 0 /* index hint */);
504 }
505
Steven Moreland85e067b2021-05-26 17:43:53 +0000506 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000507 if (exclusive != nullptr) {
508 mConnection = exclusive;
509 mReentrant = true;
510 break;
511 } else if (available != nullptr) {
512 mConnection = available;
513 mConnection->exclusiveTid = tid;
514 break;
515 }
516
Steven Moreland659416d2021-05-11 00:47:50 +0000517 // TODO(b/185167543): this should return an error, rather than crash a
518 // server
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000519 // in regular binder, this would usually be a deadlock :)
Steven Morelandbb543a82021-05-11 02:31:50 +0000520 LOG_ALWAYS_FATAL_IF(mSession->mClientConnections.size() == 0,
Steven Moreland85e067b2021-05-26 17:43:53 +0000521 "Session has no client connections. This is required for an RPC server "
522 "to make any non-nested (e.g. oneway or on another thread) calls.");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000523
Steven Moreland85e067b2021-05-26 17:43:53 +0000524 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelandbb543a82021-05-11 02:31:50 +0000525 mSession->mClientConnections.size(), mSession->mServerConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000526 mSession->mAvailableConnectionCv.wait(_l);
527 }
528 mSession->mWaitingThreads--;
529}
530
531void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
532 sp<RpcConnection>* available,
533 std::vector<sp<RpcConnection>>& sockets,
534 size_t socketsIndexHint) {
535 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
536 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
537
538 if (*exclusive != nullptr) return; // consistent with break below
539
540 for (size_t i = 0; i < sockets.size(); i++) {
541 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
542
Steven Moreland85e067b2021-05-26 17:43:53 +0000543 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000544 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
545 *available = socket;
546 continue;
547 }
548
Steven Moreland85e067b2021-05-26 17:43:53 +0000549 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000550 // (nested transactions)
551 if (exclusive && socket->exclusiveTid == tid) {
552 *exclusive = socket;
553 break; // consistent with return above
554 }
555 }
556}
557
558RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000559 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000560 // is using this fd, and it retains the right to it. So, we don't give up
561 // exclusive ownership, and no thread is freed.
562 if (!mReentrant) {
563 std::unique_lock<std::mutex> _l(mSession->mMutex);
564 mConnection->exclusiveTid = std::nullopt;
565 if (mSession->mWaitingThreads > 0) {
566 _l.unlock();
567 mSession->mAvailableConnectionCv.notify_one();
568 }
569 }
570}
571
572} // namespace android