blob: c756f2e8fbbd5aeda3960587361c27f300ba21ff [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"
42
43#ifdef __GLIBC__
44extern "C" pid_t gettid();
45#endif
46
47namespace android {
48
49using base::unique_fd;
50
Yifan Hong702115c2021-06-24 15:39:18 -070051RpcSession::RpcSession(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory)
52 : mRpcTransportCtxFactory(std::move(rpcTransportCtxFactory)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000053 LOG_RPC_DETAIL("RpcSession created %p", this);
54
55 mState = std::make_unique<RpcState>();
56}
57RpcSession::~RpcSession() {
58 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
59
60 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000061 LOG_ALWAYS_FATAL_IF(mIncomingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000062 "Should not be able to destroy a session with servers in use.");
63}
64
Yifan Hong702115c2021-06-24 15:39:18 -070065sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
66 // Default is without TLS.
67 if (rpcTransportCtxFactory == nullptr)
68 rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
69 return sp<RpcSession>::make(std::move(rpcTransportCtxFactory));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000070}
71
Steven Moreland103424e2021-06-02 18:16:19 +000072void RpcSession::setMaxThreads(size_t threads) {
73 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000074 LOG_ALWAYS_FATAL_IF(!mOutgoingConnections.empty() || !mIncomingConnections.empty(),
Steven Moreland103424e2021-06-02 18:16:19 +000075 "Must set max threads before setting up connections, but has %zu client(s) "
76 "and %zu server(s)",
Steven Moreland19fc9f72021-06-10 03:57:30 +000077 mOutgoingConnections.size(), mIncomingConnections.size());
Steven Moreland103424e2021-06-02 18:16:19 +000078 mMaxThreads = threads;
79}
80
81size_t RpcSession::getMaxThreads() {
82 std::lock_guard<std::mutex> _l(mMutex);
83 return mMaxThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000084}
85
Steven Morelandbf57bce2021-07-26 15:26:12 -070086bool RpcSession::setProtocolVersion(uint32_t version) {
87 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
88 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
89 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
90 "is %u).",
91 version, RPC_WIRE_PROTOCOL_VERSION);
92 return false;
93 }
94
95 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -070096 if (mProtocolVersion && version > *mProtocolVersion) {
97 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
98 *mProtocolVersion, version);
99 return false;
100 }
101
Steven Morelandbf57bce2021-07-26 15:26:12 -0700102 mProtocolVersion = version;
103 return true;
104}
105
106std::optional<uint32_t> RpcSession::getProtocolVersion() {
107 std::lock_guard<std::mutex> _l(mMutex);
108 return mProtocolVersion;
109}
110
Steven Moreland2372f9d2021-08-05 15:42:01 -0700111status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000112 return setupSocketClient(UnixSocketAddress(path));
113}
114
Steven Moreland2372f9d2021-08-05 15:42:01 -0700115status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000116 return setupSocketClient(VsockSocketAddress(cid, port));
117}
118
Steven Moreland2372f9d2021-08-05 15:42:01 -0700119status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000120 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700121 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000122 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
123 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700124 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000125 }
126 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 -0700127 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000128}
129
Steven Moreland2372f9d2021-08-05 15:42:01 -0700130status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
131 return setupClient([&](const RpcAddress& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700132 // std::move'd from fd becomes -1 (!ok())
133 if (!fd.ok()) {
134 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700135 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700136 }
137 return initAndAddConnection(std::move(fd), sessionId, incoming);
138 });
139}
140
Steven Moreland2372f9d2021-08-05 15:42:01 -0700141status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700142 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700143 if (auto status = initShutdownTrigger(); status != OK) return status;
144
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000145 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
146
147 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700148 int savedErrno = errno;
149 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
150 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000151 }
152
Yifan Hong702115c2021-06-24 15:39:18 -0700153 auto ctx = mRpcTransportCtxFactory->newClientCtx();
154 if (ctx == nullptr) {
155 ALOGE("Unable to create RpcTransportCtx for null debugging client");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700156 return NO_MEMORY;
Yifan Hong702115c2021-06-24 15:39:18 -0700157 }
158 auto server = ctx->newTransport(std::move(serverFd));
159 if (server == nullptr) {
160 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700161 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700162 }
163 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000164}
165
166sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000167 ExclusiveConnection connection;
168 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
169 ConnectionUse::CLIENT, &connection);
170 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000171 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000172}
173
Steven Moreland1be91352021-05-11 22:12:15 +0000174status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000175 ExclusiveConnection connection;
176 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
177 ConnectionUse::CLIENT, &connection);
178 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000179 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000180}
181
Steven Morelandc9d7b532021-06-04 20:57:41 +0000182bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000183 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000184 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000185
186 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000187
Steven Morelandc9d7b532021-06-04 20:57:41 +0000188 if (wait) {
189 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
190 mShutdownListener->waitForShutdown(_l);
Steven Morelanddd67b942021-07-23 17:15:41 -0700191
Steven Morelandc9d7b532021-06-04 20:57:41 +0000192 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
193 }
194
195 _l.unlock();
196 mState->clear();
197
Steven Moreland659416d2021-05-11 00:47:50 +0000198 return true;
199}
200
Steven Morelandf5174272021-05-25 00:39:28 +0000201status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000202 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000203 ExclusiveConnection connection;
204 status_t status =
205 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
206 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
207 : ConnectionUse::CLIENT,
208 &connection);
209 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000210 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000211 sp<RpcSession>::fromExisting(this), reply, flags);
212}
213
214status_t RpcSession::sendDecStrong(const RpcAddress& address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000215 ExclusiveConnection connection;
216 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
217 ConnectionUse::CLIENT_REFCOUNT, &connection);
218 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000219 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000220}
221
222status_t RpcSession::readId() {
223 {
224 std::lock_guard<std::mutex> _l(mMutex);
225 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
226 }
227
Steven Moreland195edb82021-06-08 02:44:39 +0000228 ExclusiveConnection connection;
229 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
230 ConnectionUse::CLIENT, &connection);
231 if (status != OK) return status;
232
Steven Moreland01a6bad2021-06-11 00:59:20 +0000233 mId = RpcAddress::zero();
234 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this),
235 &mId.value());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000236 if (status != OK) return status;
237
Steven Moreland01a6bad2021-06-11 00:59:20 +0000238 LOG_RPC_DETAIL("RpcSession %p has id %s", this, mId->toString().c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000239 return OK;
240}
241
Steven Morelanddd67b942021-07-23 17:15:41 -0700242void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000243 const sp<RpcSession>& session) {
244 (void)session;
245 mShutdown = true;
246}
247
Steven Moreland19fc9f72021-06-10 03:57:30 +0000248void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000249 mCv.notify_all();
250}
251
252void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
253 while (!mShutdown) {
254 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
255 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
256 }
257 }
258}
259
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000260void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000261 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000262
Steven Morelanda63ff932021-05-12 00:03:15 +0000263 {
264 std::lock_guard<std::mutex> _l(mMutex);
265 mThreads[thread.get_id()] = std::move(thread);
266 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000267}
Steven Morelanda63ff932021-05-12 00:03:15 +0000268
Yifan Hong702115c2021-06-24 15:39:18 -0700269RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
270 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000271 // must be registered to allow arbitrary client code executing commands to
272 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700273 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000274
Steven Morelanddd67b942021-07-23 17:15:41 -0700275 status_t status;
276
277 if (connection == nullptr) {
278 status = DEAD_OBJECT;
279 } else {
280 status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
281 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000282
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000283 return PreJoinSetupResult{
284 .connection = std::move(connection),
285 .status = status,
286 };
287}
288
Yifan Hong194acf22021-06-29 18:44:56 -0700289namespace {
290// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
291// Android Runtime doesn't exist, no-op.
292class JavaThreadAttacher {
293public:
294 JavaThreadAttacher() {
295 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
296 // libbinder.
297 auto vm = getJavaVM();
298 if (vm == nullptr) return;
299
300 char threadName[16];
301 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
302 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
303 memcpy(threadName, defaultThreadName,
304 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
305 }
306 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
307 JavaVMAttachArgs args;
308 args.version = JNI_VERSION_1_2;
309 args.name = threadName;
310 args.group = nullptr;
311 JNIEnv* env;
312
313 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
314 "Cannot attach thread %s to JVM", threadName);
315 mAttached = true;
316 }
317 ~JavaThreadAttacher() {
318 if (!mAttached) return;
319 auto vm = getJavaVM();
320 LOG_ALWAYS_FATAL_IF(vm == nullptr,
321 "Unable to detach thread. No JavaVM, but it was present before!");
322
323 LOG_RPC_DETAIL("Detaching current thread from JVM");
324 if (vm->DetachCurrentThread() != JNI_OK) {
325 mAttached = false;
326 } else {
327 ALOGW("Unable to detach current thread from JVM");
328 }
329 }
330
331private:
332 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
333 bool mAttached = false;
334
335 static JavaVM* getJavaVM() {
336 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
337 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
338 if (fn == nullptr) return nullptr;
339 return fn();
340 }
341};
342} // namespace
343
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000344void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
345 sp<RpcConnection>& connection = setupResult.connection;
346
347 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700348 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hong194acf22021-06-29 18:44:56 -0700349 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000350 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000351 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000352 RpcState::CommandType::ANY);
353 if (status != OK) {
354 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
355 statusToString(status).c_str());
356 break;
357 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000358 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000359 } else {
360 ALOGE("Connection failed to init, closing with status %s",
361 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000362 }
363
Steven Moreland659416d2021-05-11 00:47:50 +0000364 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000365 {
Steven Moreland659416d2021-05-11 00:47:50 +0000366 std::lock_guard<std::mutex> _l(session->mMutex);
367 auto it = session->mThreads.find(std::this_thread::get_id());
368 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000369 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000370 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000371
Steven Moreland659416d2021-05-11 00:47:50 +0000372 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000373 }
374
Steven Morelanddd67b942021-07-23 17:15:41 -0700375 // done after all cleanup, since session shutdown progresses via callbacks here
376 if (connection != nullptr) {
377 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
378 "bad state: connection object guaranteed to be in list");
379 }
380
Steven Moreland659416d2021-05-11 00:47:50 +0000381 session = nullptr;
382
383 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000384 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000385 }
386}
387
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000388sp<RpcServer> RpcSession::server() {
389 RpcServer* unsafeServer = mForServer.unsafe_get();
390 sp<RpcServer> server = mForServer.promote();
391
392 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
393 "wp<> is to avoid strong cycle only");
394 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000395}
396
Steven Moreland2372f9d2021-08-05 15:42:01 -0700397status_t RpcSession::setupClient(
398 const std::function<status_t(const RpcAddress& sessionId, bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000399 {
400 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000401 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000402 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000403 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000404 }
Yifan Hong832521e2021-08-05 14:55:40 -0700405 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000406
Steven Moreland2372f9d2021-08-05 15:42:01 -0700407 if (status_t status = connectAndInit(RpcAddress::zero(), false /*incoming*/); status != OK)
408 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409
Steven Morelandbf57bce2021-07-26 15:26:12 -0700410 {
411 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700412 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
413 ConnectionUse::CLIENT, &connection);
414 status != OK)
415 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700416
417 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700418 if (status_t status =
419 state()->readNewSessionResponse(connection.get(),
420 sp<RpcSession>::fromExisting(this), &version);
421 status != OK)
422 return status;
423 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700424 }
425
Steven Morelanda5036f02021-06-08 02:26:57 +0000426 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000427 // instead of all at once.
428 // TODO(b/186470974): first risk of blocking
429 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000430 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700431 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000432 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700433 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000434 }
435
436 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700437 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000438 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700439 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000440 }
441
Steven Morelanda5036f02021-06-08 02:26:57 +0000442 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000443 // instead of all at once - the other side should be responsible for setting
444 // up additional connections. We need to create at least one (unless 0 are
445 // requested to be set) in order to allow the other side to reliably make
446 // any requests at all.
447
Steven Moreland4198a122021-08-03 17:37:58 -0700448 // we've already setup one client
449 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700450 if (status_t status = connectAndInit(mId.value(), false /*incoming*/); status != OK)
451 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700452 }
453
Steven Moreland103424e2021-06-02 18:16:19 +0000454 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700455 if (status_t status = connectAndInit(mId.value(), true /*incoming*/); status != OK)
456 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000457 }
458
Steven Moreland2372f9d2021-08-05 15:42:01 -0700459 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000460}
461
Steven Moreland2372f9d2021-08-05 15:42:01 -0700462status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700463 return setupClient([&](const RpcAddress& sessionId, bool incoming) {
464 return setupOneSocketConnection(addr, sessionId, incoming);
465 });
466}
467
Steven Moreland2372f9d2021-08-05 15:42:01 -0700468status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
469 const RpcAddress& sessionId, bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000470 for (size_t tries = 0; tries < 5; tries++) {
471 if (tries > 0) usleep(10000);
472
473 unique_fd serverFd(
474 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
475 if (serverFd == -1) {
476 int savedErrno = errno;
477 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
478 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700479 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000480 }
481
482 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
483 if (errno == ECONNRESET) {
484 ALOGW("Connection reset on %s", addr.toString().c_str());
485 continue;
486 }
487 int savedErrno = errno;
488 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
489 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700490 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000491 }
Yifan Hong702115c2021-06-24 15:39:18 -0700492 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
493
Steven Moreland4198a122021-08-03 17:37:58 -0700494 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000495 }
496
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000497 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700498 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000499}
500
Steven Moreland2372f9d2021-08-05 15:42:01 -0700501status_t RpcSession::initAndAddConnection(unique_fd fd, const RpcAddress& sessionId,
502 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700503 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Steven Moreland4198a122021-08-03 17:37:58 -0700504 auto ctx = mRpcTransportCtxFactory->newClientCtx();
505 if (ctx == nullptr) {
506 ALOGE("Unable to create client RpcTransportCtx with %s sockets",
507 mRpcTransportCtxFactory->toCString());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700508 return NO_MEMORY;
Steven Moreland4198a122021-08-03 17:37:58 -0700509 }
510 auto server = ctx->newTransport(std::move(fd));
511 if (server == nullptr) {
512 ALOGE("Unable to set up RpcTransport in %s context", mRpcTransportCtxFactory->toCString());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700513 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700514 }
515
516 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
517
518 RpcConnectionHeader header{
519 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
520 .options = 0,
521 };
522 memcpy(&header.sessionId, &sessionId.viewRawEmbedded(), sizeof(RpcWireAddress));
523
524 if (incoming) header.options |= RPC_CONNECTION_OPTION_INCOMING;
525
Yifan Hong8c950422021-08-05 17:13:55 -0700526 auto sendHeaderStatus =
527 server->interruptableWriteFully(mShutdownTrigger.get(), &header, sizeof(header));
528 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700529 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700530 statusToString(sendHeaderStatus).c_str());
531 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700532 }
533
534 LOG_RPC_DETAIL("Socket at client: header sent");
535
536 if (incoming) {
537 return addIncomingConnection(std::move(server));
538 } else {
539 return addOutgoingConnection(std::move(server), true /*init*/);
540 }
541}
542
Steven Moreland2372f9d2021-08-05 15:42:01 -0700543status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000544 std::mutex mutex;
545 std::condition_variable joinCv;
546 std::unique_lock<std::mutex> lock(mutex);
547 std::thread thread;
548 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
549 bool ownershipTransferred = false;
550 thread = std::thread([&]() {
551 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700552 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000553 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
554 sp<RpcSession> session = thiz;
555 session->preJoinThreadOwnership(std::move(thread));
556
557 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700558 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000559
560 ownershipTransferred = true;
561 threadLock.unlock();
562 joinCv.notify_one();
563 // do not use & vars below
564
565 RpcSession::join(std::move(session), std::move(setupResult));
566 });
567 joinCv.wait(lock, [&] { return ownershipTransferred; });
568 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700569 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000570}
571
Yifan Hong832521e2021-08-05 14:55:40 -0700572status_t RpcSession::initShutdownTrigger() {
573 // first client connection added, but setForServer not called, so
574 // initializaing for a client.
575 if (mShutdownTrigger == nullptr) {
576 mShutdownTrigger = FdTrigger::make();
577 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
578 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
579 }
580 return OK;
581}
582
Steven Moreland2372f9d2021-08-05 15:42:01 -0700583status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000584 sp<RpcConnection> connection = sp<RpcConnection>::make();
585 {
586 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700587 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000588 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000589 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000590 }
591
Steven Morelandb86e26b2021-06-12 00:35:58 +0000592 status_t status = OK;
593 if (init) {
594 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
595 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000596
597 {
598 std::lock_guard<std::mutex> _l(mMutex);
599 connection->exclusiveTid = std::nullopt;
600 }
601
Steven Moreland2372f9d2021-08-05 15:42:01 -0700602 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000603}
604
Steven Morelanda8b44292021-06-08 01:27:53 +0000605bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000606 const RpcAddress& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000607 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
608 LOG_ALWAYS_FATAL_IF(server == nullptr);
609 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
610 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000611 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000612
613 mShutdownTrigger = FdTrigger::make();
614 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000615
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000616 mId = sessionId;
617 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000618 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000619 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000620}
621
Yifan Hong702115c2021-06-24 15:39:18 -0700622sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
623 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000624 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700625
Steven Moreland132d5bf2021-08-03 16:13:24 -0700626 if (mIncomingConnections.size() >= mMaxThreads) {
627 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
628 mIncomingConnections.size(), mMaxThreads);
629 return nullptr;
630 }
631
Steven Morelanddd67b942021-07-23 17:15:41 -0700632 // Don't accept any more connections, some have shutdown. Usually this
633 // happens when new connections are still being established as part of a
634 // very short-lived session which shuts down after it already started
635 // accepting new connections.
636 if (mIncomingConnections.size() < mMaxIncomingConnections) {
637 return nullptr;
638 }
639
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000640 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700641 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000642 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700643
Steven Moreland19fc9f72021-06-10 03:57:30 +0000644 mIncomingConnections.push_back(session);
Steven Morelanddd67b942021-07-23 17:15:41 -0700645 mMaxIncomingConnections = mIncomingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000646
647 return session;
648}
649
Steven Moreland19fc9f72021-06-10 03:57:30 +0000650bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700651 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000652 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
653 it != mIncomingConnections.end()) {
654 mIncomingConnections.erase(it);
655 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000656 sp<EventListener> listener = mEventListener.promote();
657 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700658 _l.unlock();
659 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000660 }
Steven Morelandee78e762021-05-05 21:12:51 +0000661 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000662 return true;
663 }
664 return false;
665}
666
Steven Moreland195edb82021-06-08 02:44:39 +0000667status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
668 ExclusiveConnection* connection) {
669 connection->mSession = session;
670 connection->mConnection = nullptr;
671 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000672
Steven Moreland195edb82021-06-08 02:44:39 +0000673 pid_t tid = gettid();
674 std::unique_lock<std::mutex> _l(session->mMutex);
675
676 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000677 while (true) {
678 sp<RpcConnection> exclusive;
679 sp<RpcConnection> available;
680
681 // CHECK FOR DEDICATED CLIENT SOCKET
682 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000683 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000684 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
685 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000686
687 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000688 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000689 //
690 // Imagine we have more than one thread in play, and a single thread
691 // sends a synchronous, then an asynchronous command. Imagine the
692 // asynchronous command is sent on the first client connection. Then, if
693 // we naively send a synchronous command to that same connection, the
694 // thread on the far side might be busy processing the asynchronous
695 // command. So, we move to considering the second available thread
696 // for subsequent calls.
697 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000698 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
699 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000700 }
701
Steven Morelandc7d40132021-06-10 03:42:11 +0000702 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000703 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000704 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000705 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000706 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
707 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000708
709 // asynchronous calls cannot be nested, we currently allow ref count
710 // calls to be nested (so that you can use this without having extra
711 // threads). Note 'drainCommands' is used so that these ref counts can't
712 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000713 if (exclusiveIncoming != nullptr) {
714 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000715 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000716 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000717 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
718 // prefer available socket, but if we don't have one, don't
719 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000720 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000721 }
722 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000723 }
724
Steven Moreland85e067b2021-05-26 17:43:53 +0000725 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000726 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000727 connection->mConnection = exclusive;
728 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000729 break;
730 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000731 connection->mConnection = available;
732 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000733 break;
734 }
735
Steven Moreland19fc9f72021-06-10 03:57:30 +0000736 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000737 ALOGE("Session has no client connections. This is required for an RPC server to make "
738 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
739 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000740 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000741 return WOULD_BLOCK;
742 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000743
Steven Moreland85e067b2021-05-26 17:43:53 +0000744 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000745 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000746 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000747 }
Steven Moreland195edb82021-06-08 02:44:39 +0000748 session->mWaitingThreads--;
749
750 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000751}
752
753void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
754 sp<RpcConnection>* available,
755 std::vector<sp<RpcConnection>>& sockets,
756 size_t socketsIndexHint) {
757 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
758 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
759
760 if (*exclusive != nullptr) return; // consistent with break below
761
762 for (size_t i = 0; i < sockets.size(); i++) {
763 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
764
Steven Moreland85e067b2021-05-26 17:43:53 +0000765 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000766 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
767 *available = socket;
768 continue;
769 }
770
Steven Moreland85e067b2021-05-26 17:43:53 +0000771 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000772 // (nested transactions)
773 if (exclusive && socket->exclusiveTid == tid) {
774 *exclusive = socket;
775 break; // consistent with return above
776 }
777 }
778}
779
780RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000781 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000782 // is using this fd, and it retains the right to it. So, we don't give up
783 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000784 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000785 std::unique_lock<std::mutex> _l(mSession->mMutex);
786 mConnection->exclusiveTid = std::nullopt;
787 if (mSession->mWaitingThreads > 0) {
788 _l.unlock();
789 mSession->mAvailableConnectionCv.notify_one();
790 }
791 }
792}
793
794} // namespace android