blob: 73061b894838a7be75ddfdc19bc9e4f2589b4fc7 [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
Yifan Hong194acf22021-06-29 18:44:56 -070021#include <dlfcn.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000022#include <inttypes.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000023#include <poll.h>
Yifan Hong194acf22021-06-29 18:44:56 -070024#include <pthread.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000025#include <unistd.h>
26
27#include <string_view>
28
Steven Moreland4ec3c432021-05-20 00:32:47 +000029#include <android-base/macros.h>
Yifan Hong194acf22021-06-29 18:44:56 -070030#include <android_runtime/vm.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000031#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000032#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070033#include <binder/RpcTransportRaw.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000034#include <binder/Stability.h>
Yifan Hong194acf22021-06-29 18:44:56 -070035#include <jni.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000036#include <utils/String8.h>
37
Yifan Hong8c950422021-08-05 17:13:55 -070038#include "FdTrigger.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000039#include "RpcSocketAddress.h"
40#include "RpcState.h"
41#include "RpcWireFormat.h"
Yifan Hongb675ffe2021-08-05 16:37:17 -070042#include "Utils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000043
44#ifdef __GLIBC__
45extern "C" pid_t gettid();
46#endif
47
48namespace android {
49
50using base::unique_fd;
51
Yifan Hong702115c2021-06-24 15:39:18 -070052RpcSession::RpcSession(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory)
53 : mRpcTransportCtxFactory(std::move(rpcTransportCtxFactory)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000054 LOG_RPC_DETAIL("RpcSession created %p", this);
55
56 mState = std::make_unique<RpcState>();
57}
58RpcSession::~RpcSession() {
59 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
60
61 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000062 LOG_ALWAYS_FATAL_IF(mIncomingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000063 "Should not be able to destroy a session with servers in use.");
64}
65
Yifan Hong702115c2021-06-24 15:39:18 -070066sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
67 // Default is without TLS.
68 if (rpcTransportCtxFactory == nullptr)
69 rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
70 return sp<RpcSession>::make(std::move(rpcTransportCtxFactory));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000071}
72
Steven Moreland103424e2021-06-02 18:16:19 +000073void RpcSession::setMaxThreads(size_t threads) {
74 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000075 LOG_ALWAYS_FATAL_IF(!mOutgoingConnections.empty() || !mIncomingConnections.empty(),
Steven Moreland103424e2021-06-02 18:16:19 +000076 "Must set max threads before setting up connections, but has %zu client(s) "
77 "and %zu server(s)",
Steven Moreland19fc9f72021-06-10 03:57:30 +000078 mOutgoingConnections.size(), mIncomingConnections.size());
Steven Moreland103424e2021-06-02 18:16:19 +000079 mMaxThreads = threads;
80}
81
82size_t RpcSession::getMaxThreads() {
83 std::lock_guard<std::mutex> _l(mMutex);
84 return mMaxThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000085}
86
Steven Morelandbf57bce2021-07-26 15:26:12 -070087bool RpcSession::setProtocolVersion(uint32_t version) {
88 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
89 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
90 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
91 "is %u).",
92 version, RPC_WIRE_PROTOCOL_VERSION);
93 return false;
94 }
95
96 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -070097 if (mProtocolVersion && version > *mProtocolVersion) {
98 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
99 *mProtocolVersion, version);
100 return false;
101 }
102
Steven Morelandbf57bce2021-07-26 15:26:12 -0700103 mProtocolVersion = version;
104 return true;
105}
106
107std::optional<uint32_t> RpcSession::getProtocolVersion() {
108 std::lock_guard<std::mutex> _l(mMutex);
109 return mProtocolVersion;
110}
111
Steven Moreland2372f9d2021-08-05 15:42:01 -0700112status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000113 return setupSocketClient(UnixSocketAddress(path));
114}
115
Steven Moreland2372f9d2021-08-05 15:42:01 -0700116status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000117 return setupSocketClient(VsockSocketAddress(cid, port));
118}
119
Steven Moreland2372f9d2021-08-05 15:42:01 -0700120status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000121 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700122 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000123 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
124 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700125 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000126 }
127 ALOGE("None of the socket address resolved for %s:%u can be added as inet client.", addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700128 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000129}
130
Steven Moreland2372f9d2021-08-05 15:42:01 -0700131status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
132 return setupClient([&](const RpcAddress& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700133 // std::move'd from fd becomes -1 (!ok())
134 if (!fd.ok()) {
135 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700136 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700137 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700138 if (auto res = setNonBlocking(fd); !res.ok()) {
139 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
140 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
141 }
Steven Moreland4198a122021-08-03 17:37:58 -0700142 return initAndAddConnection(std::move(fd), sessionId, incoming);
143 });
144}
145
Steven Moreland2372f9d2021-08-05 15:42:01 -0700146status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700147 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700148 if (auto status = initShutdownTrigger(); status != OK) return status;
149
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000150 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
151
152 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700153 int savedErrno = errno;
154 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
155 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000156 }
157
Yifan Hong702115c2021-06-24 15:39:18 -0700158 auto ctx = mRpcTransportCtxFactory->newClientCtx();
159 if (ctx == nullptr) {
160 ALOGE("Unable to create RpcTransportCtx for null debugging client");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700161 return NO_MEMORY;
Yifan Hong702115c2021-06-24 15:39:18 -0700162 }
163 auto server = ctx->newTransport(std::move(serverFd));
164 if (server == nullptr) {
165 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700166 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700167 }
168 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000169}
170
171sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000172 ExclusiveConnection connection;
173 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
174 ConnectionUse::CLIENT, &connection);
175 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000176 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000177}
178
Steven Moreland1be91352021-05-11 22:12:15 +0000179status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000180 ExclusiveConnection connection;
181 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
182 ConnectionUse::CLIENT, &connection);
183 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000184 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000185}
186
Steven Morelandc9d7b532021-06-04 20:57:41 +0000187bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000188 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000189 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000190
191 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000192
Steven Morelandc9d7b532021-06-04 20:57:41 +0000193 if (wait) {
194 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
195 mShutdownListener->waitForShutdown(_l);
Steven Morelanddd67b942021-07-23 17:15:41 -0700196
Steven Morelandc9d7b532021-06-04 20:57:41 +0000197 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
198 }
199
200 _l.unlock();
201 mState->clear();
202
Steven Moreland659416d2021-05-11 00:47:50 +0000203 return true;
204}
205
Steven Morelandf5174272021-05-25 00:39:28 +0000206status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000207 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000208 ExclusiveConnection connection;
209 status_t status =
210 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
211 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
212 : ConnectionUse::CLIENT,
213 &connection);
214 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000215 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000216 sp<RpcSession>::fromExisting(this), reply, flags);
217}
218
219status_t RpcSession::sendDecStrong(const RpcAddress& address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000220 ExclusiveConnection connection;
221 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
222 ConnectionUse::CLIENT_REFCOUNT, &connection);
223 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000224 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000225}
226
227status_t RpcSession::readId() {
228 {
229 std::lock_guard<std::mutex> _l(mMutex);
230 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
231 }
232
Steven Moreland195edb82021-06-08 02:44:39 +0000233 ExclusiveConnection connection;
234 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
235 ConnectionUse::CLIENT, &connection);
236 if (status != OK) return status;
237
Steven Moreland01a6bad2021-06-11 00:59:20 +0000238 mId = RpcAddress::zero();
239 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this),
240 &mId.value());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000241 if (status != OK) return status;
242
Steven Moreland01a6bad2021-06-11 00:59:20 +0000243 LOG_RPC_DETAIL("RpcSession %p has id %s", this, mId->toString().c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000244 return OK;
245}
246
Steven Morelanddd67b942021-07-23 17:15:41 -0700247void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000248 const sp<RpcSession>& session) {
249 (void)session;
250 mShutdown = true;
251}
252
Steven Moreland19fc9f72021-06-10 03:57:30 +0000253void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000254 mCv.notify_all();
255}
256
257void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
258 while (!mShutdown) {
259 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
260 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
261 }
262 }
263}
264
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000265void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000266 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000267
Steven Morelanda63ff932021-05-12 00:03:15 +0000268 {
269 std::lock_guard<std::mutex> _l(mMutex);
270 mThreads[thread.get_id()] = std::move(thread);
271 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000272}
Steven Morelanda63ff932021-05-12 00:03:15 +0000273
Yifan Hong702115c2021-06-24 15:39:18 -0700274RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
275 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000276 // must be registered to allow arbitrary client code executing commands to
277 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700278 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000279
Steven Morelanddd67b942021-07-23 17:15:41 -0700280 status_t status;
281
282 if (connection == nullptr) {
283 status = DEAD_OBJECT;
284 } else {
285 status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
286 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000287
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000288 return PreJoinSetupResult{
289 .connection = std::move(connection),
290 .status = status,
291 };
292}
293
Yifan Hong194acf22021-06-29 18:44:56 -0700294namespace {
295// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
296// Android Runtime doesn't exist, no-op.
297class JavaThreadAttacher {
298public:
299 JavaThreadAttacher() {
300 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
301 // libbinder.
302 auto vm = getJavaVM();
303 if (vm == nullptr) return;
304
305 char threadName[16];
306 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
307 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
308 memcpy(threadName, defaultThreadName,
309 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
310 }
311 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
312 JavaVMAttachArgs args;
313 args.version = JNI_VERSION_1_2;
314 args.name = threadName;
315 args.group = nullptr;
316 JNIEnv* env;
317
318 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
319 "Cannot attach thread %s to JVM", threadName);
320 mAttached = true;
321 }
322 ~JavaThreadAttacher() {
323 if (!mAttached) return;
324 auto vm = getJavaVM();
325 LOG_ALWAYS_FATAL_IF(vm == nullptr,
326 "Unable to detach thread. No JavaVM, but it was present before!");
327
328 LOG_RPC_DETAIL("Detaching current thread from JVM");
329 if (vm->DetachCurrentThread() != JNI_OK) {
330 mAttached = false;
331 } else {
332 ALOGW("Unable to detach current thread from JVM");
333 }
334 }
335
336private:
337 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
338 bool mAttached = false;
339
340 static JavaVM* getJavaVM() {
341 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
342 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
343 if (fn == nullptr) return nullptr;
344 return fn();
345 }
346};
347} // namespace
348
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000349void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
350 sp<RpcConnection>& connection = setupResult.connection;
351
352 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700353 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hong194acf22021-06-29 18:44:56 -0700354 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000355 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000356 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000357 RpcState::CommandType::ANY);
358 if (status != OK) {
359 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
360 statusToString(status).c_str());
361 break;
362 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000363 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000364 } else {
365 ALOGE("Connection failed to init, closing with status %s",
366 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000367 }
368
Steven Moreland659416d2021-05-11 00:47:50 +0000369 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000370 {
Steven Moreland659416d2021-05-11 00:47:50 +0000371 std::lock_guard<std::mutex> _l(session->mMutex);
372 auto it = session->mThreads.find(std::this_thread::get_id());
373 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000374 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000375 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000376
Steven Moreland659416d2021-05-11 00:47:50 +0000377 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000378 }
379
Steven Morelanddd67b942021-07-23 17:15:41 -0700380 // done after all cleanup, since session shutdown progresses via callbacks here
381 if (connection != nullptr) {
382 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
383 "bad state: connection object guaranteed to be in list");
384 }
385
Steven Moreland659416d2021-05-11 00:47:50 +0000386 session = nullptr;
387
388 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000389 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000390 }
391}
392
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000393sp<RpcServer> RpcSession::server() {
394 RpcServer* unsafeServer = mForServer.unsafe_get();
395 sp<RpcServer> server = mForServer.promote();
396
397 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
398 "wp<> is to avoid strong cycle only");
399 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000400}
401
Steven Moreland2372f9d2021-08-05 15:42:01 -0700402status_t RpcSession::setupClient(
403 const std::function<status_t(const RpcAddress& sessionId, bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000404 {
405 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000406 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000407 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000408 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409 }
Yifan Hong832521e2021-08-05 14:55:40 -0700410 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000411
Steven Moreland2372f9d2021-08-05 15:42:01 -0700412 if (status_t status = connectAndInit(RpcAddress::zero(), false /*incoming*/); status != OK)
413 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000414
Steven Morelandbf57bce2021-07-26 15:26:12 -0700415 {
416 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700417 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
418 ConnectionUse::CLIENT, &connection);
419 status != OK)
420 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700421
422 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700423 if (status_t status =
424 state()->readNewSessionResponse(connection.get(),
425 sp<RpcSession>::fromExisting(this), &version);
426 status != OK)
427 return status;
428 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700429 }
430
Steven Morelanda5036f02021-06-08 02:26:57 +0000431 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000432 // instead of all at once.
433 // TODO(b/186470974): first risk of blocking
434 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000435 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700436 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000437 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700438 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000439 }
440
441 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700442 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000443 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700444 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000445 }
446
Steven Morelanda5036f02021-06-08 02:26:57 +0000447 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000448 // instead of all at once - the other side should be responsible for setting
449 // up additional connections. We need to create at least one (unless 0 are
450 // requested to be set) in order to allow the other side to reliably make
451 // any requests at all.
452
Steven Moreland4198a122021-08-03 17:37:58 -0700453 // we've already setup one client
454 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700455 if (status_t status = connectAndInit(mId.value(), false /*incoming*/); status != OK)
456 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700457 }
458
Steven Moreland103424e2021-06-02 18:16:19 +0000459 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700460 if (status_t status = connectAndInit(mId.value(), true /*incoming*/); status != OK)
461 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000462 }
463
Steven Moreland2372f9d2021-08-05 15:42:01 -0700464 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000465}
466
Steven Moreland2372f9d2021-08-05 15:42:01 -0700467status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700468 return setupClient([&](const RpcAddress& sessionId, bool incoming) {
469 return setupOneSocketConnection(addr, sessionId, incoming);
470 });
471}
472
Steven Moreland2372f9d2021-08-05 15:42:01 -0700473status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
474 const RpcAddress& sessionId, bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000475 for (size_t tries = 0; tries < 5; tries++) {
476 if (tries > 0) usleep(10000);
477
Yifan Hongb675ffe2021-08-05 16:37:17 -0700478 unique_fd serverFd(TEMP_FAILURE_RETRY(
479 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000480 if (serverFd == -1) {
481 int savedErrno = errno;
482 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
483 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700484 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000485 }
486
487 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
488 if (errno == ECONNRESET) {
489 ALOGW("Connection reset on %s", addr.toString().c_str());
490 continue;
491 }
492 int savedErrno = errno;
493 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
494 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700495 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000496 }
Yifan Hong702115c2021-06-24 15:39:18 -0700497 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
498
Steven Moreland4198a122021-08-03 17:37:58 -0700499 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000500 }
501
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000502 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700503 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000504}
505
Steven Moreland2372f9d2021-08-05 15:42:01 -0700506status_t RpcSession::initAndAddConnection(unique_fd fd, const RpcAddress& sessionId,
507 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700508 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Steven Moreland4198a122021-08-03 17:37:58 -0700509 auto ctx = mRpcTransportCtxFactory->newClientCtx();
510 if (ctx == nullptr) {
511 ALOGE("Unable to create client RpcTransportCtx with %s sockets",
512 mRpcTransportCtxFactory->toCString());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700513 return NO_MEMORY;
Steven Moreland4198a122021-08-03 17:37:58 -0700514 }
515 auto server = ctx->newTransport(std::move(fd));
516 if (server == nullptr) {
517 ALOGE("Unable to set up RpcTransport in %s context", mRpcTransportCtxFactory->toCString());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700518 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700519 }
520
521 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
522
523 RpcConnectionHeader header{
524 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
525 .options = 0,
526 };
527 memcpy(&header.sessionId, &sessionId.viewRawEmbedded(), sizeof(RpcWireAddress));
528
529 if (incoming) header.options |= RPC_CONNECTION_OPTION_INCOMING;
530
Yifan Hong8c950422021-08-05 17:13:55 -0700531 auto sendHeaderStatus =
532 server->interruptableWriteFully(mShutdownTrigger.get(), &header, sizeof(header));
533 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700534 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700535 statusToString(sendHeaderStatus).c_str());
536 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700537 }
538
539 LOG_RPC_DETAIL("Socket at client: header sent");
540
541 if (incoming) {
542 return addIncomingConnection(std::move(server));
543 } else {
544 return addOutgoingConnection(std::move(server), true /*init*/);
545 }
546}
547
Steven Moreland2372f9d2021-08-05 15:42:01 -0700548status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000549 std::mutex mutex;
550 std::condition_variable joinCv;
551 std::unique_lock<std::mutex> lock(mutex);
552 std::thread thread;
553 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
554 bool ownershipTransferred = false;
555 thread = std::thread([&]() {
556 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700557 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000558 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
559 sp<RpcSession> session = thiz;
560 session->preJoinThreadOwnership(std::move(thread));
561
562 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700563 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000564
565 ownershipTransferred = true;
566 threadLock.unlock();
567 joinCv.notify_one();
568 // do not use & vars below
569
570 RpcSession::join(std::move(session), std::move(setupResult));
571 });
572 joinCv.wait(lock, [&] { return ownershipTransferred; });
573 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700574 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000575}
576
Yifan Hong832521e2021-08-05 14:55:40 -0700577status_t RpcSession::initShutdownTrigger() {
578 // first client connection added, but setForServer not called, so
579 // initializaing for a client.
580 if (mShutdownTrigger == nullptr) {
581 mShutdownTrigger = FdTrigger::make();
582 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
583 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
584 }
585 return OK;
586}
587
Steven Moreland2372f9d2021-08-05 15:42:01 -0700588status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000589 sp<RpcConnection> connection = sp<RpcConnection>::make();
590 {
591 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700592 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000593 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000594 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000595 }
596
Steven Morelandb86e26b2021-06-12 00:35:58 +0000597 status_t status = OK;
598 if (init) {
599 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
600 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000601
602 {
603 std::lock_guard<std::mutex> _l(mMutex);
604 connection->exclusiveTid = std::nullopt;
605 }
606
Steven Moreland2372f9d2021-08-05 15:42:01 -0700607 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000608}
609
Steven Morelanda8b44292021-06-08 01:27:53 +0000610bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000611 const RpcAddress& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000612 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
613 LOG_ALWAYS_FATAL_IF(server == nullptr);
614 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
615 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000616 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000617
618 mShutdownTrigger = FdTrigger::make();
619 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000620
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000621 mId = sessionId;
622 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000623 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000624 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000625}
626
Yifan Hong702115c2021-06-24 15:39:18 -0700627sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
628 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000629 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700630
Steven Moreland132d5bf2021-08-03 16:13:24 -0700631 if (mIncomingConnections.size() >= mMaxThreads) {
632 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
633 mIncomingConnections.size(), mMaxThreads);
634 return nullptr;
635 }
636
Steven Morelanddd67b942021-07-23 17:15:41 -0700637 // Don't accept any more connections, some have shutdown. Usually this
638 // happens when new connections are still being established as part of a
639 // very short-lived session which shuts down after it already started
640 // accepting new connections.
641 if (mIncomingConnections.size() < mMaxIncomingConnections) {
642 return nullptr;
643 }
644
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000645 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700646 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000647 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700648
Steven Moreland19fc9f72021-06-10 03:57:30 +0000649 mIncomingConnections.push_back(session);
Steven Morelanddd67b942021-07-23 17:15:41 -0700650 mMaxIncomingConnections = mIncomingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000651
652 return session;
653}
654
Steven Moreland19fc9f72021-06-10 03:57:30 +0000655bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700656 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000657 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
658 it != mIncomingConnections.end()) {
659 mIncomingConnections.erase(it);
660 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000661 sp<EventListener> listener = mEventListener.promote();
662 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700663 _l.unlock();
664 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000665 }
Steven Morelandee78e762021-05-05 21:12:51 +0000666 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000667 return true;
668 }
669 return false;
670}
671
Steven Moreland195edb82021-06-08 02:44:39 +0000672status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
673 ExclusiveConnection* connection) {
674 connection->mSession = session;
675 connection->mConnection = nullptr;
676 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000677
Steven Moreland195edb82021-06-08 02:44:39 +0000678 pid_t tid = gettid();
679 std::unique_lock<std::mutex> _l(session->mMutex);
680
681 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000682 while (true) {
683 sp<RpcConnection> exclusive;
684 sp<RpcConnection> available;
685
686 // CHECK FOR DEDICATED CLIENT SOCKET
687 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000688 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000689 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
690 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000691
692 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000693 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000694 //
695 // Imagine we have more than one thread in play, and a single thread
696 // sends a synchronous, then an asynchronous command. Imagine the
697 // asynchronous command is sent on the first client connection. Then, if
698 // we naively send a synchronous command to that same connection, the
699 // thread on the far side might be busy processing the asynchronous
700 // command. So, we move to considering the second available thread
701 // for subsequent calls.
702 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000703 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
704 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000705 }
706
Steven Morelandc7d40132021-06-10 03:42:11 +0000707 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000708 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000709 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000710 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000711 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
712 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000713
714 // asynchronous calls cannot be nested, we currently allow ref count
715 // calls to be nested (so that you can use this without having extra
716 // threads). Note 'drainCommands' is used so that these ref counts can't
717 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000718 if (exclusiveIncoming != nullptr) {
719 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000720 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000721 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000722 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
723 // prefer available socket, but if we don't have one, don't
724 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000725 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000726 }
727 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000728 }
729
Steven Moreland85e067b2021-05-26 17:43:53 +0000730 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000731 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000732 connection->mConnection = exclusive;
733 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000734 break;
735 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000736 connection->mConnection = available;
737 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000738 break;
739 }
740
Steven Moreland19fc9f72021-06-10 03:57:30 +0000741 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000742 ALOGE("Session has no client connections. This is required for an RPC server to make "
743 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
744 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000745 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000746 return WOULD_BLOCK;
747 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000748
Steven Moreland85e067b2021-05-26 17:43:53 +0000749 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000750 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000751 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000752 }
Steven Moreland195edb82021-06-08 02:44:39 +0000753 session->mWaitingThreads--;
754
755 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000756}
757
758void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
759 sp<RpcConnection>* available,
760 std::vector<sp<RpcConnection>>& sockets,
761 size_t socketsIndexHint) {
762 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
763 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
764
765 if (*exclusive != nullptr) return; // consistent with break below
766
767 for (size_t i = 0; i < sockets.size(); i++) {
768 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
769
Steven Moreland85e067b2021-05-26 17:43:53 +0000770 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000771 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
772 *available = socket;
773 continue;
774 }
775
Steven Moreland85e067b2021-05-26 17:43:53 +0000776 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000777 // (nested transactions)
778 if (exclusive && socket->exclusiveTid == tid) {
779 *exclusive = socket;
780 break; // consistent with return above
781 }
782 }
783}
784
785RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000786 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000787 // is using this fd, and it retains the right to it. So, we don't give up
788 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000789 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000790 std::unique_lock<std::mutex> _l(mSession->mMutex);
791 mConnection->exclusiveTid = std::nullopt;
792 if (mSession->mWaitingThreads > 0) {
793 _l.unlock();
794 mSession->mAvailableConnectionCv.notify_one();
795 }
796 }
797}
798
799} // namespace android