blob: 2a230d290df4f7b7deef09bfa442a637b4f182a1 [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 Morelandc88b7fc2021-06-10 00:40:39 +0000239void RpcSession::preJoinThreadOwnership(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 Morelandc88b7fc2021-06-10 00:40:39 +0000248RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(base::unique_fd fd) {
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 Morelandc88b7fc2021-06-10 00:40:39 +0000251 sp<RpcConnection> connection = assignServerToThisThread(std::move(fd));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000252
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000253 status_t status =
254 mState->readConnectionInit(connection->fd, sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000255
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000256 return PreJoinSetupResult{
257 .connection = std::move(connection),
258 .status = status,
259 };
260}
261
262void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
263 sp<RpcConnection>& connection = setupResult.connection;
264
265 if (setupResult.status == OK) {
266 while (true) {
267 status_t status = session->state()->getAndExecuteCommand(connection->fd, session,
268 RpcState::CommandType::ANY);
269 if (status != OK) {
270 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
271 statusToString(status).c_str());
272 break;
273 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000274 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000275 } else {
276 ALOGE("Connection failed to init, closing with status %s",
277 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000278 }
279
Steven Moreland659416d2021-05-11 00:47:50 +0000280 LOG_ALWAYS_FATAL_IF(!session->removeServerConnection(connection),
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000281 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000282
Steven Moreland659416d2021-05-11 00:47:50 +0000283 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000284 {
Steven Moreland659416d2021-05-11 00:47:50 +0000285 std::lock_guard<std::mutex> _l(session->mMutex);
286 auto it = session->mThreads.find(std::this_thread::get_id());
287 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000288 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000289 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000290
Steven Moreland659416d2021-05-11 00:47:50 +0000291 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000292 }
293
Steven Moreland659416d2021-05-11 00:47:50 +0000294 session = nullptr;
295
296 if (listener != nullptr) {
297 listener->onSessionServerThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000298 }
299}
300
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000301wp<RpcServer> RpcSession::server() {
302 return mForServer;
303}
304
305bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
306 {
307 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000308 LOG_ALWAYS_FATAL_IF(mClientConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000309 "Must only setup session once, but already has %zu clients",
Steven Morelandbb543a82021-05-11 02:31:50 +0000310 mClientConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000311 }
312
Steven Moreland659416d2021-05-11 00:47:50 +0000313 if (!setupOneSocketConnection(addr, RPC_SESSION_ID_NEW, false /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000314
Steven Morelanda5036f02021-06-08 02:26:57 +0000315 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000316 // instead of all at once.
317 // TODO(b/186470974): first risk of blocking
318 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000319 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000320 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
321 statusToString(status).c_str());
322 return false;
323 }
324
325 if (status_t status = readId(); status != OK) {
326 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
327 statusToString(status).c_str());
328 return false;
329 }
330
331 // we've already setup one client
332 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000333 // TODO(b/189955605): shutdown existing connections?
Steven Moreland659416d2021-05-11 00:47:50 +0000334 if (!setupOneSocketConnection(addr, mId.value(), false /*reverse*/)) return false;
335 }
336
Steven Morelanda5036f02021-06-08 02:26:57 +0000337 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000338 // instead of all at once - the other side should be responsible for setting
339 // up additional connections. We need to create at least one (unless 0 are
340 // requested to be set) in order to allow the other side to reliably make
341 // any requests at all.
342
Steven Moreland103424e2021-06-02 18:16:19 +0000343 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland659416d2021-05-11 00:47:50 +0000344 if (!setupOneSocketConnection(addr, mId.value(), true /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000345 }
346
347 return true;
348}
349
Steven Moreland659416d2021-05-11 00:47:50 +0000350bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, int32_t id, bool reverse) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000351 for (size_t tries = 0; tries < 5; tries++) {
352 if (tries > 0) usleep(10000);
353
354 unique_fd serverFd(
355 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
356 if (serverFd == -1) {
357 int savedErrno = errno;
358 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
359 strerror(savedErrno));
360 return false;
361 }
362
363 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
364 if (errno == ECONNRESET) {
365 ALOGW("Connection reset on %s", addr.toString().c_str());
366 continue;
367 }
368 int savedErrno = errno;
369 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
370 strerror(savedErrno));
371 return false;
372 }
373
Steven Moreland659416d2021-05-11 00:47:50 +0000374 RpcConnectionHeader header{
375 .sessionId = id,
376 };
377 if (reverse) header.options |= RPC_CONNECTION_OPTION_REVERSE;
378
379 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000380 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000381 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000382 strerror(savedErrno));
383 return false;
384 }
385
386 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
387
Steven Moreland659416d2021-05-11 00:47:50 +0000388 if (reverse) {
389 std::mutex mutex;
390 std::condition_variable joinCv;
391 std::unique_lock<std::mutex> lock(mutex);
392 std::thread thread;
393 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
394 bool ownershipTransferred = false;
395 thread = std::thread([&]() {
396 std::unique_lock<std::mutex> threadLock(mutex);
397 unique_fd fd = std::move(serverFd);
398 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
399 sp<RpcSession> session = thiz;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000400 session->preJoinThreadOwnership(std::move(thread));
Steven Moreland659416d2021-05-11 00:47:50 +0000401
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000402 // only continue once we have a response or the connection fails
403 auto setupResult = session->preJoinSetup(std::move(fd));
404
405 ownershipTransferred = true;
Steven Moreland659416d2021-05-11 00:47:50 +0000406 threadLock.unlock();
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000407 joinCv.notify_one();
Steven Moreland659416d2021-05-11 00:47:50 +0000408 // do not use & vars below
409
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000410 RpcSession::join(std::move(session), std::move(setupResult));
Steven Moreland659416d2021-05-11 00:47:50 +0000411 });
412 joinCv.wait(lock, [&] { return ownershipTransferred; });
413 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
414 return true;
415 } else {
416 return addClientConnection(std::move(serverFd));
417 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000418 }
419
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000420 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
421 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000422}
423
Steven Morelandb0dd1182021-05-25 01:56:46 +0000424bool RpcSession::addClientConnection(unique_fd fd) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000425 sp<RpcConnection> connection = sp<RpcConnection>::make();
426 {
427 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000428
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000429 // first client connection added, but setForServer not called, so
430 // initializaing for a client.
431 if (mShutdownTrigger == nullptr) {
432 mShutdownTrigger = FdTrigger::make();
433 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
434 if (mShutdownTrigger == nullptr) return false;
435 }
436
437 connection->fd = std::move(fd);
438 connection->exclusiveTid = gettid();
439 mClientConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000440 }
441
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000442 status_t status =
443 mState->sendConnectionInit(connection->fd, sp<RpcSession>::fromExisting(this));
444
445 {
446 std::lock_guard<std::mutex> _l(mMutex);
447 connection->exclusiveTid = std::nullopt;
448 }
449
450 return status == OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000451}
452
Steven Morelanda8b44292021-06-08 01:27:53 +0000453bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
454 int32_t sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000455 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
456 LOG_ALWAYS_FATAL_IF(server == nullptr);
457 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
458 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000459 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000460
461 mShutdownTrigger = FdTrigger::make();
462 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000463
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000464 mId = sessionId;
465 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000466 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000467 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000468}
469
470sp<RpcSession::RpcConnection> RpcSession::assignServerToThisThread(unique_fd fd) {
471 std::lock_guard<std::mutex> _l(mMutex);
472 sp<RpcConnection> session = sp<RpcConnection>::make();
473 session->fd = std::move(fd);
474 session->exclusiveTid = gettid();
Steven Morelandbb543a82021-05-11 02:31:50 +0000475 mServerConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000476
477 return session;
478}
479
480bool RpcSession::removeServerConnection(const sp<RpcConnection>& connection) {
481 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandbb543a82021-05-11 02:31:50 +0000482 if (auto it = std::find(mServerConnections.begin(), mServerConnections.end(), connection);
483 it != mServerConnections.end()) {
484 mServerConnections.erase(it);
485 if (mServerConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000486 sp<EventListener> listener = mEventListener.promote();
487 if (listener) {
488 listener->onSessionLockedAllServerThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000489 }
Steven Morelandee78e762021-05-05 21:12:51 +0000490 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000491 return true;
492 }
493 return false;
494}
495
496RpcSession::ExclusiveConnection::ExclusiveConnection(const sp<RpcSession>& session,
497 ConnectionUse use)
498 : mSession(session) {
499 pid_t tid = gettid();
500 std::unique_lock<std::mutex> _l(mSession->mMutex);
501
502 mSession->mWaitingThreads++;
503 while (true) {
504 sp<RpcConnection> exclusive;
505 sp<RpcConnection> available;
506
507 // CHECK FOR DEDICATED CLIENT SOCKET
508 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000509 // A server/looper should always use a dedicated connection if available
Steven Morelandbb543a82021-05-11 02:31:50 +0000510 findConnection(tid, &exclusive, &available, mSession->mClientConnections,
511 mSession->mClientConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000512
513 // WARNING: this assumes a server cannot request its client to send
Steven Morelandbb543a82021-05-11 02:31:50 +0000514 // a transaction, as mServerConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000515 //
516 // Imagine we have more than one thread in play, and a single thread
517 // sends a synchronous, then an asynchronous command. Imagine the
518 // asynchronous command is sent on the first client connection. Then, if
519 // we naively send a synchronous command to that same connection, the
520 // thread on the far side might be busy processing the asynchronous
521 // command. So, we move to considering the second available thread
522 // for subsequent calls.
523 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelandbb543a82021-05-11 02:31:50 +0000524 mSession->mClientConnectionsOffset =
525 (mSession->mClientConnectionsOffset + 1) % mSession->mClientConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000526 }
527
528 // USE SERVING SOCKET (for nested transaction)
529 //
530 // asynchronous calls cannot be nested
531 if (use != ConnectionUse::CLIENT_ASYNC) {
532 // server connections are always assigned to a thread
Steven Morelandbb543a82021-05-11 02:31:50 +0000533 findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServerConnections,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000534 0 /* index hint */);
535 }
536
Steven Moreland85e067b2021-05-26 17:43:53 +0000537 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000538 if (exclusive != nullptr) {
539 mConnection = exclusive;
540 mReentrant = true;
541 break;
542 } else if (available != nullptr) {
543 mConnection = available;
544 mConnection->exclusiveTid = tid;
545 break;
546 }
547
Steven Moreland659416d2021-05-11 00:47:50 +0000548 // TODO(b/185167543): this should return an error, rather than crash a
549 // server
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000550 // in regular binder, this would usually be a deadlock :)
Steven Morelandbb543a82021-05-11 02:31:50 +0000551 LOG_ALWAYS_FATAL_IF(mSession->mClientConnections.size() == 0,
Steven Moreland85e067b2021-05-26 17:43:53 +0000552 "Session has no client connections. This is required for an RPC server "
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000553 "to make any non-nested (e.g. oneway or on another thread) calls. "
554 "Use: %d. Server connections: %zu",
555 static_cast<int>(use), mSession->mServerConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000556
Steven Moreland85e067b2021-05-26 17:43:53 +0000557 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelandbb543a82021-05-11 02:31:50 +0000558 mSession->mClientConnections.size(), mSession->mServerConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000559 mSession->mAvailableConnectionCv.wait(_l);
560 }
561 mSession->mWaitingThreads--;
562}
563
564void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
565 sp<RpcConnection>* available,
566 std::vector<sp<RpcConnection>>& sockets,
567 size_t socketsIndexHint) {
568 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
569 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
570
571 if (*exclusive != nullptr) return; // consistent with break below
572
573 for (size_t i = 0; i < sockets.size(); i++) {
574 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
575
Steven Moreland85e067b2021-05-26 17:43:53 +0000576 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000577 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
578 *available = socket;
579 continue;
580 }
581
Steven Moreland85e067b2021-05-26 17:43:53 +0000582 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000583 // (nested transactions)
584 if (exclusive && socket->exclusiveTid == tid) {
585 *exclusive = socket;
586 break; // consistent with return above
587 }
588 }
589}
590
591RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000592 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000593 // is using this fd, and it retains the right to it. So, we don't give up
594 // exclusive ownership, and no thread is freed.
595 if (!mReentrant) {
596 std::unique_lock<std::mutex> _l(mSession->mMutex);
597 mConnection->exclusiveTid = std::nullopt;
598 if (mSession->mWaitingThreads > 0) {
599 _l.unlock();
600 mSession->mAvailableConnectionCv.notify_one();
601 }
602 }
603}
604
605} // namespace android