blob: 6a22913148e1ccf845303cba22f13910199ec7c0 [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
38#include "RpcSocketAddress.h"
39#include "RpcState.h"
40#include "RpcWireFormat.h"
41
42#ifdef __GLIBC__
43extern "C" pid_t gettid();
44#endif
45
46namespace android {
47
48using base::unique_fd;
49
Yifan Hong702115c2021-06-24 15:39:18 -070050RpcSession::RpcSession(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory)
51 : mRpcTransportCtxFactory(std::move(rpcTransportCtxFactory)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000052 LOG_RPC_DETAIL("RpcSession created %p", this);
53
54 mState = std::make_unique<RpcState>();
55}
56RpcSession::~RpcSession() {
57 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
58
59 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000060 LOG_ALWAYS_FATAL_IF(mIncomingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000061 "Should not be able to destroy a session with servers in use.");
62}
63
Yifan Hong702115c2021-06-24 15:39:18 -070064sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
65 // Default is without TLS.
66 if (rpcTransportCtxFactory == nullptr)
67 rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
68 return sp<RpcSession>::make(std::move(rpcTransportCtxFactory));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000069}
70
Steven Moreland103424e2021-06-02 18:16:19 +000071void RpcSession::setMaxThreads(size_t threads) {
72 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000073 LOG_ALWAYS_FATAL_IF(!mOutgoingConnections.empty() || !mIncomingConnections.empty(),
Steven Moreland103424e2021-06-02 18:16:19 +000074 "Must set max threads before setting up connections, but has %zu client(s) "
75 "and %zu server(s)",
Steven Moreland19fc9f72021-06-10 03:57:30 +000076 mOutgoingConnections.size(), mIncomingConnections.size());
Steven Moreland103424e2021-06-02 18:16:19 +000077 mMaxThreads = threads;
78}
79
80size_t RpcSession::getMaxThreads() {
81 std::lock_guard<std::mutex> _l(mMutex);
82 return mMaxThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000083}
84
Steven Morelandbf57bce2021-07-26 15:26:12 -070085bool RpcSession::setProtocolVersion(uint32_t version) {
86 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
87 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
88 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
89 "is %u).",
90 version, RPC_WIRE_PROTOCOL_VERSION);
91 return false;
92 }
93
94 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -070095 if (mProtocolVersion && version > *mProtocolVersion) {
96 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
97 *mProtocolVersion, version);
98 return false;
99 }
100
Steven Morelandbf57bce2021-07-26 15:26:12 -0700101 mProtocolVersion = version;
102 return true;
103}
104
105std::optional<uint32_t> RpcSession::getProtocolVersion() {
106 std::lock_guard<std::mutex> _l(mMutex);
107 return mProtocolVersion;
108}
109
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000110bool RpcSession::setupUnixDomainClient(const char* path) {
111 return setupSocketClient(UnixSocketAddress(path));
112}
113
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000114bool RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
115 return setupSocketClient(VsockSocketAddress(cid, port));
116}
117
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000118bool RpcSession::setupInetClient(const char* addr, unsigned int port) {
119 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
120 if (aiStart == nullptr) return false;
121 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
122 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
123 if (setupSocketClient(socketAddress)) return true;
124 }
125 ALOGE("None of the socket address resolved for %s:%u can be added as inet client.", addr, port);
126 return false;
127}
128
129bool RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700130 // Note: only works on raw sockets.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000131 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
132
133 if (serverFd == -1) {
134 ALOGE("Could not connect to /dev/null: %s", strerror(errno));
135 return false;
136 }
137
Yifan Hong702115c2021-06-24 15:39:18 -0700138 auto ctx = mRpcTransportCtxFactory->newClientCtx();
139 if (ctx == nullptr) {
140 ALOGE("Unable to create RpcTransportCtx for null debugging client");
141 return false;
142 }
143 auto server = ctx->newTransport(std::move(serverFd));
144 if (server == nullptr) {
145 ALOGE("Unable to set up RpcTransport");
146 return false;
147 }
148 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000149}
150
151sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000152 ExclusiveConnection connection;
153 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
154 ConnectionUse::CLIENT, &connection);
155 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000156 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000157}
158
Steven Moreland1be91352021-05-11 22:12:15 +0000159status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000160 ExclusiveConnection connection;
161 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
162 ConnectionUse::CLIENT, &connection);
163 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000164 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000165}
166
Steven Morelandc9d7b532021-06-04 20:57:41 +0000167bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000168 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000169 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000170
171 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000172
Steven Morelandc9d7b532021-06-04 20:57:41 +0000173 if (wait) {
174 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
175 mShutdownListener->waitForShutdown(_l);
Steven Morelanddd67b942021-07-23 17:15:41 -0700176
Steven Morelandc9d7b532021-06-04 20:57:41 +0000177 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
178 }
179
180 _l.unlock();
181 mState->clear();
182
Steven Moreland659416d2021-05-11 00:47:50 +0000183 return true;
184}
185
Steven Morelandf5174272021-05-25 00:39:28 +0000186status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000187 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000188 ExclusiveConnection connection;
189 status_t status =
190 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
191 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
192 : ConnectionUse::CLIENT,
193 &connection);
194 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000195 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000196 sp<RpcSession>::fromExisting(this), reply, flags);
197}
198
199status_t RpcSession::sendDecStrong(const RpcAddress& address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000200 ExclusiveConnection connection;
201 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
202 ConnectionUse::CLIENT_REFCOUNT, &connection);
203 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000204 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000205}
206
Steven Morelande47511f2021-05-20 00:07:41 +0000207std::unique_ptr<RpcSession::FdTrigger> RpcSession::FdTrigger::make() {
208 auto ret = std::make_unique<RpcSession::FdTrigger>();
Steven Morelanda8b44292021-06-08 01:27:53 +0000209 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) {
210 ALOGE("Could not create pipe %s", strerror(errno));
211 return nullptr;
212 }
Steven Morelande47511f2021-05-20 00:07:41 +0000213 return ret;
214}
215
216void RpcSession::FdTrigger::trigger() {
217 mWrite.reset();
218}
219
Steven Morelanda8b44292021-06-08 01:27:53 +0000220bool RpcSession::FdTrigger::isTriggered() {
221 return mWrite == -1;
222}
223
Yifan Hong702115c2021-06-24 15:39:18 -0700224status_t RpcSession::FdTrigger::triggerablePoll(RpcTransport* rpcTransport, int16_t event) {
225 return triggerablePoll(rpcTransport->pollSocket(), event);
226}
227
Steven Moreland798e0d12021-07-14 23:19:25 +0000228status_t RpcSession::FdTrigger::triggerablePoll(base::borrowed_fd fd, int16_t event) {
Steven Moreland4ec3c432021-05-20 00:32:47 +0000229 while (true) {
Steven Moreland441bb0e2021-07-21 22:36:32 +0000230 pollfd pfd[]{{.fd = fd.get(), .events = static_cast<int16_t>(event), .revents = 0},
Steven Moreland4ec3c432021-05-20 00:32:47 +0000231 {.fd = mRead.get(), .events = POLLHUP, .revents = 0}};
232 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
233 if (ret < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000234 return -errno;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000235 }
236 if (ret == 0) {
237 continue;
238 }
239 if (pfd[1].revents & POLLHUP) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000240 return -ECANCELED;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000241 }
Steven Moreland798e0d12021-07-14 23:19:25 +0000242 return pfd[0].revents & event ? OK : DEAD_OBJECT;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000243 }
244}
245
Yifan Hong702115c2021-06-24 15:39:18 -0700246status_t RpcSession::FdTrigger::interruptableWriteFully(RpcTransport* rpcTransport,
247 const void* data, size_t size) {
Steven Moreland798e0d12021-07-14 23:19:25 +0000248 const uint8_t* buffer = reinterpret_cast<const uint8_t*>(data);
249 const uint8_t* end = buffer + size;
250
251 MAYBE_WAIT_IN_FLAKE_MODE;
252
253 status_t status;
Yifan Hong702115c2021-06-24 15:39:18 -0700254 while ((status = triggerablePoll(rpcTransport, POLLOUT)) == OK) {
255 auto writeSize = rpcTransport->send(buffer, end - buffer);
256 if (!writeSize.ok()) {
257 LOG_RPC_DETAIL("RpcTransport::send(): %s", writeSize.error().message().c_str());
258 return writeSize.error().code() == 0 ? UNKNOWN_ERROR : -writeSize.error().code();
Steven Moreland798e0d12021-07-14 23:19:25 +0000259 }
Yifan Hong702115c2021-06-24 15:39:18 -0700260
261 if (*writeSize == 0) return DEAD_OBJECT;
262
263 buffer += *writeSize;
Steven Moreland798e0d12021-07-14 23:19:25 +0000264 if (buffer == end) return OK;
265 }
266 return status;
267}
268
Yifan Hong702115c2021-06-24 15:39:18 -0700269status_t RpcSession::FdTrigger::interruptableReadFully(RpcTransport* rpcTransport, void* data,
Steven Moreland2b4f3802021-05-22 01:46:27 +0000270 size_t size) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000271 uint8_t* buffer = reinterpret_cast<uint8_t*>(data);
272 uint8_t* end = buffer + size;
273
Steven Morelandb8176792021-06-22 20:29:21 +0000274 MAYBE_WAIT_IN_FLAKE_MODE;
275
Steven Moreland2b4f3802021-05-22 01:46:27 +0000276 status_t status;
Yifan Hong702115c2021-06-24 15:39:18 -0700277 while ((status = triggerablePoll(rpcTransport, POLLIN)) == OK) {
278 auto readSize = rpcTransport->recv(buffer, end - buffer);
279 if (!readSize.ok()) {
280 LOG_RPC_DETAIL("RpcTransport::recv(): %s", readSize.error().message().c_str());
281 return readSize.error().code() == 0 ? UNKNOWN_ERROR : -readSize.error().code();
Steven Moreland9d11b922021-05-20 01:22:58 +0000282 }
Yifan Hong702115c2021-06-24 15:39:18 -0700283
284 if (*readSize == 0) return DEAD_OBJECT; // EOF
285
286 buffer += *readSize;
Steven Moreland2b4f3802021-05-22 01:46:27 +0000287 if (buffer == end) return OK;
Steven Moreland9d11b922021-05-20 01:22:58 +0000288 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000289 return status;
Steven Moreland9d11b922021-05-20 01:22:58 +0000290}
291
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000292status_t RpcSession::readId() {
293 {
294 std::lock_guard<std::mutex> _l(mMutex);
295 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
296 }
297
Steven Moreland195edb82021-06-08 02:44:39 +0000298 ExclusiveConnection connection;
299 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
300 ConnectionUse::CLIENT, &connection);
301 if (status != OK) return status;
302
Steven Moreland01a6bad2021-06-11 00:59:20 +0000303 mId = RpcAddress::zero();
304 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this),
305 &mId.value());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000306 if (status != OK) return status;
307
Steven Moreland01a6bad2021-06-11 00:59:20 +0000308 LOG_RPC_DETAIL("RpcSession %p has id %s", this, mId->toString().c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000309 return OK;
310}
311
Steven Morelanddd67b942021-07-23 17:15:41 -0700312void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000313 const sp<RpcSession>& session) {
314 (void)session;
315 mShutdown = true;
316}
317
Steven Moreland19fc9f72021-06-10 03:57:30 +0000318void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000319 mCv.notify_all();
320}
321
322void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
323 while (!mShutdown) {
324 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
325 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
326 }
327 }
328}
329
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000330void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000331 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000332
Steven Morelanda63ff932021-05-12 00:03:15 +0000333 {
334 std::lock_guard<std::mutex> _l(mMutex);
335 mThreads[thread.get_id()] = std::move(thread);
336 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000337}
Steven Morelanda63ff932021-05-12 00:03:15 +0000338
Yifan Hong702115c2021-06-24 15:39:18 -0700339RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
340 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000341 // must be registered to allow arbitrary client code executing commands to
342 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700343 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000344
Steven Morelanddd67b942021-07-23 17:15:41 -0700345 status_t status;
346
347 if (connection == nullptr) {
348 status = DEAD_OBJECT;
349 } else {
350 status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
351 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000352
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000353 return PreJoinSetupResult{
354 .connection = std::move(connection),
355 .status = status,
356 };
357}
358
Yifan Hong194acf22021-06-29 18:44:56 -0700359namespace {
360// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
361// Android Runtime doesn't exist, no-op.
362class JavaThreadAttacher {
363public:
364 JavaThreadAttacher() {
365 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
366 // libbinder.
367 auto vm = getJavaVM();
368 if (vm == nullptr) return;
369
370 char threadName[16];
371 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
372 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
373 memcpy(threadName, defaultThreadName,
374 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
375 }
376 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
377 JavaVMAttachArgs args;
378 args.version = JNI_VERSION_1_2;
379 args.name = threadName;
380 args.group = nullptr;
381 JNIEnv* env;
382
383 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
384 "Cannot attach thread %s to JVM", threadName);
385 mAttached = true;
386 }
387 ~JavaThreadAttacher() {
388 if (!mAttached) return;
389 auto vm = getJavaVM();
390 LOG_ALWAYS_FATAL_IF(vm == nullptr,
391 "Unable to detach thread. No JavaVM, but it was present before!");
392
393 LOG_RPC_DETAIL("Detaching current thread from JVM");
394 if (vm->DetachCurrentThread() != JNI_OK) {
395 mAttached = false;
396 } else {
397 ALOGW("Unable to detach current thread from JVM");
398 }
399 }
400
401private:
402 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
403 bool mAttached = false;
404
405 static JavaVM* getJavaVM() {
406 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
407 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
408 if (fn == nullptr) return nullptr;
409 return fn();
410 }
411};
412} // namespace
413
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000414void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
415 sp<RpcConnection>& connection = setupResult.connection;
416
417 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700418 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hong194acf22021-06-29 18:44:56 -0700419 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000420 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000421 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000422 RpcState::CommandType::ANY);
423 if (status != OK) {
424 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
425 statusToString(status).c_str());
426 break;
427 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000428 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000429 } else {
430 ALOGE("Connection failed to init, closing with status %s",
431 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000432 }
433
Steven Moreland659416d2021-05-11 00:47:50 +0000434 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000435 {
Steven Moreland659416d2021-05-11 00:47:50 +0000436 std::lock_guard<std::mutex> _l(session->mMutex);
437 auto it = session->mThreads.find(std::this_thread::get_id());
438 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000439 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000440 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000441
Steven Moreland659416d2021-05-11 00:47:50 +0000442 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000443 }
444
Steven Morelanddd67b942021-07-23 17:15:41 -0700445 // done after all cleanup, since session shutdown progresses via callbacks here
446 if (connection != nullptr) {
447 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
448 "bad state: connection object guaranteed to be in list");
449 }
450
Steven Moreland659416d2021-05-11 00:47:50 +0000451 session = nullptr;
452
453 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000454 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000455 }
456}
457
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000458sp<RpcServer> RpcSession::server() {
459 RpcServer* unsafeServer = mForServer.unsafe_get();
460 sp<RpcServer> server = mForServer.promote();
461
462 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
463 "wp<> is to avoid strong cycle only");
464 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000465}
466
467bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
468 {
469 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000470 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000471 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000472 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000473 }
474
Steven Moreland1b304292021-07-15 22:59:34 +0000475 if (!setupOneSocketConnection(addr, RpcAddress::zero(), false /*incoming*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000476
Steven Morelandbf57bce2021-07-26 15:26:12 -0700477 {
478 ExclusiveConnection connection;
479 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
480 ConnectionUse::CLIENT, &connection);
481 if (status != OK) return false;
482
483 uint32_t version;
484 status = state()->readNewSessionResponse(connection.get(),
485 sp<RpcSession>::fromExisting(this), &version);
486 if (!setProtocolVersion(version)) return false;
487 }
488
Steven Morelanda5036f02021-06-08 02:26:57 +0000489 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000490 // instead of all at once.
491 // TODO(b/186470974): first risk of blocking
492 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000493 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000494 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
495 statusToString(status).c_str());
496 return false;
497 }
498
499 if (status_t status = readId(); status != OK) {
500 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
501 statusToString(status).c_str());
502 return false;
503 }
504
505 // we've already setup one client
506 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000507 // TODO(b/189955605): shutdown existing connections?
Steven Moreland1b304292021-07-15 22:59:34 +0000508 if (!setupOneSocketConnection(addr, mId.value(), false /*incoming*/)) return false;
Steven Moreland659416d2021-05-11 00:47:50 +0000509 }
510
Steven Morelanda5036f02021-06-08 02:26:57 +0000511 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000512 // instead of all at once - the other side should be responsible for setting
513 // up additional connections. We need to create at least one (unless 0 are
514 // requested to be set) in order to allow the other side to reliably make
515 // any requests at all.
516
Steven Moreland103424e2021-06-02 18:16:19 +0000517 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland1b304292021-07-15 22:59:34 +0000518 if (!setupOneSocketConnection(addr, mId.value(), true /*incoming*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000519 }
520
521 return true;
522}
523
Steven Moreland01a6bad2021-06-11 00:59:20 +0000524bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, const RpcAddress& id,
Steven Moreland1b304292021-07-15 22:59:34 +0000525 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000526 for (size_t tries = 0; tries < 5; tries++) {
527 if (tries > 0) usleep(10000);
528
529 unique_fd serverFd(
530 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
531 if (serverFd == -1) {
532 int savedErrno = errno;
533 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
534 strerror(savedErrno));
535 return false;
536 }
537
538 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
539 if (errno == ECONNRESET) {
540 ALOGW("Connection reset on %s", addr.toString().c_str());
541 continue;
542 }
543 int savedErrno = errno;
544 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
545 strerror(savedErrno));
546 return false;
547 }
Yifan Hong702115c2021-06-24 15:39:18 -0700548 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
549
550 auto ctx = mRpcTransportCtxFactory->newClientCtx();
551 if (ctx == nullptr) {
552 ALOGE("Unable to create client RpcTransportCtx with %s sockets",
553 mRpcTransportCtxFactory->toCString());
554 return false;
555 }
556 auto server = ctx->newTransport(std::move(serverFd));
557 if (server == nullptr) {
558 ALOGE("Unable to set up RpcTransport for %s", addr.toString().c_str());
559 return false;
560 }
561
562 LOG_RPC_DETAIL("Socket at %s client with RpcTransport %p", addr.toString().c_str(),
563 server.get());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000564
Steven Morelandbf57bce2021-07-26 15:26:12 -0700565 RpcConnectionHeader header{
566 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
567 .options = 0,
568 };
Steven Moreland01a6bad2021-06-11 00:59:20 +0000569 memcpy(&header.sessionId, &id.viewRawEmbedded(), sizeof(RpcWireAddress));
570
Steven Moreland1b304292021-07-15 22:59:34 +0000571 if (incoming) header.options |= RPC_CONNECTION_OPTION_INCOMING;
Steven Moreland659416d2021-05-11 00:47:50 +0000572
Yifan Hong702115c2021-06-24 15:39:18 -0700573 auto sentHeader = server->send(&header, sizeof(header));
574 if (!sentHeader.ok()) {
Steven Moreland659416d2021-05-11 00:47:50 +0000575 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Yifan Hong702115c2021-06-24 15:39:18 -0700576 sentHeader.error().message().c_str());
577 return false;
578 }
579 if (*sentHeader != sizeof(header)) {
580 ALOGE("Could not write connection header to socket at %s: sent %zd bytes, expected %zd",
581 addr.toString().c_str(), *sentHeader, sizeof(header));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000582 return false;
583 }
584
Yifan Hong702115c2021-06-24 15:39:18 -0700585 LOG_RPC_DETAIL("Socket at %s client: header sent", addr.toString().c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000586
Steven Moreland1b304292021-07-15 22:59:34 +0000587 if (incoming) {
Yifan Hong702115c2021-06-24 15:39:18 -0700588 return addIncomingConnection(std::move(server));
Steven Moreland659416d2021-05-11 00:47:50 +0000589 } else {
Yifan Hong702115c2021-06-24 15:39:18 -0700590 return addOutgoingConnection(std::move(server), true);
Steven Moreland659416d2021-05-11 00:47:50 +0000591 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000592 }
593
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000594 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
595 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000596}
597
Yifan Hong702115c2021-06-24 15:39:18 -0700598bool RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000599 std::mutex mutex;
600 std::condition_variable joinCv;
601 std::unique_lock<std::mutex> lock(mutex);
602 std::thread thread;
603 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
604 bool ownershipTransferred = false;
605 thread = std::thread([&]() {
606 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700607 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000608 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
609 sp<RpcSession> session = thiz;
610 session->preJoinThreadOwnership(std::move(thread));
611
612 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700613 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000614
615 ownershipTransferred = true;
616 threadLock.unlock();
617 joinCv.notify_one();
618 // do not use & vars below
619
620 RpcSession::join(std::move(session), std::move(setupResult));
621 });
622 joinCv.wait(lock, [&] { return ownershipTransferred; });
623 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
624 return true;
625}
626
Yifan Hong702115c2021-06-24 15:39:18 -0700627bool RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000628 sp<RpcConnection> connection = sp<RpcConnection>::make();
629 {
630 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000631
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000632 // first client connection added, but setForServer not called, so
633 // initializaing for a client.
634 if (mShutdownTrigger == nullptr) {
635 mShutdownTrigger = FdTrigger::make();
636 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
637 if (mShutdownTrigger == nullptr) return false;
638 }
639
Yifan Hong702115c2021-06-24 15:39:18 -0700640 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000641 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000642 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000643 }
644
Steven Morelandb86e26b2021-06-12 00:35:58 +0000645 status_t status = OK;
646 if (init) {
647 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
648 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000649
650 {
651 std::lock_guard<std::mutex> _l(mMutex);
652 connection->exclusiveTid = std::nullopt;
653 }
654
655 return status == OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000656}
657
Steven Morelanda8b44292021-06-08 01:27:53 +0000658bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000659 const RpcAddress& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000660 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
661 LOG_ALWAYS_FATAL_IF(server == nullptr);
662 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
663 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000664 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000665
666 mShutdownTrigger = FdTrigger::make();
667 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000668
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000669 mId = sessionId;
670 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000671 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000672 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000673}
674
Yifan Hong702115c2021-06-24 15:39:18 -0700675sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
676 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000677 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700678
679 // Don't accept any more connections, some have shutdown. Usually this
680 // happens when new connections are still being established as part of a
681 // very short-lived session which shuts down after it already started
682 // accepting new connections.
683 if (mIncomingConnections.size() < mMaxIncomingConnections) {
684 return nullptr;
685 }
686
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000687 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700688 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000689 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700690
Steven Moreland19fc9f72021-06-10 03:57:30 +0000691 mIncomingConnections.push_back(session);
Steven Morelanddd67b942021-07-23 17:15:41 -0700692 mMaxIncomingConnections = mIncomingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000693
694 return session;
695}
696
Steven Moreland19fc9f72021-06-10 03:57:30 +0000697bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700698 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000699 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
700 it != mIncomingConnections.end()) {
701 mIncomingConnections.erase(it);
702 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000703 sp<EventListener> listener = mEventListener.promote();
704 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700705 _l.unlock();
706 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000707 }
Steven Morelandee78e762021-05-05 21:12:51 +0000708 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000709 return true;
710 }
711 return false;
712}
713
Steven Moreland195edb82021-06-08 02:44:39 +0000714status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
715 ExclusiveConnection* connection) {
716 connection->mSession = session;
717 connection->mConnection = nullptr;
718 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000719
Steven Moreland195edb82021-06-08 02:44:39 +0000720 pid_t tid = gettid();
721 std::unique_lock<std::mutex> _l(session->mMutex);
722
723 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000724 while (true) {
725 sp<RpcConnection> exclusive;
726 sp<RpcConnection> available;
727
728 // CHECK FOR DEDICATED CLIENT SOCKET
729 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000730 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000731 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
732 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000733
734 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000735 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000736 //
737 // Imagine we have more than one thread in play, and a single thread
738 // sends a synchronous, then an asynchronous command. Imagine the
739 // asynchronous command is sent on the first client connection. Then, if
740 // we naively send a synchronous command to that same connection, the
741 // thread on the far side might be busy processing the asynchronous
742 // command. So, we move to considering the second available thread
743 // for subsequent calls.
744 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000745 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
746 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000747 }
748
Steven Morelandc7d40132021-06-10 03:42:11 +0000749 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000750 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000751 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000752 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000753 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
754 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000755
756 // asynchronous calls cannot be nested, we currently allow ref count
757 // calls to be nested (so that you can use this without having extra
758 // threads). Note 'drainCommands' is used so that these ref counts can't
759 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000760 if (exclusiveIncoming != nullptr) {
761 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000762 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000763 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000764 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
765 // prefer available socket, but if we don't have one, don't
766 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000767 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000768 }
769 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000770 }
771
Steven Moreland85e067b2021-05-26 17:43:53 +0000772 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000773 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000774 connection->mConnection = exclusive;
775 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000776 break;
777 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000778 connection->mConnection = available;
779 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000780 break;
781 }
782
Steven Moreland19fc9f72021-06-10 03:57:30 +0000783 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000784 ALOGE("Session has no client connections. This is required for an RPC server to make "
785 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
786 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000787 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000788 return WOULD_BLOCK;
789 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000790
Steven Moreland85e067b2021-05-26 17:43:53 +0000791 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000792 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000793 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000794 }
Steven Moreland195edb82021-06-08 02:44:39 +0000795 session->mWaitingThreads--;
796
797 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000798}
799
800void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
801 sp<RpcConnection>* available,
802 std::vector<sp<RpcConnection>>& sockets,
803 size_t socketsIndexHint) {
804 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
805 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
806
807 if (*exclusive != nullptr) return; // consistent with break below
808
809 for (size_t i = 0; i < sockets.size(); i++) {
810 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
811
Steven Moreland85e067b2021-05-26 17:43:53 +0000812 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000813 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
814 *available = socket;
815 continue;
816 }
817
Steven Moreland85e067b2021-05-26 17:43:53 +0000818 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000819 // (nested transactions)
820 if (exclusive && socket->exclusiveTid == tid) {
821 *exclusive = socket;
822 break; // consistent with return above
823 }
824 }
825}
826
827RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000828 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000829 // is using this fd, and it retains the right to it. So, we don't give up
830 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000831 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000832 std::unique_lock<std::mutex> _l(mSession->mMutex);
833 mConnection->exclusiveTid = std::nullopt;
834 if (mSession->mWaitingThreads > 0) {
835 _l.unlock();
836 mSession->mAvailableConnectionCv.notify_one();
837 }
838 }
839}
840
841} // namespace android