blob: 8da3fa3c3f646acb677c93cb9d9ca0974831cbf0 [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 Hongecf937d2021-08-11 17:29:28 -070052RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
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 Hongecf937d2021-08-11 17:29:28 -070065sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070066 // Default is without TLS.
Yifan Hongfdd9f692021-09-09 15:12:52 -070067 return make(RpcTransportCtxFactoryRaw::make());
Yifan Hongecf937d2021-08-11 17:29:28 -070068}
69
Yifan Hongfdd9f692021-09-09 15:12:52 -070070sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
Yifan Hongecf937d2021-08-11 17:29:28 -070071 auto ctx = rpcTransportCtxFactory->newClientCtx();
72 if (ctx == nullptr) return nullptr;
Yifan Hongecf937d2021-08-11 17:29:28 -070073 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000074}
75
Steven Moreland103424e2021-06-02 18:16:19 +000076void RpcSession::setMaxThreads(size_t threads) {
77 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000078 LOG_ALWAYS_FATAL_IF(!mOutgoingConnections.empty() || !mIncomingConnections.empty(),
Steven Moreland103424e2021-06-02 18:16:19 +000079 "Must set max threads before setting up connections, but has %zu client(s) "
80 "and %zu server(s)",
Steven Moreland19fc9f72021-06-10 03:57:30 +000081 mOutgoingConnections.size(), mIncomingConnections.size());
Steven Moreland103424e2021-06-02 18:16:19 +000082 mMaxThreads = threads;
83}
84
85size_t RpcSession::getMaxThreads() {
86 std::lock_guard<std::mutex> _l(mMutex);
87 return mMaxThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000088}
89
Steven Morelandbf57bce2021-07-26 15:26:12 -070090bool RpcSession::setProtocolVersion(uint32_t version) {
91 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
92 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
93 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
94 "is %u).",
95 version, RPC_WIRE_PROTOCOL_VERSION);
96 return false;
97 }
98
99 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -0700100 if (mProtocolVersion && version > *mProtocolVersion) {
101 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
102 *mProtocolVersion, version);
103 return false;
104 }
105
Steven Morelandbf57bce2021-07-26 15:26:12 -0700106 mProtocolVersion = version;
107 return true;
108}
109
110std::optional<uint32_t> RpcSession::getProtocolVersion() {
111 std::lock_guard<std::mutex> _l(mMutex);
112 return mProtocolVersion;
113}
114
Steven Moreland2372f9d2021-08-05 15:42:01 -0700115status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000116 return setupSocketClient(UnixSocketAddress(path));
117}
118
Steven Moreland2372f9d2021-08-05 15:42:01 -0700119status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000120 return setupSocketClient(VsockSocketAddress(cid, port));
121}
122
Steven Moreland2372f9d2021-08-05 15:42:01 -0700123status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000124 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700125 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000126 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
127 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700128 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000129 }
130 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 -0700131 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000132}
133
Steven Moreland2372f9d2021-08-05 15:42:01 -0700134status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
135 return setupClient([&](const RpcAddress& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700136 // std::move'd from fd becomes -1 (!ok())
137 if (!fd.ok()) {
138 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700139 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700140 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700141 if (auto res = setNonBlocking(fd); !res.ok()) {
142 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
143 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
144 }
Steven Moreland4198a122021-08-03 17:37:58 -0700145 return initAndAddConnection(std::move(fd), sessionId, incoming);
146 });
147}
148
Steven Moreland2372f9d2021-08-05 15:42:01 -0700149status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700150 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700151 if (auto status = initShutdownTrigger(); status != OK) return status;
152
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000153 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
154
155 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700156 int savedErrno = errno;
157 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
158 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000159 }
160
Yifan Hongecf937d2021-08-11 17:29:28 -0700161 auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700162 if (server == nullptr) {
163 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700164 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700165 }
166 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000167}
168
169sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000170 ExclusiveConnection connection;
171 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
172 ConnectionUse::CLIENT, &connection);
173 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000174 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000175}
176
Steven Moreland1be91352021-05-11 22:12:15 +0000177status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000178 ExclusiveConnection connection;
179 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
180 ConnectionUse::CLIENT, &connection);
181 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000182 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000183}
184
Steven Morelandc9d7b532021-06-04 20:57:41 +0000185bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000186 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000187 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000188
189 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000190
Steven Morelandc9d7b532021-06-04 20:57:41 +0000191 if (wait) {
192 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
193 mShutdownListener->waitForShutdown(_l);
Steven Morelanddd67b942021-07-23 17:15:41 -0700194
Steven Morelandc9d7b532021-06-04 20:57:41 +0000195 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
196 }
197
198 _l.unlock();
199 mState->clear();
200
Steven Moreland659416d2021-05-11 00:47:50 +0000201 return true;
202}
203
Steven Morelandf5174272021-05-25 00:39:28 +0000204status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000205 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000206 ExclusiveConnection connection;
207 status_t status =
208 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
209 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
210 : ConnectionUse::CLIENT,
211 &connection);
212 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000213 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000214 sp<RpcSession>::fromExisting(this), reply, flags);
215}
216
217status_t RpcSession::sendDecStrong(const RpcAddress& address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000218 ExclusiveConnection connection;
219 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
220 ConnectionUse::CLIENT_REFCOUNT, &connection);
221 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000222 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000223}
224
225status_t RpcSession::readId() {
226 {
227 std::lock_guard<std::mutex> _l(mMutex);
228 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
229 }
230
Steven Moreland195edb82021-06-08 02:44:39 +0000231 ExclusiveConnection connection;
232 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
233 ConnectionUse::CLIENT, &connection);
234 if (status != OK) return status;
235
Steven Moreland01a6bad2021-06-11 00:59:20 +0000236 mId = RpcAddress::zero();
237 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this),
238 &mId.value());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000239 if (status != OK) return status;
240
Steven Moreland01a6bad2021-06-11 00:59:20 +0000241 LOG_RPC_DETAIL("RpcSession %p has id %s", this, mId->toString().c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000242 return OK;
243}
244
Steven Morelanddd67b942021-07-23 17:15:41 -0700245void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000246 const sp<RpcSession>& session) {
247 (void)session;
248 mShutdown = true;
249}
250
Steven Moreland19fc9f72021-06-10 03:57:30 +0000251void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000252 mCv.notify_all();
253}
254
255void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
256 while (!mShutdown) {
257 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
258 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
259 }
260 }
261}
262
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000263void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000264 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000265
Steven Morelanda63ff932021-05-12 00:03:15 +0000266 {
267 std::lock_guard<std::mutex> _l(mMutex);
268 mThreads[thread.get_id()] = std::move(thread);
269 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000270}
Steven Morelanda63ff932021-05-12 00:03:15 +0000271
Yifan Hong702115c2021-06-24 15:39:18 -0700272RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
273 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000274 // must be registered to allow arbitrary client code executing commands to
275 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700276 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000277
Steven Morelanddd67b942021-07-23 17:15:41 -0700278 status_t status;
279
280 if (connection == nullptr) {
281 status = DEAD_OBJECT;
282 } else {
283 status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
284 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000285
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000286 return PreJoinSetupResult{
287 .connection = std::move(connection),
288 .status = status,
289 };
290}
291
Yifan Hong194acf22021-06-29 18:44:56 -0700292namespace {
293// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
294// Android Runtime doesn't exist, no-op.
295class JavaThreadAttacher {
296public:
297 JavaThreadAttacher() {
298 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
299 // libbinder.
300 auto vm = getJavaVM();
301 if (vm == nullptr) return;
302
303 char threadName[16];
304 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
305 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
306 memcpy(threadName, defaultThreadName,
307 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
308 }
309 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
310 JavaVMAttachArgs args;
311 args.version = JNI_VERSION_1_2;
312 args.name = threadName;
313 args.group = nullptr;
314 JNIEnv* env;
315
316 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
317 "Cannot attach thread %s to JVM", threadName);
318 mAttached = true;
319 }
320 ~JavaThreadAttacher() {
321 if (!mAttached) return;
322 auto vm = getJavaVM();
323 LOG_ALWAYS_FATAL_IF(vm == nullptr,
324 "Unable to detach thread. No JavaVM, but it was present before!");
325
326 LOG_RPC_DETAIL("Detaching current thread from JVM");
327 if (vm->DetachCurrentThread() != JNI_OK) {
328 mAttached = false;
329 } else {
330 ALOGW("Unable to detach current thread from JVM");
331 }
332 }
333
334private:
335 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
336 bool mAttached = false;
337
338 static JavaVM* getJavaVM() {
339 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
340 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
341 if (fn == nullptr) return nullptr;
342 return fn();
343 }
344};
345} // namespace
346
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000347void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
348 sp<RpcConnection>& connection = setupResult.connection;
349
350 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700351 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hong194acf22021-06-29 18:44:56 -0700352 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000353 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000354 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000355 RpcState::CommandType::ANY);
356 if (status != OK) {
357 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
358 statusToString(status).c_str());
359 break;
360 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000361 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000362 } else {
363 ALOGE("Connection failed to init, closing with status %s",
364 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000365 }
366
Steven Moreland659416d2021-05-11 00:47:50 +0000367 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000368 {
Steven Moreland659416d2021-05-11 00:47:50 +0000369 std::lock_guard<std::mutex> _l(session->mMutex);
370 auto it = session->mThreads.find(std::this_thread::get_id());
371 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000372 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000373 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000374
Steven Moreland659416d2021-05-11 00:47:50 +0000375 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000376 }
377
Steven Morelanddd67b942021-07-23 17:15:41 -0700378 // done after all cleanup, since session shutdown progresses via callbacks here
379 if (connection != nullptr) {
380 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
381 "bad state: connection object guaranteed to be in list");
382 }
383
Steven Moreland659416d2021-05-11 00:47:50 +0000384 session = nullptr;
385
386 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000387 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000388 }
389}
390
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000391sp<RpcServer> RpcSession::server() {
392 RpcServer* unsafeServer = mForServer.unsafe_get();
393 sp<RpcServer> server = mForServer.promote();
394
395 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
396 "wp<> is to avoid strong cycle only");
397 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000398}
399
Steven Moreland2372f9d2021-08-05 15:42:01 -0700400status_t RpcSession::setupClient(
401 const std::function<status_t(const RpcAddress& sessionId, bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000402 {
403 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000404 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000405 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000406 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000407 }
Yifan Hong832521e2021-08-05 14:55:40 -0700408 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409
Steven Moreland2372f9d2021-08-05 15:42:01 -0700410 if (status_t status = connectAndInit(RpcAddress::zero(), false /*incoming*/); status != OK)
411 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000412
Steven Morelandbf57bce2021-07-26 15:26:12 -0700413 {
414 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700415 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
416 ConnectionUse::CLIENT, &connection);
417 status != OK)
418 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700419
420 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700421 if (status_t status =
422 state()->readNewSessionResponse(connection.get(),
423 sp<RpcSession>::fromExisting(this), &version);
424 status != OK)
425 return status;
426 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700427 }
428
Steven Morelanda5036f02021-06-08 02:26:57 +0000429 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000430 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000431 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000432 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700433 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000434 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700435 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000436 }
437
438 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700439 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000440 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700441 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000442 }
443
Steven Morelanda5036f02021-06-08 02:26:57 +0000444 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000445 // instead of all at once - the other side should be responsible for setting
446 // up additional connections. We need to create at least one (unless 0 are
447 // requested to be set) in order to allow the other side to reliably make
448 // any requests at all.
449
Steven Moreland4198a122021-08-03 17:37:58 -0700450 // we've already setup one client
451 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700452 if (status_t status = connectAndInit(mId.value(), false /*incoming*/); status != OK)
453 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700454 }
455
Steven Moreland103424e2021-06-02 18:16:19 +0000456 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700457 if (status_t status = connectAndInit(mId.value(), true /*incoming*/); status != OK)
458 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000459 }
460
Steven Moreland2372f9d2021-08-05 15:42:01 -0700461 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000462}
463
Steven Moreland2372f9d2021-08-05 15:42:01 -0700464status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700465 return setupClient([&](const RpcAddress& sessionId, bool incoming) {
466 return setupOneSocketConnection(addr, sessionId, incoming);
467 });
468}
469
Steven Moreland2372f9d2021-08-05 15:42:01 -0700470status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
471 const RpcAddress& sessionId, bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000472 for (size_t tries = 0; tries < 5; tries++) {
473 if (tries > 0) usleep(10000);
474
Yifan Hongb675ffe2021-08-05 16:37:17 -0700475 unique_fd serverFd(TEMP_FAILURE_RETRY(
476 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000477 if (serverFd == -1) {
478 int savedErrno = errno;
479 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
480 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700481 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000482 }
483
484 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700485 int connErrno = errno;
486 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
487 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
488 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
489 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
490 if (pollStatus != OK) {
491 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
492 statusToString(pollStatus).c_str());
493 return pollStatus;
494 }
495 // Set connErrno to the errno that connect() would have set if the fd were blocking.
496 socklen_t connErrnoLen = sizeof(connErrno);
497 int ret =
498 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
499 if (ret == -1) {
500 int savedErrno = errno;
501 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
502 "(Original error from connect() is: %s)",
503 strerror(savedErrno), strerror(connErrno));
504 return -savedErrno;
505 }
506 // Retrieved the real connErrno as if connect() was called with a blocking socket
507 // fd. Continue checking connErrno.
508 }
509 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000510 ALOGW("Connection reset on %s", addr.toString().c_str());
511 continue;
512 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700513 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
514 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700515 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700516 strerror(connErrno));
517 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700518 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000519 }
Yifan Hong702115c2021-06-24 15:39:18 -0700520 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
521
Steven Moreland4198a122021-08-03 17:37:58 -0700522 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000523 }
524
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000525 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700526 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000527}
528
Steven Moreland2372f9d2021-08-05 15:42:01 -0700529status_t RpcSession::initAndAddConnection(unique_fd fd, const RpcAddress& sessionId,
530 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700531 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700532 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700533 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700534 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700535 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700536 }
537
538 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
539
540 RpcConnectionHeader header{
541 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
542 .options = 0,
543 };
544 memcpy(&header.sessionId, &sessionId.viewRawEmbedded(), sizeof(RpcWireAddress));
545
546 if (incoming) header.options |= RPC_CONNECTION_OPTION_INCOMING;
547
Yifan Hong8c950422021-08-05 17:13:55 -0700548 auto sendHeaderStatus =
549 server->interruptableWriteFully(mShutdownTrigger.get(), &header, sizeof(header));
550 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700551 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700552 statusToString(sendHeaderStatus).c_str());
553 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700554 }
555
556 LOG_RPC_DETAIL("Socket at client: header sent");
557
558 if (incoming) {
559 return addIncomingConnection(std::move(server));
560 } else {
561 return addOutgoingConnection(std::move(server), true /*init*/);
562 }
563}
564
Steven Moreland2372f9d2021-08-05 15:42:01 -0700565status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000566 std::mutex mutex;
567 std::condition_variable joinCv;
568 std::unique_lock<std::mutex> lock(mutex);
569 std::thread thread;
570 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
571 bool ownershipTransferred = false;
572 thread = std::thread([&]() {
573 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700574 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000575 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
576 sp<RpcSession> session = thiz;
577 session->preJoinThreadOwnership(std::move(thread));
578
579 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700580 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000581
582 ownershipTransferred = true;
583 threadLock.unlock();
584 joinCv.notify_one();
585 // do not use & vars below
586
587 RpcSession::join(std::move(session), std::move(setupResult));
588 });
589 joinCv.wait(lock, [&] { return ownershipTransferred; });
590 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700591 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000592}
593
Yifan Hong832521e2021-08-05 14:55:40 -0700594status_t RpcSession::initShutdownTrigger() {
595 // first client connection added, but setForServer not called, so
596 // initializaing for a client.
597 if (mShutdownTrigger == nullptr) {
598 mShutdownTrigger = FdTrigger::make();
599 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
600 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
601 }
602 return OK;
603}
604
Steven Moreland2372f9d2021-08-05 15:42:01 -0700605status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000606 sp<RpcConnection> connection = sp<RpcConnection>::make();
607 {
608 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700609 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000610 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000611 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000612 }
613
Steven Morelandb86e26b2021-06-12 00:35:58 +0000614 status_t status = OK;
615 if (init) {
616 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
617 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000618
619 {
620 std::lock_guard<std::mutex> _l(mMutex);
621 connection->exclusiveTid = std::nullopt;
622 }
623
Steven Moreland2372f9d2021-08-05 15:42:01 -0700624 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000625}
626
Steven Morelanda8b44292021-06-08 01:27:53 +0000627bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000628 const RpcAddress& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000629 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
630 LOG_ALWAYS_FATAL_IF(server == nullptr);
631 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
632 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000633 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000634
635 mShutdownTrigger = FdTrigger::make();
636 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000637
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000638 mId = sessionId;
639 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000640 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000641 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000642}
643
Yifan Hong702115c2021-06-24 15:39:18 -0700644sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
645 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000646 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700647
Steven Moreland132d5bf2021-08-03 16:13:24 -0700648 if (mIncomingConnections.size() >= mMaxThreads) {
649 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
650 mIncomingConnections.size(), mMaxThreads);
651 return nullptr;
652 }
653
Steven Morelanddd67b942021-07-23 17:15:41 -0700654 // Don't accept any more connections, some have shutdown. Usually this
655 // happens when new connections are still being established as part of a
656 // very short-lived session which shuts down after it already started
657 // accepting new connections.
658 if (mIncomingConnections.size() < mMaxIncomingConnections) {
659 return nullptr;
660 }
661
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000662 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700663 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000664 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700665
Steven Moreland19fc9f72021-06-10 03:57:30 +0000666 mIncomingConnections.push_back(session);
Steven Morelanddd67b942021-07-23 17:15:41 -0700667 mMaxIncomingConnections = mIncomingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000668
669 return session;
670}
671
Steven Moreland19fc9f72021-06-10 03:57:30 +0000672bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700673 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000674 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
675 it != mIncomingConnections.end()) {
676 mIncomingConnections.erase(it);
677 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000678 sp<EventListener> listener = mEventListener.promote();
679 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700680 _l.unlock();
681 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000682 }
Steven Morelandee78e762021-05-05 21:12:51 +0000683 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000684 return true;
685 }
686 return false;
687}
688
Yifan Hongecf937d2021-08-11 17:29:28 -0700689std::string RpcSession::getCertificate(CertificateFormat format) {
690 return mCtx->getCertificate(format);
691}
692
Steven Moreland195edb82021-06-08 02:44:39 +0000693status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
694 ExclusiveConnection* connection) {
695 connection->mSession = session;
696 connection->mConnection = nullptr;
697 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000698
Steven Moreland195edb82021-06-08 02:44:39 +0000699 pid_t tid = gettid();
700 std::unique_lock<std::mutex> _l(session->mMutex);
701
702 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000703 while (true) {
704 sp<RpcConnection> exclusive;
705 sp<RpcConnection> available;
706
707 // CHECK FOR DEDICATED CLIENT SOCKET
708 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000709 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000710 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
711 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000712
713 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000714 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000715 //
716 // Imagine we have more than one thread in play, and a single thread
717 // sends a synchronous, then an asynchronous command. Imagine the
718 // asynchronous command is sent on the first client connection. Then, if
719 // we naively send a synchronous command to that same connection, the
720 // thread on the far side might be busy processing the asynchronous
721 // command. So, we move to considering the second available thread
722 // for subsequent calls.
723 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000724 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
725 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000726 }
727
Steven Morelandc7d40132021-06-10 03:42:11 +0000728 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000729 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000730 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000731 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000732 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
733 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000734
735 // asynchronous calls cannot be nested, we currently allow ref count
736 // calls to be nested (so that you can use this without having extra
737 // threads). Note 'drainCommands' is used so that these ref counts can't
738 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000739 if (exclusiveIncoming != nullptr) {
740 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000741 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000742 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000743 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
744 // prefer available socket, but if we don't have one, don't
745 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000746 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000747 }
748 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000749 }
750
Steven Moreland85e067b2021-05-26 17:43:53 +0000751 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000752 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000753 connection->mConnection = exclusive;
754 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000755 break;
756 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000757 connection->mConnection = available;
758 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000759 break;
760 }
761
Steven Moreland19fc9f72021-06-10 03:57:30 +0000762 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000763 ALOGE("Session has no client connections. This is required for an RPC server to make "
764 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
765 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000766 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000767 return WOULD_BLOCK;
768 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000769
Steven Moreland85e067b2021-05-26 17:43:53 +0000770 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000771 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000772 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000773 }
Steven Moreland195edb82021-06-08 02:44:39 +0000774 session->mWaitingThreads--;
775
776 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000777}
778
779void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
780 sp<RpcConnection>* available,
781 std::vector<sp<RpcConnection>>& sockets,
782 size_t socketsIndexHint) {
783 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
784 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
785
786 if (*exclusive != nullptr) return; // consistent with break below
787
788 for (size_t i = 0; i < sockets.size(); i++) {
789 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
790
Steven Moreland85e067b2021-05-26 17:43:53 +0000791 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000792 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
793 *available = socket;
794 continue;
795 }
796
Steven Moreland85e067b2021-05-26 17:43:53 +0000797 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000798 // (nested transactions)
799 if (exclusive && socket->exclusiveTid == tid) {
800 *exclusive = socket;
801 break; // consistent with return above
802 }
803 }
804}
805
806RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000807 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000808 // is using this fd, and it retains the right to it. So, we don't give up
809 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000810 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000811 std::unique_lock<std::mutex> _l(mSession->mMutex);
812 mConnection->exclusiveTid = std::nullopt;
813 if (mSession->mWaitingThreads > 0) {
814 _l.unlock();
815 mSession->mAvailableConnectionCv.notify_one();
816 }
817 }
818}
819
820} // namespace android