blob: a99e06160f078b302a65a5c6346c83763b28127b [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");
205 mShutdownListener->waitForShutdown(_l);
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
229status_t RpcSession::sendDecStrong(const RpcAddress& 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;
259 mShutdown = true;
260}
261
Steven Moreland19fc9f72021-06-10 03:57:30 +0000262void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000263 mCv.notify_all();
264}
265
266void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
267 while (!mShutdown) {
268 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
269 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
270 }
271 }
272}
273
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000274void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000275 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000276
Steven Morelanda63ff932021-05-12 00:03:15 +0000277 {
278 std::lock_guard<std::mutex> _l(mMutex);
279 mThreads[thread.get_id()] = std::move(thread);
280 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000281}
Steven Morelanda63ff932021-05-12 00:03:15 +0000282
Yifan Hong702115c2021-06-24 15:39:18 -0700283RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
284 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000285 // must be registered to allow arbitrary client code executing commands to
286 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700287 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000288
Steven Morelanddd67b942021-07-23 17:15:41 -0700289 status_t status;
290
291 if (connection == nullptr) {
292 status = DEAD_OBJECT;
293 } else {
294 status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
295 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000296
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000297 return PreJoinSetupResult{
298 .connection = std::move(connection),
299 .status = status,
300 };
301}
302
Yifan Hong194acf22021-06-29 18:44:56 -0700303namespace {
304// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
305// Android Runtime doesn't exist, no-op.
306class JavaThreadAttacher {
307public:
308 JavaThreadAttacher() {
309 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
310 // libbinder.
311 auto vm = getJavaVM();
312 if (vm == nullptr) return;
313
314 char threadName[16];
315 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
316 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
317 memcpy(threadName, defaultThreadName,
318 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
319 }
320 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
321 JavaVMAttachArgs args;
322 args.version = JNI_VERSION_1_2;
323 args.name = threadName;
324 args.group = nullptr;
325 JNIEnv* env;
326
327 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
328 "Cannot attach thread %s to JVM", threadName);
329 mAttached = true;
330 }
331 ~JavaThreadAttacher() {
332 if (!mAttached) return;
333 auto vm = getJavaVM();
334 LOG_ALWAYS_FATAL_IF(vm == nullptr,
335 "Unable to detach thread. No JavaVM, but it was present before!");
336
337 LOG_RPC_DETAIL("Detaching current thread from JVM");
338 if (vm->DetachCurrentThread() != JNI_OK) {
339 mAttached = false;
340 } else {
341 ALOGW("Unable to detach current thread from JVM");
342 }
343 }
344
345private:
346 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
347 bool mAttached = false;
348
349 static JavaVM* getJavaVM() {
350 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
351 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
352 if (fn == nullptr) return nullptr;
353 return fn();
354 }
355};
356} // namespace
357
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000358void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
359 sp<RpcConnection>& connection = setupResult.connection;
360
361 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700362 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hong194acf22021-06-29 18:44:56 -0700363 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000364 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000365 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000366 RpcState::CommandType::ANY);
367 if (status != OK) {
368 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
369 statusToString(status).c_str());
370 break;
371 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000372 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000373 } else {
374 ALOGE("Connection failed to init, closing with status %s",
375 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000376 }
377
Steven Moreland659416d2021-05-11 00:47:50 +0000378 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000379 {
Steven Moreland659416d2021-05-11 00:47:50 +0000380 std::lock_guard<std::mutex> _l(session->mMutex);
381 auto it = session->mThreads.find(std::this_thread::get_id());
382 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000383 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000384 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000385
Steven Moreland659416d2021-05-11 00:47:50 +0000386 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000387 }
388
Steven Morelanddd67b942021-07-23 17:15:41 -0700389 // done after all cleanup, since session shutdown progresses via callbacks here
390 if (connection != nullptr) {
391 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
392 "bad state: connection object guaranteed to be in list");
393 }
394
Steven Moreland659416d2021-05-11 00:47:50 +0000395 session = nullptr;
396
397 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000398 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000399 }
400}
401
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000402sp<RpcServer> RpcSession::server() {
403 RpcServer* unsafeServer = mForServer.unsafe_get();
404 sp<RpcServer> server = mForServer.promote();
405
406 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
407 "wp<> is to avoid strong cycle only");
408 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409}
410
Steven Moreland826367f2021-09-10 14:05:31 -0700411status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
412 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000413 {
414 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000415 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000416 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000417 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000418 }
Yifan Hong832521e2021-08-05 14:55:40 -0700419 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000420
Steven Moreland826367f2021-09-10 14:05:31 -0700421 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000422
Steven Morelandbf57bce2021-07-26 15:26:12 -0700423 {
424 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700425 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
426 ConnectionUse::CLIENT, &connection);
427 status != OK)
428 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700429
430 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700431 if (status_t status =
432 state()->readNewSessionResponse(connection.get(),
433 sp<RpcSession>::fromExisting(this), &version);
434 status != OK)
435 return status;
436 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700437 }
438
Steven Morelanda5036f02021-06-08 02:26:57 +0000439 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000440 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000441 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000442 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700443 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000444 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700445 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000446 }
447
448 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700449 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000450 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700451 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000452 }
453
Steven Morelanda5036f02021-06-08 02:26:57 +0000454 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000455 // instead of all at once - the other side should be responsible for setting
456 // up additional connections. We need to create at least one (unless 0 are
457 // requested to be set) in order to allow the other side to reliably make
458 // any requests at all.
459
Steven Moreland4198a122021-08-03 17:37:58 -0700460 // we've already setup one client
461 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700462 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700463 }
464
Steven Moreland103424e2021-06-02 18:16:19 +0000465 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700466 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000467 }
468
Steven Moreland2372f9d2021-08-05 15:42:01 -0700469 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000470}
471
Steven Moreland2372f9d2021-08-05 15:42:01 -0700472status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700473 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700474 return setupOneSocketConnection(addr, sessionId, incoming);
475 });
476}
477
Steven Moreland2372f9d2021-08-05 15:42:01 -0700478status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700479 const std::vector<uint8_t>& sessionId,
480 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000481 for (size_t tries = 0; tries < 5; tries++) {
482 if (tries > 0) usleep(10000);
483
Yifan Hongb675ffe2021-08-05 16:37:17 -0700484 unique_fd serverFd(TEMP_FAILURE_RETRY(
485 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000486 if (serverFd == -1) {
487 int savedErrno = errno;
488 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
489 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700490 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000491 }
492
493 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700494 int connErrno = errno;
495 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
496 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
497 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
498 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
499 if (pollStatus != OK) {
500 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
501 statusToString(pollStatus).c_str());
502 return pollStatus;
503 }
504 // Set connErrno to the errno that connect() would have set if the fd were blocking.
505 socklen_t connErrnoLen = sizeof(connErrno);
506 int ret =
507 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
508 if (ret == -1) {
509 int savedErrno = errno;
510 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
511 "(Original error from connect() is: %s)",
512 strerror(savedErrno), strerror(connErrno));
513 return -savedErrno;
514 }
515 // Retrieved the real connErrno as if connect() was called with a blocking socket
516 // fd. Continue checking connErrno.
517 }
518 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000519 ALOGW("Connection reset on %s", addr.toString().c_str());
520 continue;
521 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700522 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
523 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700524 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700525 strerror(connErrno));
526 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700527 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000528 }
Yifan Hong702115c2021-06-24 15:39:18 -0700529 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
530
Steven Moreland4198a122021-08-03 17:37:58 -0700531 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000532 }
533
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000534 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700535 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000536}
537
Steven Moreland826367f2021-09-10 14:05:31 -0700538status_t RpcSession::initAndAddConnection(unique_fd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700539 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700540 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700541 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700542 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700543 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700544 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700545 }
546
547 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
548
Steven Moreland826367f2021-09-10 14:05:31 -0700549 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
550 ALOGE("Session ID too big %zu", sessionId.size());
551 return BAD_VALUE;
552 }
553
Steven Moreland4198a122021-08-03 17:37:58 -0700554 RpcConnectionHeader header{
555 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
556 .options = 0,
Steven Moreland826367f2021-09-10 14:05:31 -0700557 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700558 };
Steven Moreland4198a122021-08-03 17:37:58 -0700559
Steven Moreland826367f2021-09-10 14:05:31 -0700560 if (incoming) {
561 header.options |= RPC_CONNECTION_OPTION_INCOMING;
562 }
Steven Moreland4198a122021-08-03 17:37:58 -0700563
Yifan Hong8c950422021-08-05 17:13:55 -0700564 auto sendHeaderStatus =
565 server->interruptableWriteFully(mShutdownTrigger.get(), &header, sizeof(header));
566 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700567 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700568 statusToString(sendHeaderStatus).c_str());
569 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700570 }
571
Steven Moreland826367f2021-09-10 14:05:31 -0700572 if (sessionId.size() > 0) {
573 auto sendSessionIdStatus =
574 server->interruptableWriteFully(mShutdownTrigger.get(), sessionId.data(),
575 sessionId.size());
576 if (sendSessionIdStatus != OK) {
577 ALOGE("Could not write session ID ('%s') to socket: %s",
578 base::HexString(sessionId.data(), sessionId.size()).c_str(),
579 statusToString(sendSessionIdStatus).c_str());
580 return sendSessionIdStatus;
581 }
582 }
583
Steven Moreland4198a122021-08-03 17:37:58 -0700584 LOG_RPC_DETAIL("Socket at client: header sent");
585
586 if (incoming) {
587 return addIncomingConnection(std::move(server));
588 } else {
589 return addOutgoingConnection(std::move(server), true /*init*/);
590 }
591}
592
Steven Moreland2372f9d2021-08-05 15:42:01 -0700593status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000594 std::mutex mutex;
595 std::condition_variable joinCv;
596 std::unique_lock<std::mutex> lock(mutex);
597 std::thread thread;
598 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
599 bool ownershipTransferred = false;
600 thread = std::thread([&]() {
601 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700602 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000603 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
604 sp<RpcSession> session = thiz;
605 session->preJoinThreadOwnership(std::move(thread));
606
607 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700608 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000609
610 ownershipTransferred = true;
611 threadLock.unlock();
612 joinCv.notify_one();
613 // do not use & vars below
614
615 RpcSession::join(std::move(session), std::move(setupResult));
616 });
617 joinCv.wait(lock, [&] { return ownershipTransferred; });
618 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700619 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000620}
621
Yifan Hong832521e2021-08-05 14:55:40 -0700622status_t RpcSession::initShutdownTrigger() {
623 // first client connection added, but setForServer not called, so
624 // initializaing for a client.
625 if (mShutdownTrigger == nullptr) {
626 mShutdownTrigger = FdTrigger::make();
627 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
628 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
629 }
630 return OK;
631}
632
Steven Moreland2372f9d2021-08-05 15:42:01 -0700633status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000634 sp<RpcConnection> connection = sp<RpcConnection>::make();
635 {
636 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700637 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000638 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000639 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000640 }
641
Steven Morelandb86e26b2021-06-12 00:35:58 +0000642 status_t status = OK;
643 if (init) {
644 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
645 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000646
647 {
648 std::lock_guard<std::mutex> _l(mMutex);
649 connection->exclusiveTid = std::nullopt;
650 }
651
Steven Moreland2372f9d2021-08-05 15:42:01 -0700652 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000653}
654
Steven Morelanda8b44292021-06-08 01:27:53 +0000655bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland826367f2021-09-10 14:05:31 -0700656 const std::vector<uint8_t>& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000657 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
658 LOG_ALWAYS_FATAL_IF(server == nullptr);
659 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
660 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000661 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000662
663 mShutdownTrigger = FdTrigger::make();
664 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000665
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000666 mId = sessionId;
667 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000668 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000669 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000670}
671
Yifan Hong702115c2021-06-24 15:39:18 -0700672sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
673 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000674 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700675
Steven Moreland132d5bf2021-08-03 16:13:24 -0700676 if (mIncomingConnections.size() >= mMaxThreads) {
677 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
678 mIncomingConnections.size(), mMaxThreads);
679 return nullptr;
680 }
681
Steven Morelanddd67b942021-07-23 17:15:41 -0700682 // Don't accept any more connections, some have shutdown. Usually this
683 // happens when new connections are still being established as part of a
684 // very short-lived session which shuts down after it already started
685 // accepting new connections.
686 if (mIncomingConnections.size() < mMaxIncomingConnections) {
687 return nullptr;
688 }
689
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000690 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700691 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000692 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700693
Steven Moreland19fc9f72021-06-10 03:57:30 +0000694 mIncomingConnections.push_back(session);
Steven Morelanddd67b942021-07-23 17:15:41 -0700695 mMaxIncomingConnections = mIncomingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000696
697 return session;
698}
699
Steven Moreland19fc9f72021-06-10 03:57:30 +0000700bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700701 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000702 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
703 it != mIncomingConnections.end()) {
704 mIncomingConnections.erase(it);
705 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000706 sp<EventListener> listener = mEventListener.promote();
707 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700708 _l.unlock();
709 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000710 }
Steven Morelandee78e762021-05-05 21:12:51 +0000711 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000712 return true;
713 }
714 return false;
715}
716
Yifan Hongecf937d2021-08-11 17:29:28 -0700717std::string RpcSession::getCertificate(CertificateFormat format) {
718 return mCtx->getCertificate(format);
719}
720
Steven Moreland195edb82021-06-08 02:44:39 +0000721status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
722 ExclusiveConnection* connection) {
723 connection->mSession = session;
724 connection->mConnection = nullptr;
725 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000726
Steven Moreland195edb82021-06-08 02:44:39 +0000727 pid_t tid = gettid();
728 std::unique_lock<std::mutex> _l(session->mMutex);
729
730 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000731 while (true) {
732 sp<RpcConnection> exclusive;
733 sp<RpcConnection> available;
734
735 // CHECK FOR DEDICATED CLIENT SOCKET
736 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000737 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000738 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
739 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000740
741 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000742 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000743 //
744 // Imagine we have more than one thread in play, and a single thread
745 // sends a synchronous, then an asynchronous command. Imagine the
746 // asynchronous command is sent on the first client connection. Then, if
747 // we naively send a synchronous command to that same connection, the
748 // thread on the far side might be busy processing the asynchronous
749 // command. So, we move to considering the second available thread
750 // for subsequent calls.
751 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000752 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
753 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000754 }
755
Steven Morelandc7d40132021-06-10 03:42:11 +0000756 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000757 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000758 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000759 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000760 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
761 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000762
763 // asynchronous calls cannot be nested, we currently allow ref count
764 // calls to be nested (so that you can use this without having extra
765 // threads). Note 'drainCommands' is used so that these ref counts can't
766 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000767 if (exclusiveIncoming != nullptr) {
768 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000769 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000770 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000771 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
772 // prefer available socket, but if we don't have one, don't
773 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000774 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000775 }
776 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000777 }
778
Steven Moreland85e067b2021-05-26 17:43:53 +0000779 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000780 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000781 connection->mConnection = exclusive;
782 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000783 break;
784 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000785 connection->mConnection = available;
786 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000787 break;
788 }
789
Steven Moreland19fc9f72021-06-10 03:57:30 +0000790 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000791 ALOGE("Session has no client connections. This is required for an RPC server to make "
792 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
793 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000794 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000795 return WOULD_BLOCK;
796 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000797
Steven Moreland85e067b2021-05-26 17:43:53 +0000798 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000799 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000800 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000801 }
Steven Moreland195edb82021-06-08 02:44:39 +0000802 session->mWaitingThreads--;
803
804 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000805}
806
807void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
808 sp<RpcConnection>* available,
809 std::vector<sp<RpcConnection>>& sockets,
810 size_t socketsIndexHint) {
811 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
812 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
813
814 if (*exclusive != nullptr) return; // consistent with break below
815
816 for (size_t i = 0; i < sockets.size(); i++) {
817 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
818
Steven Moreland85e067b2021-05-26 17:43:53 +0000819 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000820 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
821 *available = socket;
822 continue;
823 }
824
Steven Moreland85e067b2021-05-26 17:43:53 +0000825 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000826 // (nested transactions)
827 if (exclusive && socket->exclusiveTid == tid) {
828 *exclusive = socket;
829 break; // consistent with return above
830 }
831 }
832}
833
834RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000835 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000836 // is using this fd, and it retains the right to it. So, we don't give up
837 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000838 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000839 std::unique_lock<std::mutex> _l(mSession->mMutex);
840 mConnection->exclusiveTid = std::nullopt;
841 if (mSession->mWaitingThreads > 0) {
842 _l.unlock();
843 mSession->mAvailableConnectionCv.notify_one();
844 }
845 }
846}
847
848} // namespace android