blob: 9395b505e1ddd9472c573876f442d904b2b39a1d [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 Hongfdd9f692021-09-09 15:12:52 -070068 return make(RpcTransportCtxFactoryRaw::make());
Yifan Hongecf937d2021-08-11 17:29:28 -070069}
70
Yifan Hongfdd9f692021-09-09 15:12:52 -070071sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
Yifan Hongecf937d2021-08-11 17:29:28 -070072 auto ctx = rpcTransportCtxFactory->newClientCtx();
73 if (ctx == nullptr) return nullptr;
Yifan Hongecf937d2021-08-11 17:29:28 -070074 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000075}
76
Steven Moreland103424e2021-06-02 18:16:19 +000077void RpcSession::setMaxThreads(size_t threads) {
78 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000079 LOG_ALWAYS_FATAL_IF(!mOutgoingConnections.empty() || !mIncomingConnections.empty(),
Steven Moreland103424e2021-06-02 18:16:19 +000080 "Must set max threads before setting up connections, but has %zu client(s) "
81 "and %zu server(s)",
Steven Moreland19fc9f72021-06-10 03:57:30 +000082 mOutgoingConnections.size(), mIncomingConnections.size());
Steven Moreland103424e2021-06-02 18:16:19 +000083 mMaxThreads = threads;
84}
85
86size_t RpcSession::getMaxThreads() {
87 std::lock_guard<std::mutex> _l(mMutex);
88 return mMaxThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000089}
90
Steven Morelandbf57bce2021-07-26 15:26:12 -070091bool RpcSession::setProtocolVersion(uint32_t version) {
92 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
93 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
94 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
95 "is %u).",
96 version, RPC_WIRE_PROTOCOL_VERSION);
97 return false;
98 }
99
100 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -0700101 if (mProtocolVersion && version > *mProtocolVersion) {
102 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
103 *mProtocolVersion, version);
104 return false;
105 }
106
Steven Morelandbf57bce2021-07-26 15:26:12 -0700107 mProtocolVersion = version;
108 return true;
109}
110
111std::optional<uint32_t> RpcSession::getProtocolVersion() {
112 std::lock_guard<std::mutex> _l(mMutex);
113 return mProtocolVersion;
114}
115
Steven Moreland2372f9d2021-08-05 15:42:01 -0700116status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000117 return setupSocketClient(UnixSocketAddress(path));
118}
119
Steven Moreland2372f9d2021-08-05 15:42:01 -0700120status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000121 return setupSocketClient(VsockSocketAddress(cid, port));
122}
123
Steven Moreland2372f9d2021-08-05 15:42:01 -0700124status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000125 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700126 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000127 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
128 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700129 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000130 }
131 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 -0700132 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000133}
134
Steven Moreland2372f9d2021-08-05 15:42:01 -0700135status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
Steven Moreland826367f2021-09-10 14:05:31 -0700136 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700137 // std::move'd from fd becomes -1 (!ok())
138 if (!fd.ok()) {
139 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700140 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700141 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700142 if (auto res = setNonBlocking(fd); !res.ok()) {
143 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
144 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
145 }
Steven Moreland4198a122021-08-03 17:37:58 -0700146 return initAndAddConnection(std::move(fd), sessionId, incoming);
147 });
148}
149
Steven Moreland2372f9d2021-08-05 15:42:01 -0700150status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700151 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700152 if (auto status = initShutdownTrigger(); status != OK) return status;
153
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000154 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
155
156 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700157 int savedErrno = errno;
158 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
159 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000160 }
161
Yifan Hongecf937d2021-08-11 17:29:28 -0700162 auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700163 if (server == nullptr) {
164 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700165 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700166 }
167 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000168}
169
170sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000171 ExclusiveConnection connection;
172 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
173 ConnectionUse::CLIENT, &connection);
174 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000175 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000176}
177
Steven Moreland1be91352021-05-11 22:12:15 +0000178status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000179 ExclusiveConnection connection;
180 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
181 ConnectionUse::CLIENT, &connection);
182 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000183 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000184}
185
Steven Morelandc9d7b532021-06-04 20:57:41 +0000186bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000187 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000188 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000189
190 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000191
Steven Morelandc9d7b532021-06-04 20:57:41 +0000192 if (wait) {
193 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
194 mShutdownListener->waitForShutdown(_l);
Steven Morelanddd67b942021-07-23 17:15:41 -0700195
Steven Morelandc9d7b532021-06-04 20:57:41 +0000196 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
197 }
198
199 _l.unlock();
200 mState->clear();
201
Steven Moreland659416d2021-05-11 00:47:50 +0000202 return true;
203}
204
Steven Morelandf5174272021-05-25 00:39:28 +0000205status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000206 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000207 ExclusiveConnection connection;
208 status_t status =
209 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
210 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
211 : ConnectionUse::CLIENT,
212 &connection);
213 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000214 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000215 sp<RpcSession>::fromExisting(this), reply, flags);
216}
217
Steven Moreland5623d1a2021-09-10 15:45:34 -0700218status_t RpcSession::sendDecStrong(uint64_t address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000219 ExclusiveConnection connection;
220 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
221 ConnectionUse::CLIENT_REFCOUNT, &connection);
222 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000223 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000224}
225
226status_t RpcSession::readId() {
227 {
228 std::lock_guard<std::mutex> _l(mMutex);
229 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
230 }
231
Steven Moreland195edb82021-06-08 02:44:39 +0000232 ExclusiveConnection connection;
233 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
234 ConnectionUse::CLIENT, &connection);
235 if (status != OK) return status;
236
Steven Moreland826367f2021-09-10 14:05:31 -0700237 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000238 if (status != OK) return status;
239
Steven Moreland826367f2021-09-10 14:05:31 -0700240 LOG_RPC_DETAIL("RpcSession %p has id %s", this,
241 base::HexString(mId.data(), mId.size()).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 Moreland826367f2021-09-10 14:05:31 -0700400status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
401 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 Moreland826367f2021-09-10 14:05:31 -0700410 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000411
Steven Morelandbf57bce2021-07-26 15:26:12 -0700412 {
413 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700414 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
415 ConnectionUse::CLIENT, &connection);
416 status != OK)
417 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700418
419 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700420 if (status_t status =
421 state()->readNewSessionResponse(connection.get(),
422 sp<RpcSession>::fromExisting(this), &version);
423 status != OK)
424 return status;
425 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700426 }
427
Steven Morelanda5036f02021-06-08 02:26:57 +0000428 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000429 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000430 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000431 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700432 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000433 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700434 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000435 }
436
437 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700438 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000439 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700440 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000441 }
442
Steven Morelanda5036f02021-06-08 02:26:57 +0000443 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000444 // instead of all at once - the other side should be responsible for setting
445 // up additional connections. We need to create at least one (unless 0 are
446 // requested to be set) in order to allow the other side to reliably make
447 // any requests at all.
448
Steven Moreland4198a122021-08-03 17:37:58 -0700449 // we've already setup one client
450 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700451 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700452 }
453
Steven Moreland103424e2021-06-02 18:16:19 +0000454 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700455 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000456 }
457
Steven Moreland2372f9d2021-08-05 15:42:01 -0700458 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000459}
460
Steven Moreland2372f9d2021-08-05 15:42:01 -0700461status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700462 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700463 return setupOneSocketConnection(addr, sessionId, incoming);
464 });
465}
466
Steven Moreland2372f9d2021-08-05 15:42:01 -0700467status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700468 const std::vector<uint8_t>& sessionId,
469 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000470 for (size_t tries = 0; tries < 5; tries++) {
471 if (tries > 0) usleep(10000);
472
Yifan Hongb675ffe2021-08-05 16:37:17 -0700473 unique_fd serverFd(TEMP_FAILURE_RETRY(
474 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000475 if (serverFd == -1) {
476 int savedErrno = errno;
477 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
478 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700479 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000480 }
481
482 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700483 int connErrno = errno;
484 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
485 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
486 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
487 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
488 if (pollStatus != OK) {
489 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
490 statusToString(pollStatus).c_str());
491 return pollStatus;
492 }
493 // Set connErrno to the errno that connect() would have set if the fd were blocking.
494 socklen_t connErrnoLen = sizeof(connErrno);
495 int ret =
496 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
497 if (ret == -1) {
498 int savedErrno = errno;
499 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
500 "(Original error from connect() is: %s)",
501 strerror(savedErrno), strerror(connErrno));
502 return -savedErrno;
503 }
504 // Retrieved the real connErrno as if connect() was called with a blocking socket
505 // fd. Continue checking connErrno.
506 }
507 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000508 ALOGW("Connection reset on %s", addr.toString().c_str());
509 continue;
510 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700511 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
512 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700513 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700514 strerror(connErrno));
515 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700516 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000517 }
Yifan Hong702115c2021-06-24 15:39:18 -0700518 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
519
Steven Moreland4198a122021-08-03 17:37:58 -0700520 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000521 }
522
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000523 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700524 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000525}
526
Steven Moreland826367f2021-09-10 14:05:31 -0700527status_t RpcSession::initAndAddConnection(unique_fd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700528 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700529 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700530 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700531 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700532 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700533 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700534 }
535
536 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
537
Steven Moreland826367f2021-09-10 14:05:31 -0700538 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
539 ALOGE("Session ID too big %zu", sessionId.size());
540 return BAD_VALUE;
541 }
542
Steven Moreland4198a122021-08-03 17:37:58 -0700543 RpcConnectionHeader header{
544 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
545 .options = 0,
Steven Moreland826367f2021-09-10 14:05:31 -0700546 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700547 };
Steven Moreland4198a122021-08-03 17:37:58 -0700548
Steven Moreland826367f2021-09-10 14:05:31 -0700549 if (incoming) {
550 header.options |= RPC_CONNECTION_OPTION_INCOMING;
551 }
Steven Moreland4198a122021-08-03 17:37:58 -0700552
Yifan Hong8c950422021-08-05 17:13:55 -0700553 auto sendHeaderStatus =
554 server->interruptableWriteFully(mShutdownTrigger.get(), &header, sizeof(header));
555 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700556 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700557 statusToString(sendHeaderStatus).c_str());
558 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700559 }
560
Steven Moreland826367f2021-09-10 14:05:31 -0700561 if (sessionId.size() > 0) {
562 auto sendSessionIdStatus =
563 server->interruptableWriteFully(mShutdownTrigger.get(), sessionId.data(),
564 sessionId.size());
565 if (sendSessionIdStatus != OK) {
566 ALOGE("Could not write session ID ('%s') to socket: %s",
567 base::HexString(sessionId.data(), sessionId.size()).c_str(),
568 statusToString(sendSessionIdStatus).c_str());
569 return sendSessionIdStatus;
570 }
571 }
572
Steven Moreland4198a122021-08-03 17:37:58 -0700573 LOG_RPC_DETAIL("Socket at client: header sent");
574
575 if (incoming) {
576 return addIncomingConnection(std::move(server));
577 } else {
578 return addOutgoingConnection(std::move(server), true /*init*/);
579 }
580}
581
Steven Moreland2372f9d2021-08-05 15:42:01 -0700582status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000583 std::mutex mutex;
584 std::condition_variable joinCv;
585 std::unique_lock<std::mutex> lock(mutex);
586 std::thread thread;
587 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
588 bool ownershipTransferred = false;
589 thread = std::thread([&]() {
590 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700591 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000592 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
593 sp<RpcSession> session = thiz;
594 session->preJoinThreadOwnership(std::move(thread));
595
596 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700597 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000598
599 ownershipTransferred = true;
600 threadLock.unlock();
601 joinCv.notify_one();
602 // do not use & vars below
603
604 RpcSession::join(std::move(session), std::move(setupResult));
605 });
606 joinCv.wait(lock, [&] { return ownershipTransferred; });
607 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700608 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000609}
610
Yifan Hong832521e2021-08-05 14:55:40 -0700611status_t RpcSession::initShutdownTrigger() {
612 // first client connection added, but setForServer not called, so
613 // initializaing for a client.
614 if (mShutdownTrigger == nullptr) {
615 mShutdownTrigger = FdTrigger::make();
616 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
617 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
618 }
619 return OK;
620}
621
Steven Moreland2372f9d2021-08-05 15:42:01 -0700622status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000623 sp<RpcConnection> connection = sp<RpcConnection>::make();
624 {
625 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700626 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000627 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000628 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000629 }
630
Steven Morelandb86e26b2021-06-12 00:35:58 +0000631 status_t status = OK;
632 if (init) {
633 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
634 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000635
636 {
637 std::lock_guard<std::mutex> _l(mMutex);
638 connection->exclusiveTid = std::nullopt;
639 }
640
Steven Moreland2372f9d2021-08-05 15:42:01 -0700641 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000642}
643
Steven Morelanda8b44292021-06-08 01:27:53 +0000644bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland826367f2021-09-10 14:05:31 -0700645 const std::vector<uint8_t>& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000646 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
647 LOG_ALWAYS_FATAL_IF(server == nullptr);
648 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
649 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000650 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000651
652 mShutdownTrigger = FdTrigger::make();
653 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000654
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000655 mId = sessionId;
656 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000657 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000658 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000659}
660
Yifan Hong702115c2021-06-24 15:39:18 -0700661sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
662 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000663 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700664
Steven Moreland132d5bf2021-08-03 16:13:24 -0700665 if (mIncomingConnections.size() >= mMaxThreads) {
666 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
667 mIncomingConnections.size(), mMaxThreads);
668 return nullptr;
669 }
670
Steven Morelanddd67b942021-07-23 17:15:41 -0700671 // Don't accept any more connections, some have shutdown. Usually this
672 // happens when new connections are still being established as part of a
673 // very short-lived session which shuts down after it already started
674 // accepting new connections.
675 if (mIncomingConnections.size() < mMaxIncomingConnections) {
676 return nullptr;
677 }
678
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000679 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700680 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000681 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700682
Steven Moreland19fc9f72021-06-10 03:57:30 +0000683 mIncomingConnections.push_back(session);
Steven Morelanddd67b942021-07-23 17:15:41 -0700684 mMaxIncomingConnections = mIncomingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000685
686 return session;
687}
688
Steven Moreland19fc9f72021-06-10 03:57:30 +0000689bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700690 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000691 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
692 it != mIncomingConnections.end()) {
693 mIncomingConnections.erase(it);
694 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000695 sp<EventListener> listener = mEventListener.promote();
696 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700697 _l.unlock();
698 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000699 }
Steven Morelandee78e762021-05-05 21:12:51 +0000700 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000701 return true;
702 }
703 return false;
704}
705
Yifan Hong9734cfc2021-09-13 16:14:09 -0700706std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700707 return mCtx->getCertificate(format);
708}
709
Steven Moreland195edb82021-06-08 02:44:39 +0000710status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
711 ExclusiveConnection* connection) {
712 connection->mSession = session;
713 connection->mConnection = nullptr;
714 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000715
Steven Moreland195edb82021-06-08 02:44:39 +0000716 pid_t tid = gettid();
717 std::unique_lock<std::mutex> _l(session->mMutex);
718
719 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000720 while (true) {
721 sp<RpcConnection> exclusive;
722 sp<RpcConnection> available;
723
724 // CHECK FOR DEDICATED CLIENT SOCKET
725 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000726 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000727 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
728 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000729
730 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000731 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000732 //
733 // Imagine we have more than one thread in play, and a single thread
734 // sends a synchronous, then an asynchronous command. Imagine the
735 // asynchronous command is sent on the first client connection. Then, if
736 // we naively send a synchronous command to that same connection, the
737 // thread on the far side might be busy processing the asynchronous
738 // command. So, we move to considering the second available thread
739 // for subsequent calls.
740 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000741 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
742 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000743 }
744
Steven Morelandc7d40132021-06-10 03:42:11 +0000745 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000746 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000747 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000748 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000749 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
750 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000751
752 // asynchronous calls cannot be nested, we currently allow ref count
753 // calls to be nested (so that you can use this without having extra
754 // threads). Note 'drainCommands' is used so that these ref counts can't
755 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000756 if (exclusiveIncoming != nullptr) {
757 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000758 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000759 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000760 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
761 // prefer available socket, but if we don't have one, don't
762 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000763 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000764 }
765 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000766 }
767
Steven Moreland85e067b2021-05-26 17:43:53 +0000768 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000769 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000770 connection->mConnection = exclusive;
771 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000772 break;
773 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000774 connection->mConnection = available;
775 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000776 break;
777 }
778
Steven Moreland19fc9f72021-06-10 03:57:30 +0000779 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000780 ALOGE("Session has no client connections. This is required for an RPC server to make "
781 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
782 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000783 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000784 return WOULD_BLOCK;
785 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000786
Steven Moreland85e067b2021-05-26 17:43:53 +0000787 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000788 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000789 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000790 }
Steven Moreland195edb82021-06-08 02:44:39 +0000791 session->mWaitingThreads--;
792
793 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000794}
795
796void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
797 sp<RpcConnection>* available,
798 std::vector<sp<RpcConnection>>& sockets,
799 size_t socketsIndexHint) {
800 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
801 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
802
803 if (*exclusive != nullptr) return; // consistent with break below
804
805 for (size_t i = 0; i < sockets.size(); i++) {
806 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
807
Steven Moreland85e067b2021-05-26 17:43:53 +0000808 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000809 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
810 *available = socket;
811 continue;
812 }
813
Steven Moreland85e067b2021-05-26 17:43:53 +0000814 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000815 // (nested transactions)
816 if (exclusive && socket->exclusiveTid == tid) {
817 *exclusive = socket;
818 break; // consistent with return above
819 }
820 }
821}
822
823RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000824 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000825 // is using this fd, and it retains the right to it. So, we don't give up
826 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000827 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000828 std::unique_lock<std::mutex> _l(mSession->mMutex);
829 mConnection->exclusiveTid = std::nullopt;
830 if (mSession->mWaitingThreads > 0) {
831 _l.unlock();
832 mSession->mAvailableConnectionCv.notify_one();
833 }
834 }
835}
836
837} // namespace android