blob: 3e9e5a8441cf0bc568e6b1dbbc7584879e08816b [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 }
Yifan Hongf6d42292021-08-05 23:43:05 -0700163 auto server = ctx->newTransport(std::move(serverFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700164 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.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000433 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000434 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700435 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000436 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700437 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000438 }
439
440 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700441 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000442 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700443 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000444 }
445
Steven Morelanda5036f02021-06-08 02:26:57 +0000446 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000447 // instead of all at once - the other side should be responsible for setting
448 // up additional connections. We need to create at least one (unless 0 are
449 // requested to be set) in order to allow the other side to reliably make
450 // any requests at all.
451
Steven Moreland4198a122021-08-03 17:37:58 -0700452 // we've already setup one client
453 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700454 if (status_t status = connectAndInit(mId.value(), false /*incoming*/); status != OK)
455 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700456 }
457
Steven Moreland103424e2021-06-02 18:16:19 +0000458 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700459 if (status_t status = connectAndInit(mId.value(), true /*incoming*/); status != OK)
460 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000461 }
462
Steven Moreland2372f9d2021-08-05 15:42:01 -0700463 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000464}
465
Steven Moreland2372f9d2021-08-05 15:42:01 -0700466status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700467 return setupClient([&](const RpcAddress& sessionId, bool incoming) {
468 return setupOneSocketConnection(addr, sessionId, incoming);
469 });
470}
471
Steven Moreland2372f9d2021-08-05 15:42:01 -0700472status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
473 const RpcAddress& sessionId, bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000474 for (size_t tries = 0; tries < 5; tries++) {
475 if (tries > 0) usleep(10000);
476
Yifan Hongb675ffe2021-08-05 16:37:17 -0700477 unique_fd serverFd(TEMP_FAILURE_RETRY(
478 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000479 if (serverFd == -1) {
480 int savedErrno = errno;
481 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
482 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700483 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000484 }
485
486 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700487 int connErrno = errno;
488 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
489 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
490 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
491 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
492 if (pollStatus != OK) {
493 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
494 statusToString(pollStatus).c_str());
495 return pollStatus;
496 }
497 // Set connErrno to the errno that connect() would have set if the fd were blocking.
498 socklen_t connErrnoLen = sizeof(connErrno);
499 int ret =
500 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
501 if (ret == -1) {
502 int savedErrno = errno;
503 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
504 "(Original error from connect() is: %s)",
505 strerror(savedErrno), strerror(connErrno));
506 return -savedErrno;
507 }
508 // Retrieved the real connErrno as if connect() was called with a blocking socket
509 // fd. Continue checking connErrno.
510 }
511 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000512 ALOGW("Connection reset on %s", addr.toString().c_str());
513 continue;
514 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700515 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
516 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700517 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700518 strerror(connErrno));
519 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700520 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000521 }
Yifan Hong702115c2021-06-24 15:39:18 -0700522 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
523
Steven Moreland4198a122021-08-03 17:37:58 -0700524 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000525 }
526
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000527 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700528 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000529}
530
Steven Moreland2372f9d2021-08-05 15:42:01 -0700531status_t RpcSession::initAndAddConnection(unique_fd fd, const RpcAddress& sessionId,
532 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700533 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Steven Moreland4198a122021-08-03 17:37:58 -0700534 auto ctx = mRpcTransportCtxFactory->newClientCtx();
535 if (ctx == nullptr) {
536 ALOGE("Unable to create client RpcTransportCtx with %s sockets",
537 mRpcTransportCtxFactory->toCString());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700538 return NO_MEMORY;
Steven Moreland4198a122021-08-03 17:37:58 -0700539 }
Yifan Hongf6d42292021-08-05 23:43:05 -0700540 auto server = ctx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700541 if (server == nullptr) {
542 ALOGE("Unable to set up RpcTransport in %s context", mRpcTransportCtxFactory->toCString());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700543 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700544 }
545
546 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
547
548 RpcConnectionHeader header{
549 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
550 .options = 0,
551 };
552 memcpy(&header.sessionId, &sessionId.viewRawEmbedded(), sizeof(RpcWireAddress));
553
554 if (incoming) header.options |= RPC_CONNECTION_OPTION_INCOMING;
555
Yifan Hong8c950422021-08-05 17:13:55 -0700556 auto sendHeaderStatus =
557 server->interruptableWriteFully(mShutdownTrigger.get(), &header, sizeof(header));
558 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700559 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700560 statusToString(sendHeaderStatus).c_str());
561 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700562 }
563
564 LOG_RPC_DETAIL("Socket at client: header sent");
565
566 if (incoming) {
567 return addIncomingConnection(std::move(server));
568 } else {
569 return addOutgoingConnection(std::move(server), true /*init*/);
570 }
571}
572
Steven Moreland2372f9d2021-08-05 15:42:01 -0700573status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000574 std::mutex mutex;
575 std::condition_variable joinCv;
576 std::unique_lock<std::mutex> lock(mutex);
577 std::thread thread;
578 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
579 bool ownershipTransferred = false;
580 thread = std::thread([&]() {
581 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700582 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000583 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
584 sp<RpcSession> session = thiz;
585 session->preJoinThreadOwnership(std::move(thread));
586
587 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700588 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000589
590 ownershipTransferred = true;
591 threadLock.unlock();
592 joinCv.notify_one();
593 // do not use & vars below
594
595 RpcSession::join(std::move(session), std::move(setupResult));
596 });
597 joinCv.wait(lock, [&] { return ownershipTransferred; });
598 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700599 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000600}
601
Yifan Hong832521e2021-08-05 14:55:40 -0700602status_t RpcSession::initShutdownTrigger() {
603 // first client connection added, but setForServer not called, so
604 // initializaing for a client.
605 if (mShutdownTrigger == nullptr) {
606 mShutdownTrigger = FdTrigger::make();
607 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
608 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
609 }
610 return OK;
611}
612
Steven Moreland2372f9d2021-08-05 15:42:01 -0700613status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000614 sp<RpcConnection> connection = sp<RpcConnection>::make();
615 {
616 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700617 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000618 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000619 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000620 }
621
Steven Morelandb86e26b2021-06-12 00:35:58 +0000622 status_t status = OK;
623 if (init) {
624 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
625 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000626
627 {
628 std::lock_guard<std::mutex> _l(mMutex);
629 connection->exclusiveTid = std::nullopt;
630 }
631
Steven Moreland2372f9d2021-08-05 15:42:01 -0700632 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000633}
634
Steven Morelanda8b44292021-06-08 01:27:53 +0000635bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000636 const RpcAddress& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000637 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
638 LOG_ALWAYS_FATAL_IF(server == nullptr);
639 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
640 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000641 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000642
643 mShutdownTrigger = FdTrigger::make();
644 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000645
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000646 mId = sessionId;
647 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000648 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000649 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000650}
651
Yifan Hong702115c2021-06-24 15:39:18 -0700652sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
653 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000654 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700655
Steven Moreland132d5bf2021-08-03 16:13:24 -0700656 if (mIncomingConnections.size() >= mMaxThreads) {
657 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
658 mIncomingConnections.size(), mMaxThreads);
659 return nullptr;
660 }
661
Steven Morelanddd67b942021-07-23 17:15:41 -0700662 // Don't accept any more connections, some have shutdown. Usually this
663 // happens when new connections are still being established as part of a
664 // very short-lived session which shuts down after it already started
665 // accepting new connections.
666 if (mIncomingConnections.size() < mMaxIncomingConnections) {
667 return nullptr;
668 }
669
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000670 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700671 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000672 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700673
Steven Moreland19fc9f72021-06-10 03:57:30 +0000674 mIncomingConnections.push_back(session);
Steven Morelanddd67b942021-07-23 17:15:41 -0700675 mMaxIncomingConnections = mIncomingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000676
677 return session;
678}
679
Steven Moreland19fc9f72021-06-10 03:57:30 +0000680bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700681 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000682 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
683 it != mIncomingConnections.end()) {
684 mIncomingConnections.erase(it);
685 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000686 sp<EventListener> listener = mEventListener.promote();
687 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700688 _l.unlock();
689 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000690 }
Steven Morelandee78e762021-05-05 21:12:51 +0000691 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000692 return true;
693 }
694 return false;
695}
696
Steven Moreland195edb82021-06-08 02:44:39 +0000697status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
698 ExclusiveConnection* connection) {
699 connection->mSession = session;
700 connection->mConnection = nullptr;
701 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000702
Steven Moreland195edb82021-06-08 02:44:39 +0000703 pid_t tid = gettid();
704 std::unique_lock<std::mutex> _l(session->mMutex);
705
706 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000707 while (true) {
708 sp<RpcConnection> exclusive;
709 sp<RpcConnection> available;
710
711 // CHECK FOR DEDICATED CLIENT SOCKET
712 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000713 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000714 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
715 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000716
717 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000718 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000719 //
720 // Imagine we have more than one thread in play, and a single thread
721 // sends a synchronous, then an asynchronous command. Imagine the
722 // asynchronous command is sent on the first client connection. Then, if
723 // we naively send a synchronous command to that same connection, the
724 // thread on the far side might be busy processing the asynchronous
725 // command. So, we move to considering the second available thread
726 // for subsequent calls.
727 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000728 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
729 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000730 }
731
Steven Morelandc7d40132021-06-10 03:42:11 +0000732 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000733 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000734 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000735 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000736 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
737 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000738
739 // asynchronous calls cannot be nested, we currently allow ref count
740 // calls to be nested (so that you can use this without having extra
741 // threads). Note 'drainCommands' is used so that these ref counts can't
742 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000743 if (exclusiveIncoming != nullptr) {
744 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000745 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000746 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000747 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
748 // prefer available socket, but if we don't have one, don't
749 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000750 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000751 }
752 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000753 }
754
Steven Moreland85e067b2021-05-26 17:43:53 +0000755 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000756 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000757 connection->mConnection = exclusive;
758 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000759 break;
760 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000761 connection->mConnection = available;
762 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000763 break;
764 }
765
Steven Moreland19fc9f72021-06-10 03:57:30 +0000766 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000767 ALOGE("Session has no client connections. This is required for an RPC server to make "
768 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
769 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000770 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000771 return WOULD_BLOCK;
772 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000773
Steven Moreland85e067b2021-05-26 17:43:53 +0000774 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000775 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000776 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000777 }
Steven Moreland195edb82021-06-08 02:44:39 +0000778 session->mWaitingThreads--;
779
780 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000781}
782
783void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
784 sp<RpcConnection>* available,
785 std::vector<sp<RpcConnection>>& sockets,
786 size_t socketsIndexHint) {
787 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
788 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
789
790 if (*exclusive != nullptr) return; // consistent with break below
791
792 for (size_t i = 0; i < sockets.size(); i++) {
793 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
794
Steven Moreland85e067b2021-05-26 17:43:53 +0000795 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000796 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
797 *available = socket;
798 continue;
799 }
800
Steven Moreland85e067b2021-05-26 17:43:53 +0000801 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000802 // (nested transactions)
803 if (exclusive && socket->exclusiveTid == tid) {
804 *exclusive = socket;
805 break; // consistent with return above
806 }
807 }
808}
809
810RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000811 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000812 // is using this fd, and it retains the right to it. So, we don't give up
813 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000814 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000815 std::unique_lock<std::mutex> _l(mSession->mMutex);
816 mConnection->exclusiveTid = std::nullopt;
817 if (mSession->mWaitingThreads > 0) {
818 _l.unlock();
819 mSession->mAvailableConnectionCv.notify_one();
820 }
821 }
822}
823
824} // namespace android