blob: e8f984c717e902de311ee3c7c1ecddbc73904387 [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 Moreland826367f2021-09-10 14:05:31 -070029#include <android-base/hex.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000030#include <android-base/macros.h>
Yifan Hong194acf22021-06-29 18:44:56 -070031#include <android_runtime/vm.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000032#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000033#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070034#include <binder/RpcTransportRaw.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000035#include <binder/Stability.h>
Yifan Hong194acf22021-06-29 18:44:56 -070036#include <jni.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000037#include <utils/String8.h>
38
Yifan Hong8c950422021-08-05 17:13:55 -070039#include "FdTrigger.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000040#include "RpcSocketAddress.h"
41#include "RpcState.h"
42#include "RpcWireFormat.h"
Yifan Hongb675ffe2021-08-05 16:37:17 -070043#include "Utils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000044
45#ifdef __GLIBC__
46extern "C" pid_t gettid();
47#endif
48
49namespace android {
50
51using base::unique_fd;
52
Yifan Hongecf937d2021-08-11 17:29:28 -070053RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
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 Hongecf937d2021-08-11 17:29:28 -070066sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070067 // Default is without TLS.
Yifan Hongecf937d2021-08-11 17:29:28 -070068 return make(RpcTransportCtxFactoryRaw::make(), std::nullopt, std::nullopt);
69}
70
71sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory,
72 std::optional<CertificateFormat> serverCertificateFormat,
73 std::optional<std::string> serverCertificate) {
74 auto ctx = rpcTransportCtxFactory->newClientCtx();
75 if (ctx == nullptr) return nullptr;
76 LOG_ALWAYS_FATAL_IF(serverCertificateFormat.has_value() != serverCertificate.has_value());
77 if (serverCertificateFormat.has_value() && serverCertificate.has_value()) {
78 status_t status =
79 ctx->addTrustedPeerCertificate(*serverCertificateFormat, *serverCertificate);
80 if (status != OK) {
81 ALOGE("Cannot add trusted server certificate: %s", statusToString(status).c_str());
82 return nullptr;
83 }
84 }
85 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000086}
87
Steven Moreland103424e2021-06-02 18:16:19 +000088void RpcSession::setMaxThreads(size_t threads) {
89 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000090 LOG_ALWAYS_FATAL_IF(!mOutgoingConnections.empty() || !mIncomingConnections.empty(),
Steven Moreland103424e2021-06-02 18:16:19 +000091 "Must set max threads before setting up connections, but has %zu client(s) "
92 "and %zu server(s)",
Steven Moreland19fc9f72021-06-10 03:57:30 +000093 mOutgoingConnections.size(), mIncomingConnections.size());
Steven Moreland103424e2021-06-02 18:16:19 +000094 mMaxThreads = threads;
95}
96
97size_t RpcSession::getMaxThreads() {
98 std::lock_guard<std::mutex> _l(mMutex);
99 return mMaxThreads;
Steven Moreland659416d2021-05-11 00:47:50 +0000100}
101
Steven Morelandbf57bce2021-07-26 15:26:12 -0700102bool RpcSession::setProtocolVersion(uint32_t version) {
103 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
104 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
105 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
106 "is %u).",
107 version, RPC_WIRE_PROTOCOL_VERSION);
108 return false;
109 }
110
111 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -0700112 if (mProtocolVersion && version > *mProtocolVersion) {
113 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
114 *mProtocolVersion, version);
115 return false;
116 }
117
Steven Morelandbf57bce2021-07-26 15:26:12 -0700118 mProtocolVersion = version;
119 return true;
120}
121
122std::optional<uint32_t> RpcSession::getProtocolVersion() {
123 std::lock_guard<std::mutex> _l(mMutex);
124 return mProtocolVersion;
125}
126
Steven Moreland2372f9d2021-08-05 15:42:01 -0700127status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000128 return setupSocketClient(UnixSocketAddress(path));
129}
130
Steven Moreland2372f9d2021-08-05 15:42:01 -0700131status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000132 return setupSocketClient(VsockSocketAddress(cid, port));
133}
134
Steven Moreland2372f9d2021-08-05 15:42:01 -0700135status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000136 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700137 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000138 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
139 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700140 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000141 }
142 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 -0700143 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000144}
145
Steven Moreland2372f9d2021-08-05 15:42:01 -0700146status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
Steven Moreland826367f2021-09-10 14:05:31 -0700147 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700148 // std::move'd from fd becomes -1 (!ok())
149 if (!fd.ok()) {
150 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700151 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700152 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700153 if (auto res = setNonBlocking(fd); !res.ok()) {
154 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
155 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
156 }
Steven Moreland4198a122021-08-03 17:37:58 -0700157 return initAndAddConnection(std::move(fd), sessionId, incoming);
158 });
159}
160
Steven Moreland2372f9d2021-08-05 15:42:01 -0700161status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700162 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700163 if (auto status = initShutdownTrigger(); status != OK) return status;
164
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000165 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
166
167 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700168 int savedErrno = errno;
169 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
170 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000171 }
172
Yifan Hongecf937d2021-08-11 17:29:28 -0700173 auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700174 if (server == nullptr) {
175 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700176 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700177 }
178 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000179}
180
181sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000182 ExclusiveConnection connection;
183 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
184 ConnectionUse::CLIENT, &connection);
185 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000186 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000187}
188
Steven Moreland1be91352021-05-11 22:12:15 +0000189status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000190 ExclusiveConnection connection;
191 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
192 ConnectionUse::CLIENT, &connection);
193 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000194 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000195}
196
Steven Morelandc9d7b532021-06-04 20:57:41 +0000197bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000198 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000199 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000200
201 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000202
Steven Morelandc9d7b532021-06-04 20:57:41 +0000203 if (wait) {
204 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700205 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700206
Steven Morelandc9d7b532021-06-04 20:57:41 +0000207 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
208 }
209
210 _l.unlock();
211 mState->clear();
212
Steven Moreland659416d2021-05-11 00:47:50 +0000213 return true;
214}
215
Steven Morelandf5174272021-05-25 00:39:28 +0000216status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000217 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000218 ExclusiveConnection connection;
219 status_t status =
220 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
221 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
222 : ConnectionUse::CLIENT,
223 &connection);
224 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000225 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000226 sp<RpcSession>::fromExisting(this), reply, flags);
227}
228
Steven Moreland5623d1a2021-09-10 15:45:34 -0700229status_t RpcSession::sendDecStrong(uint64_t address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000230 ExclusiveConnection connection;
231 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
232 ConnectionUse::CLIENT_REFCOUNT, &connection);
233 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000234 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000235}
236
237status_t RpcSession::readId() {
238 {
239 std::lock_guard<std::mutex> _l(mMutex);
240 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
241 }
242
Steven Moreland195edb82021-06-08 02:44:39 +0000243 ExclusiveConnection connection;
244 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
245 ConnectionUse::CLIENT, &connection);
246 if (status != OK) return status;
247
Steven Moreland826367f2021-09-10 14:05:31 -0700248 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000249 if (status != OK) return status;
250
Steven Moreland826367f2021-09-10 14:05:31 -0700251 LOG_RPC_DETAIL("RpcSession %p has id %s", this,
252 base::HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000253 return OK;
254}
255
Steven Morelanddd67b942021-07-23 17:15:41 -0700256void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000257 const sp<RpcSession>& session) {
258 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000259}
260
Steven Moreland19fc9f72021-06-10 03:57:30 +0000261void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000262 mCv.notify_all();
263}
264
Steven Moreland791e4662021-09-13 15:22:58 -0700265void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock,
266 const sp<RpcSession>& session) {
267 while (session->mIncomingConnections.size() > 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000268 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700269 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
270 "still.",
271 session->mIncomingConnections.size());
Steven Moreland659416d2021-05-11 00:47:50 +0000272 }
273 }
274}
275
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000276void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000277 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000278
Steven Morelanda63ff932021-05-12 00:03:15 +0000279 {
280 std::lock_guard<std::mutex> _l(mMutex);
281 mThreads[thread.get_id()] = std::move(thread);
282 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000283}
Steven Morelanda63ff932021-05-12 00:03:15 +0000284
Yifan Hong702115c2021-06-24 15:39:18 -0700285RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
286 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000287 // must be registered to allow arbitrary client code executing commands to
288 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700289 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000290
Steven Morelanddd67b942021-07-23 17:15:41 -0700291 status_t status;
292
293 if (connection == nullptr) {
294 status = DEAD_OBJECT;
295 } else {
296 status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
297 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000298
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000299 return PreJoinSetupResult{
300 .connection = std::move(connection),
301 .status = status,
302 };
303}
304
Yifan Hong194acf22021-06-29 18:44:56 -0700305namespace {
306// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
307// Android Runtime doesn't exist, no-op.
308class JavaThreadAttacher {
309public:
310 JavaThreadAttacher() {
311 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
312 // libbinder.
313 auto vm = getJavaVM();
314 if (vm == nullptr) return;
315
316 char threadName[16];
317 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
318 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
319 memcpy(threadName, defaultThreadName,
320 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
321 }
322 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
323 JavaVMAttachArgs args;
324 args.version = JNI_VERSION_1_2;
325 args.name = threadName;
326 args.group = nullptr;
327 JNIEnv* env;
328
329 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
330 "Cannot attach thread %s to JVM", threadName);
331 mAttached = true;
332 }
333 ~JavaThreadAttacher() {
334 if (!mAttached) return;
335 auto vm = getJavaVM();
336 LOG_ALWAYS_FATAL_IF(vm == nullptr,
337 "Unable to detach thread. No JavaVM, but it was present before!");
338
339 LOG_RPC_DETAIL("Detaching current thread from JVM");
340 if (vm->DetachCurrentThread() != JNI_OK) {
341 mAttached = false;
342 } else {
343 ALOGW("Unable to detach current thread from JVM");
344 }
345 }
346
347private:
348 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
349 bool mAttached = false;
350
351 static JavaVM* getJavaVM() {
352 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
353 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
354 if (fn == nullptr) return nullptr;
355 return fn();
356 }
357};
358} // namespace
359
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000360void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
361 sp<RpcConnection>& connection = setupResult.connection;
362
363 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700364 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hong194acf22021-06-29 18:44:56 -0700365 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000366 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000367 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000368 RpcState::CommandType::ANY);
369 if (status != OK) {
370 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
371 statusToString(status).c_str());
372 break;
373 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000374 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000375 } else {
376 ALOGE("Connection failed to init, closing with status %s",
377 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000378 }
379
Steven Moreland659416d2021-05-11 00:47:50 +0000380 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000381 {
Steven Moreland659416d2021-05-11 00:47:50 +0000382 std::lock_guard<std::mutex> _l(session->mMutex);
383 auto it = session->mThreads.find(std::this_thread::get_id());
384 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000385 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000386 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000387
Steven Moreland659416d2021-05-11 00:47:50 +0000388 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000389 }
390
Steven Morelanddd67b942021-07-23 17:15:41 -0700391 // done after all cleanup, since session shutdown progresses via callbacks here
392 if (connection != nullptr) {
393 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
394 "bad state: connection object guaranteed to be in list");
395 }
396
Steven Moreland659416d2021-05-11 00:47:50 +0000397 session = nullptr;
398
399 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000400 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000401 }
402}
403
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000404sp<RpcServer> RpcSession::server() {
405 RpcServer* unsafeServer = mForServer.unsafe_get();
406 sp<RpcServer> server = mForServer.promote();
407
408 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
409 "wp<> is to avoid strong cycle only");
410 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000411}
412
Steven Moreland826367f2021-09-10 14:05:31 -0700413status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
414 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000415 {
416 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000417 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000418 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000419 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000420 }
Yifan Hong832521e2021-08-05 14:55:40 -0700421 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000422
Steven Moreland826367f2021-09-10 14:05:31 -0700423 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000424
Steven Morelandbf57bce2021-07-26 15:26:12 -0700425 {
426 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700427 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
428 ConnectionUse::CLIENT, &connection);
429 status != OK)
430 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700431
432 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700433 if (status_t status =
434 state()->readNewSessionResponse(connection.get(),
435 sp<RpcSession>::fromExisting(this), &version);
436 status != OK)
437 return status;
438 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700439 }
440
Steven Morelanda5036f02021-06-08 02:26:57 +0000441 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000442 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000443 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000444 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700445 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000446 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700447 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000448 }
449
450 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700451 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000452 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700453 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000454 }
455
Steven Morelanda5036f02021-06-08 02:26:57 +0000456 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000457 // instead of all at once - the other side should be responsible for setting
458 // up additional connections. We need to create at least one (unless 0 are
459 // requested to be set) in order to allow the other side to reliably make
460 // any requests at all.
461
Steven Moreland4198a122021-08-03 17:37:58 -0700462 // we've already setup one client
463 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700464 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700465 }
466
Steven Moreland103424e2021-06-02 18:16:19 +0000467 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700468 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000469 }
470
Steven Moreland2372f9d2021-08-05 15:42:01 -0700471 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000472}
473
Steven Moreland2372f9d2021-08-05 15:42:01 -0700474status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700475 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700476 return setupOneSocketConnection(addr, sessionId, incoming);
477 });
478}
479
Steven Moreland2372f9d2021-08-05 15:42:01 -0700480status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700481 const std::vector<uint8_t>& sessionId,
482 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000483 for (size_t tries = 0; tries < 5; tries++) {
484 if (tries > 0) usleep(10000);
485
Yifan Hongb675ffe2021-08-05 16:37:17 -0700486 unique_fd serverFd(TEMP_FAILURE_RETRY(
487 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000488 if (serverFd == -1) {
489 int savedErrno = errno;
490 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
491 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700492 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000493 }
494
495 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700496 int connErrno = errno;
497 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
498 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
499 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
500 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
501 if (pollStatus != OK) {
502 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
503 statusToString(pollStatus).c_str());
504 return pollStatus;
505 }
506 // Set connErrno to the errno that connect() would have set if the fd were blocking.
507 socklen_t connErrnoLen = sizeof(connErrno);
508 int ret =
509 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
510 if (ret == -1) {
511 int savedErrno = errno;
512 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
513 "(Original error from connect() is: %s)",
514 strerror(savedErrno), strerror(connErrno));
515 return -savedErrno;
516 }
517 // Retrieved the real connErrno as if connect() was called with a blocking socket
518 // fd. Continue checking connErrno.
519 }
520 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000521 ALOGW("Connection reset on %s", addr.toString().c_str());
522 continue;
523 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700524 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
525 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700526 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700527 strerror(connErrno));
528 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700529 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000530 }
Yifan Hong702115c2021-06-24 15:39:18 -0700531 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
532
Steven Moreland4198a122021-08-03 17:37:58 -0700533 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000534 }
535
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000536 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700537 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000538}
539
Steven Moreland826367f2021-09-10 14:05:31 -0700540status_t RpcSession::initAndAddConnection(unique_fd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700541 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700542 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700543 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700544 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700545 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700546 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700547 }
548
549 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
550
Steven Moreland826367f2021-09-10 14:05:31 -0700551 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
552 ALOGE("Session ID too big %zu", sessionId.size());
553 return BAD_VALUE;
554 }
555
Steven Moreland4198a122021-08-03 17:37:58 -0700556 RpcConnectionHeader header{
557 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
558 .options = 0,
Steven Moreland826367f2021-09-10 14:05:31 -0700559 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700560 };
Steven Moreland4198a122021-08-03 17:37:58 -0700561
Steven Moreland826367f2021-09-10 14:05:31 -0700562 if (incoming) {
563 header.options |= RPC_CONNECTION_OPTION_INCOMING;
564 }
Steven Moreland4198a122021-08-03 17:37:58 -0700565
Yifan Hong8c950422021-08-05 17:13:55 -0700566 auto sendHeaderStatus =
567 server->interruptableWriteFully(mShutdownTrigger.get(), &header, sizeof(header));
568 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700569 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700570 statusToString(sendHeaderStatus).c_str());
571 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700572 }
573
Steven Moreland826367f2021-09-10 14:05:31 -0700574 if (sessionId.size() > 0) {
575 auto sendSessionIdStatus =
576 server->interruptableWriteFully(mShutdownTrigger.get(), sessionId.data(),
577 sessionId.size());
578 if (sendSessionIdStatus != OK) {
579 ALOGE("Could not write session ID ('%s') to socket: %s",
580 base::HexString(sessionId.data(), sessionId.size()).c_str(),
581 statusToString(sendSessionIdStatus).c_str());
582 return sendSessionIdStatus;
583 }
584 }
585
Steven Moreland4198a122021-08-03 17:37:58 -0700586 LOG_RPC_DETAIL("Socket at client: header sent");
587
588 if (incoming) {
589 return addIncomingConnection(std::move(server));
590 } else {
591 return addOutgoingConnection(std::move(server), true /*init*/);
592 }
593}
594
Steven Moreland2372f9d2021-08-05 15:42:01 -0700595status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000596 std::mutex mutex;
597 std::condition_variable joinCv;
598 std::unique_lock<std::mutex> lock(mutex);
599 std::thread thread;
600 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
601 bool ownershipTransferred = false;
602 thread = std::thread([&]() {
603 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700604 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000605 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
606 sp<RpcSession> session = thiz;
607 session->preJoinThreadOwnership(std::move(thread));
608
609 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700610 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000611
612 ownershipTransferred = true;
613 threadLock.unlock();
614 joinCv.notify_one();
615 // do not use & vars below
616
617 RpcSession::join(std::move(session), std::move(setupResult));
618 });
619 joinCv.wait(lock, [&] { return ownershipTransferred; });
620 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700621 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000622}
623
Yifan Hong832521e2021-08-05 14:55:40 -0700624status_t RpcSession::initShutdownTrigger() {
625 // first client connection added, but setForServer not called, so
626 // initializaing for a client.
627 if (mShutdownTrigger == nullptr) {
628 mShutdownTrigger = FdTrigger::make();
629 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
630 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
631 }
632 return OK;
633}
634
Steven Moreland2372f9d2021-08-05 15:42:01 -0700635status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000636 sp<RpcConnection> connection = sp<RpcConnection>::make();
637 {
638 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700639 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000640 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000641 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000642 }
643
Steven Morelandb86e26b2021-06-12 00:35:58 +0000644 status_t status = OK;
645 if (init) {
646 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
647 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000648
649 {
650 std::lock_guard<std::mutex> _l(mMutex);
651 connection->exclusiveTid = std::nullopt;
652 }
653
Steven Moreland2372f9d2021-08-05 15:42:01 -0700654 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000655}
656
Steven Morelanda8b44292021-06-08 01:27:53 +0000657bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland826367f2021-09-10 14:05:31 -0700658 const std::vector<uint8_t>& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000659 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
660 LOG_ALWAYS_FATAL_IF(server == nullptr);
661 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
662 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000663 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000664
665 mShutdownTrigger = FdTrigger::make();
666 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000667
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000668 mId = sessionId;
669 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000670 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000671 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000672}
673
Yifan Hong702115c2021-06-24 15:39:18 -0700674sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
675 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000676 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700677
Steven Moreland132d5bf2021-08-03 16:13:24 -0700678 if (mIncomingConnections.size() >= mMaxThreads) {
679 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
680 mIncomingConnections.size(), mMaxThreads);
681 return nullptr;
682 }
683
Steven Morelanddd67b942021-07-23 17:15:41 -0700684 // Don't accept any more connections, some have shutdown. Usually this
685 // happens when new connections are still being established as part of a
686 // very short-lived session which shuts down after it already started
687 // accepting new connections.
688 if (mIncomingConnections.size() < mMaxIncomingConnections) {
689 return nullptr;
690 }
691
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000692 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700693 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000694 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700695
Steven Moreland19fc9f72021-06-10 03:57:30 +0000696 mIncomingConnections.push_back(session);
Steven Morelanddd67b942021-07-23 17:15:41 -0700697 mMaxIncomingConnections = mIncomingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000698
699 return session;
700}
701
Steven Moreland19fc9f72021-06-10 03:57:30 +0000702bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700703 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000704 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
705 it != mIncomingConnections.end()) {
706 mIncomingConnections.erase(it);
707 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000708 sp<EventListener> listener = mEventListener.promote();
709 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700710 _l.unlock();
711 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000712 }
Steven Morelandee78e762021-05-05 21:12:51 +0000713 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000714 return true;
715 }
716 return false;
717}
718
Yifan Hongecf937d2021-08-11 17:29:28 -0700719std::string RpcSession::getCertificate(CertificateFormat format) {
720 return mCtx->getCertificate(format);
721}
722
Steven Moreland195edb82021-06-08 02:44:39 +0000723status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
724 ExclusiveConnection* connection) {
725 connection->mSession = session;
726 connection->mConnection = nullptr;
727 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000728
Steven Moreland195edb82021-06-08 02:44:39 +0000729 pid_t tid = gettid();
730 std::unique_lock<std::mutex> _l(session->mMutex);
731
732 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000733 while (true) {
734 sp<RpcConnection> exclusive;
735 sp<RpcConnection> available;
736
737 // CHECK FOR DEDICATED CLIENT SOCKET
738 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000739 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000740 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
741 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000742
743 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000744 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000745 //
746 // Imagine we have more than one thread in play, and a single thread
747 // sends a synchronous, then an asynchronous command. Imagine the
748 // asynchronous command is sent on the first client connection. Then, if
749 // we naively send a synchronous command to that same connection, the
750 // thread on the far side might be busy processing the asynchronous
751 // command. So, we move to considering the second available thread
752 // for subsequent calls.
753 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000754 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
755 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000756 }
757
Steven Morelandc7d40132021-06-10 03:42:11 +0000758 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000759 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000760 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000761 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000762 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
763 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000764
765 // asynchronous calls cannot be nested, we currently allow ref count
766 // calls to be nested (so that you can use this without having extra
767 // threads). Note 'drainCommands' is used so that these ref counts can't
768 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000769 if (exclusiveIncoming != nullptr) {
770 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000771 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000772 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000773 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
774 // prefer available socket, but if we don't have one, don't
775 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000776 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000777 }
778 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000779 }
780
Steven Moreland85e067b2021-05-26 17:43:53 +0000781 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000782 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000783 connection->mConnection = exclusive;
784 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000785 break;
786 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000787 connection->mConnection = available;
788 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000789 break;
790 }
791
Steven Moreland19fc9f72021-06-10 03:57:30 +0000792 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000793 ALOGE("Session has no client connections. This is required for an RPC server to make "
794 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
795 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000796 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000797 return WOULD_BLOCK;
798 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000799
Steven Moreland85e067b2021-05-26 17:43:53 +0000800 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000801 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000802 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000803 }
Steven Moreland195edb82021-06-08 02:44:39 +0000804 session->mWaitingThreads--;
805
806 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000807}
808
809void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
810 sp<RpcConnection>* available,
811 std::vector<sp<RpcConnection>>& sockets,
812 size_t socketsIndexHint) {
813 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
814 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
815
816 if (*exclusive != nullptr) return; // consistent with break below
817
818 for (size_t i = 0; i < sockets.size(); i++) {
819 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
820
Steven Moreland85e067b2021-05-26 17:43:53 +0000821 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000822 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
823 *available = socket;
824 continue;
825 }
826
Steven Moreland85e067b2021-05-26 17:43:53 +0000827 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000828 // (nested transactions)
829 if (exclusive && socket->exclusiveTid == tid) {
830 *exclusive = socket;
831 break; // consistent with return above
832 }
833 }
834}
835
836RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000837 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000838 // is using this fd, and it retains the right to it. So, we don't give up
839 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000840 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000841 std::unique_lock<std::mutex> _l(mSession->mMutex);
842 mConnection->exclusiveTid = std::nullopt;
843 if (mSession->mWaitingThreads > 0) {
844 _l.unlock();
845 mSession->mAvailableConnectionCv.notify_one();
846 }
847 }
848}
849
850} // namespace android