blob: fe12ed4de4d7baa537ac0fb21eb3842fcbb0f349 [file] [log] [blame]
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "RpcSession"
18
19#include <binder/RpcSession.h>
20
Yifan Hong194acf22021-06-29 18:44:56 -070021#include <dlfcn.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000022#include <inttypes.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000023#include <poll.h>
Yifan Hong194acf22021-06-29 18:44:56 -070024#include <pthread.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000025#include <unistd.h>
26
27#include <string_view>
28
Steven Moreland4ec3c432021-05-20 00:32:47 +000029#include <android-base/macros.h>
Yifan Hong194acf22021-06-29 18:44:56 -070030#include <android_runtime/vm.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000031#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000032#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070033#include <binder/RpcTransportRaw.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000034#include <binder/Stability.h>
Yifan Hong194acf22021-06-29 18:44:56 -070035#include <jni.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000036#include <utils/String8.h>
37
38#include "RpcSocketAddress.h"
39#include "RpcState.h"
40#include "RpcWireFormat.h"
41
42#ifdef __GLIBC__
43extern "C" pid_t gettid();
44#endif
45
46namespace android {
47
48using base::unique_fd;
49
Yifan Hong702115c2021-06-24 15:39:18 -070050RpcSession::RpcSession(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory)
51 : mRpcTransportCtxFactory(std::move(rpcTransportCtxFactory)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000052 LOG_RPC_DETAIL("RpcSession created %p", this);
53
54 mState = std::make_unique<RpcState>();
55}
56RpcSession::~RpcSession() {
57 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
58
59 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000060 LOG_ALWAYS_FATAL_IF(mIncomingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000061 "Should not be able to destroy a session with servers in use.");
62}
63
Yifan Hong702115c2021-06-24 15:39:18 -070064sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
65 // Default is without TLS.
66 if (rpcTransportCtxFactory == nullptr)
67 rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
68 return sp<RpcSession>::make(std::move(rpcTransportCtxFactory));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000069}
70
Steven Moreland103424e2021-06-02 18:16:19 +000071void RpcSession::setMaxThreads(size_t threads) {
72 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000073 LOG_ALWAYS_FATAL_IF(!mOutgoingConnections.empty() || !mIncomingConnections.empty(),
Steven Moreland103424e2021-06-02 18:16:19 +000074 "Must set max threads before setting up connections, but has %zu client(s) "
75 "and %zu server(s)",
Steven Moreland19fc9f72021-06-10 03:57:30 +000076 mOutgoingConnections.size(), mIncomingConnections.size());
Steven Moreland103424e2021-06-02 18:16:19 +000077 mMaxThreads = threads;
78}
79
80size_t RpcSession::getMaxThreads() {
81 std::lock_guard<std::mutex> _l(mMutex);
82 return mMaxThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000083}
84
Steven Morelandbf57bce2021-07-26 15:26:12 -070085bool RpcSession::setProtocolVersion(uint32_t version) {
86 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
87 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
88 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
89 "is %u).",
90 version, RPC_WIRE_PROTOCOL_VERSION);
91 return false;
92 }
93
94 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -070095 if (mProtocolVersion && version > *mProtocolVersion) {
96 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
97 *mProtocolVersion, version);
98 return false;
99 }
100
Steven Morelandbf57bce2021-07-26 15:26:12 -0700101 mProtocolVersion = version;
102 return true;
103}
104
105std::optional<uint32_t> RpcSession::getProtocolVersion() {
106 std::lock_guard<std::mutex> _l(mMutex);
107 return mProtocolVersion;
108}
109
Steven Moreland2372f9d2021-08-05 15:42:01 -0700110status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000111 return setupSocketClient(UnixSocketAddress(path));
112}
113
Steven Moreland2372f9d2021-08-05 15:42:01 -0700114status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000115 return setupSocketClient(VsockSocketAddress(cid, port));
116}
117
Steven Moreland2372f9d2021-08-05 15:42:01 -0700118status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000119 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700120 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000121 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
122 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700123 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000124 }
125 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 -0700126 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000127}
128
Steven Moreland2372f9d2021-08-05 15:42:01 -0700129status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
130 return setupClient([&](const RpcAddress& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700131 // std::move'd from fd becomes -1 (!ok())
132 if (!fd.ok()) {
133 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700134 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700135 }
136 return initAndAddConnection(std::move(fd), sessionId, incoming);
137 });
138}
139
Steven Moreland2372f9d2021-08-05 15:42:01 -0700140status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700141 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700142 if (auto status = initShutdownTrigger(); status != OK) return status;
143
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000144 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
145
146 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700147 int savedErrno = errno;
148 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
149 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000150 }
151
Yifan Hong702115c2021-06-24 15:39:18 -0700152 auto ctx = mRpcTransportCtxFactory->newClientCtx();
153 if (ctx == nullptr) {
154 ALOGE("Unable to create RpcTransportCtx for null debugging client");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700155 return NO_MEMORY;
Yifan Hong702115c2021-06-24 15:39:18 -0700156 }
157 auto server = ctx->newTransport(std::move(serverFd));
158 if (server == nullptr) {
159 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700160 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700161 }
162 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000163}
164
165sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000166 ExclusiveConnection connection;
167 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
168 ConnectionUse::CLIENT, &connection);
169 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000170 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000171}
172
Steven Moreland1be91352021-05-11 22:12:15 +0000173status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000174 ExclusiveConnection connection;
175 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
176 ConnectionUse::CLIENT, &connection);
177 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000178 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000179}
180
Steven Morelandc9d7b532021-06-04 20:57:41 +0000181bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000182 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000183 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000184
185 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000186
Steven Morelandc9d7b532021-06-04 20:57:41 +0000187 if (wait) {
188 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
189 mShutdownListener->waitForShutdown(_l);
Steven Morelanddd67b942021-07-23 17:15:41 -0700190
Steven Morelandc9d7b532021-06-04 20:57:41 +0000191 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
192 }
193
194 _l.unlock();
195 mState->clear();
196
Steven Moreland659416d2021-05-11 00:47:50 +0000197 return true;
198}
199
Steven Morelandf5174272021-05-25 00:39:28 +0000200status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000201 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000202 ExclusiveConnection connection;
203 status_t status =
204 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
205 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
206 : ConnectionUse::CLIENT,
207 &connection);
208 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000209 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000210 sp<RpcSession>::fromExisting(this), reply, flags);
211}
212
213status_t RpcSession::sendDecStrong(const RpcAddress& address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000214 ExclusiveConnection connection;
215 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
216 ConnectionUse::CLIENT_REFCOUNT, &connection);
217 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000218 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000219}
220
Steven Morelande47511f2021-05-20 00:07:41 +0000221std::unique_ptr<RpcSession::FdTrigger> RpcSession::FdTrigger::make() {
222 auto ret = std::make_unique<RpcSession::FdTrigger>();
Steven Morelanda8b44292021-06-08 01:27:53 +0000223 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) {
224 ALOGE("Could not create pipe %s", strerror(errno));
225 return nullptr;
226 }
Steven Morelande47511f2021-05-20 00:07:41 +0000227 return ret;
228}
229
230void RpcSession::FdTrigger::trigger() {
231 mWrite.reset();
232}
233
Steven Morelanda8b44292021-06-08 01:27:53 +0000234bool RpcSession::FdTrigger::isTriggered() {
235 return mWrite == -1;
236}
237
Yifan Hong702115c2021-06-24 15:39:18 -0700238status_t RpcSession::FdTrigger::triggerablePoll(RpcTransport* rpcTransport, int16_t event) {
239 return triggerablePoll(rpcTransport->pollSocket(), event);
240}
241
Steven Moreland798e0d12021-07-14 23:19:25 +0000242status_t RpcSession::FdTrigger::triggerablePoll(base::borrowed_fd fd, int16_t event) {
Steven Moreland4ec3c432021-05-20 00:32:47 +0000243 while (true) {
Steven Moreland441bb0e2021-07-21 22:36:32 +0000244 pollfd pfd[]{{.fd = fd.get(), .events = static_cast<int16_t>(event), .revents = 0},
Steven Moreland4ec3c432021-05-20 00:32:47 +0000245 {.fd = mRead.get(), .events = POLLHUP, .revents = 0}};
246 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
247 if (ret < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000248 return -errno;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000249 }
250 if (ret == 0) {
251 continue;
252 }
253 if (pfd[1].revents & POLLHUP) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000254 return -ECANCELED;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000255 }
Steven Moreland798e0d12021-07-14 23:19:25 +0000256 return pfd[0].revents & event ? OK : DEAD_OBJECT;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000257 }
258}
259
Yifan Hong702115c2021-06-24 15:39:18 -0700260status_t RpcSession::FdTrigger::interruptableWriteFully(RpcTransport* rpcTransport,
261 const void* data, size_t size) {
Steven Moreland798e0d12021-07-14 23:19:25 +0000262 const uint8_t* buffer = reinterpret_cast<const uint8_t*>(data);
263 const uint8_t* end = buffer + size;
264
265 MAYBE_WAIT_IN_FLAKE_MODE;
266
267 status_t status;
Yifan Hong702115c2021-06-24 15:39:18 -0700268 while ((status = triggerablePoll(rpcTransport, POLLOUT)) == OK) {
269 auto writeSize = rpcTransport->send(buffer, end - buffer);
270 if (!writeSize.ok()) {
271 LOG_RPC_DETAIL("RpcTransport::send(): %s", writeSize.error().message().c_str());
272 return writeSize.error().code() == 0 ? UNKNOWN_ERROR : -writeSize.error().code();
Steven Moreland798e0d12021-07-14 23:19:25 +0000273 }
Yifan Hong702115c2021-06-24 15:39:18 -0700274
275 if (*writeSize == 0) return DEAD_OBJECT;
276
277 buffer += *writeSize;
Steven Moreland798e0d12021-07-14 23:19:25 +0000278 if (buffer == end) return OK;
279 }
280 return status;
281}
282
Yifan Hong702115c2021-06-24 15:39:18 -0700283status_t RpcSession::FdTrigger::interruptableReadFully(RpcTransport* rpcTransport, void* data,
Steven Moreland2b4f3802021-05-22 01:46:27 +0000284 size_t size) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000285 uint8_t* buffer = reinterpret_cast<uint8_t*>(data);
286 uint8_t* end = buffer + size;
287
Steven Morelandb8176792021-06-22 20:29:21 +0000288 MAYBE_WAIT_IN_FLAKE_MODE;
289
Steven Moreland2b4f3802021-05-22 01:46:27 +0000290 status_t status;
Yifan Hong702115c2021-06-24 15:39:18 -0700291 while ((status = triggerablePoll(rpcTransport, POLLIN)) == OK) {
292 auto readSize = rpcTransport->recv(buffer, end - buffer);
293 if (!readSize.ok()) {
294 LOG_RPC_DETAIL("RpcTransport::recv(): %s", readSize.error().message().c_str());
295 return readSize.error().code() == 0 ? UNKNOWN_ERROR : -readSize.error().code();
Steven Moreland9d11b922021-05-20 01:22:58 +0000296 }
Yifan Hong702115c2021-06-24 15:39:18 -0700297
298 if (*readSize == 0) return DEAD_OBJECT; // EOF
299
300 buffer += *readSize;
Steven Moreland2b4f3802021-05-22 01:46:27 +0000301 if (buffer == end) return OK;
Steven Moreland9d11b922021-05-20 01:22:58 +0000302 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000303 return status;
Steven Moreland9d11b922021-05-20 01:22:58 +0000304}
305
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000306status_t RpcSession::readId() {
307 {
308 std::lock_guard<std::mutex> _l(mMutex);
309 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
310 }
311
Steven Moreland195edb82021-06-08 02:44:39 +0000312 ExclusiveConnection connection;
313 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
314 ConnectionUse::CLIENT, &connection);
315 if (status != OK) return status;
316
Steven Moreland01a6bad2021-06-11 00:59:20 +0000317 mId = RpcAddress::zero();
318 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this),
319 &mId.value());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000320 if (status != OK) return status;
321
Steven Moreland01a6bad2021-06-11 00:59:20 +0000322 LOG_RPC_DETAIL("RpcSession %p has id %s", this, mId->toString().c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000323 return OK;
324}
325
Steven Morelanddd67b942021-07-23 17:15:41 -0700326void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000327 const sp<RpcSession>& session) {
328 (void)session;
329 mShutdown = true;
330}
331
Steven Moreland19fc9f72021-06-10 03:57:30 +0000332void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000333 mCv.notify_all();
334}
335
336void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
337 while (!mShutdown) {
338 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
339 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
340 }
341 }
342}
343
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000344void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000345 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000346
Steven Morelanda63ff932021-05-12 00:03:15 +0000347 {
348 std::lock_guard<std::mutex> _l(mMutex);
349 mThreads[thread.get_id()] = std::move(thread);
350 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000351}
Steven Morelanda63ff932021-05-12 00:03:15 +0000352
Yifan Hong702115c2021-06-24 15:39:18 -0700353RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
354 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000355 // must be registered to allow arbitrary client code executing commands to
356 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700357 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000358
Steven Morelanddd67b942021-07-23 17:15:41 -0700359 status_t status;
360
361 if (connection == nullptr) {
362 status = DEAD_OBJECT;
363 } else {
364 status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
365 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000366
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000367 return PreJoinSetupResult{
368 .connection = std::move(connection),
369 .status = status,
370 };
371}
372
Yifan Hong194acf22021-06-29 18:44:56 -0700373namespace {
374// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
375// Android Runtime doesn't exist, no-op.
376class JavaThreadAttacher {
377public:
378 JavaThreadAttacher() {
379 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
380 // libbinder.
381 auto vm = getJavaVM();
382 if (vm == nullptr) return;
383
384 char threadName[16];
385 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
386 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
387 memcpy(threadName, defaultThreadName,
388 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
389 }
390 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
391 JavaVMAttachArgs args;
392 args.version = JNI_VERSION_1_2;
393 args.name = threadName;
394 args.group = nullptr;
395 JNIEnv* env;
396
397 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
398 "Cannot attach thread %s to JVM", threadName);
399 mAttached = true;
400 }
401 ~JavaThreadAttacher() {
402 if (!mAttached) return;
403 auto vm = getJavaVM();
404 LOG_ALWAYS_FATAL_IF(vm == nullptr,
405 "Unable to detach thread. No JavaVM, but it was present before!");
406
407 LOG_RPC_DETAIL("Detaching current thread from JVM");
408 if (vm->DetachCurrentThread() != JNI_OK) {
409 mAttached = false;
410 } else {
411 ALOGW("Unable to detach current thread from JVM");
412 }
413 }
414
415private:
416 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
417 bool mAttached = false;
418
419 static JavaVM* getJavaVM() {
420 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
421 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
422 if (fn == nullptr) return nullptr;
423 return fn();
424 }
425};
426} // namespace
427
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000428void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
429 sp<RpcConnection>& connection = setupResult.connection;
430
431 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700432 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hong194acf22021-06-29 18:44:56 -0700433 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000434 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000435 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000436 RpcState::CommandType::ANY);
437 if (status != OK) {
438 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
439 statusToString(status).c_str());
440 break;
441 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000442 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000443 } else {
444 ALOGE("Connection failed to init, closing with status %s",
445 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000446 }
447
Steven Moreland659416d2021-05-11 00:47:50 +0000448 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000449 {
Steven Moreland659416d2021-05-11 00:47:50 +0000450 std::lock_guard<std::mutex> _l(session->mMutex);
451 auto it = session->mThreads.find(std::this_thread::get_id());
452 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000453 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000454 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000455
Steven Moreland659416d2021-05-11 00:47:50 +0000456 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000457 }
458
Steven Morelanddd67b942021-07-23 17:15:41 -0700459 // done after all cleanup, since session shutdown progresses via callbacks here
460 if (connection != nullptr) {
461 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
462 "bad state: connection object guaranteed to be in list");
463 }
464
Steven Moreland659416d2021-05-11 00:47:50 +0000465 session = nullptr;
466
467 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000468 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000469 }
470}
471
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000472sp<RpcServer> RpcSession::server() {
473 RpcServer* unsafeServer = mForServer.unsafe_get();
474 sp<RpcServer> server = mForServer.promote();
475
476 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
477 "wp<> is to avoid strong cycle only");
478 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000479}
480
Steven Moreland2372f9d2021-08-05 15:42:01 -0700481status_t RpcSession::setupClient(
482 const std::function<status_t(const RpcAddress& sessionId, bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000483 {
484 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000485 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000486 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000487 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000488 }
Yifan Hong832521e2021-08-05 14:55:40 -0700489 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000490
Steven Moreland2372f9d2021-08-05 15:42:01 -0700491 if (status_t status = connectAndInit(RpcAddress::zero(), false /*incoming*/); status != OK)
492 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000493
Steven Morelandbf57bce2021-07-26 15:26:12 -0700494 {
495 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700496 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
497 ConnectionUse::CLIENT, &connection);
498 status != OK)
499 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700500
501 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700502 if (status_t status =
503 state()->readNewSessionResponse(connection.get(),
504 sp<RpcSession>::fromExisting(this), &version);
505 status != OK)
506 return status;
507 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700508 }
509
Steven Morelanda5036f02021-06-08 02:26:57 +0000510 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000511 // instead of all at once.
512 // TODO(b/186470974): first risk of blocking
513 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000514 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700515 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000516 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700517 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000518 }
519
520 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700521 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000522 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700523 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000524 }
525
Steven Morelanda5036f02021-06-08 02:26:57 +0000526 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000527 // instead of all at once - the other side should be responsible for setting
528 // up additional connections. We need to create at least one (unless 0 are
529 // requested to be set) in order to allow the other side to reliably make
530 // any requests at all.
531
Steven Moreland4198a122021-08-03 17:37:58 -0700532 // we've already setup one client
533 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700534 if (status_t status = connectAndInit(mId.value(), false /*incoming*/); status != OK)
535 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700536 }
537
Steven Moreland103424e2021-06-02 18:16:19 +0000538 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700539 if (status_t status = connectAndInit(mId.value(), true /*incoming*/); status != OK)
540 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000541 }
542
Steven Moreland2372f9d2021-08-05 15:42:01 -0700543 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000544}
545
Steven Moreland2372f9d2021-08-05 15:42:01 -0700546status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700547 return setupClient([&](const RpcAddress& sessionId, bool incoming) {
548 return setupOneSocketConnection(addr, sessionId, incoming);
549 });
550}
551
Steven Moreland2372f9d2021-08-05 15:42:01 -0700552status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
553 const RpcAddress& sessionId, bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000554 for (size_t tries = 0; tries < 5; tries++) {
555 if (tries > 0) usleep(10000);
556
557 unique_fd serverFd(
558 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
559 if (serverFd == -1) {
560 int savedErrno = errno;
561 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
562 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700563 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000564 }
565
566 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
567 if (errno == ECONNRESET) {
568 ALOGW("Connection reset on %s", addr.toString().c_str());
569 continue;
570 }
571 int savedErrno = errno;
572 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
573 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700574 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000575 }
Yifan Hong702115c2021-06-24 15:39:18 -0700576 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
577
Steven Moreland4198a122021-08-03 17:37:58 -0700578 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000579 }
580
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000581 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700582 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000583}
584
Steven Moreland2372f9d2021-08-05 15:42:01 -0700585status_t RpcSession::initAndAddConnection(unique_fd fd, const RpcAddress& sessionId,
586 bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700587 auto ctx = mRpcTransportCtxFactory->newClientCtx();
588 if (ctx == nullptr) {
589 ALOGE("Unable to create client RpcTransportCtx with %s sockets",
590 mRpcTransportCtxFactory->toCString());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700591 return NO_MEMORY;
Steven Moreland4198a122021-08-03 17:37:58 -0700592 }
593 auto server = ctx->newTransport(std::move(fd));
594 if (server == nullptr) {
595 ALOGE("Unable to set up RpcTransport in %s context", mRpcTransportCtxFactory->toCString());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700596 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700597 }
598
599 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
600
601 RpcConnectionHeader header{
602 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
603 .options = 0,
604 };
605 memcpy(&header.sessionId, &sessionId.viewRawEmbedded(), sizeof(RpcWireAddress));
606
607 if (incoming) header.options |= RPC_CONNECTION_OPTION_INCOMING;
608
609 auto sentHeader = server->send(&header, sizeof(header));
610 if (!sentHeader.ok()) {
611 ALOGE("Could not write connection header to socket: %s",
612 sentHeader.error().message().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700613 return -sentHeader.error().code();
Steven Moreland4198a122021-08-03 17:37:58 -0700614 }
615 if (*sentHeader != sizeof(header)) {
616 ALOGE("Could not write connection header to socket: sent %zd bytes, expected %zd",
617 *sentHeader, sizeof(header));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700618 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700619 }
620
621 LOG_RPC_DETAIL("Socket at client: header sent");
622
623 if (incoming) {
624 return addIncomingConnection(std::move(server));
625 } else {
626 return addOutgoingConnection(std::move(server), true /*init*/);
627 }
628}
629
Steven Moreland2372f9d2021-08-05 15:42:01 -0700630status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000631 std::mutex mutex;
632 std::condition_variable joinCv;
633 std::unique_lock<std::mutex> lock(mutex);
634 std::thread thread;
635 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
636 bool ownershipTransferred = false;
637 thread = std::thread([&]() {
638 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700639 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000640 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
641 sp<RpcSession> session = thiz;
642 session->preJoinThreadOwnership(std::move(thread));
643
644 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700645 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000646
647 ownershipTransferred = true;
648 threadLock.unlock();
649 joinCv.notify_one();
650 // do not use & vars below
651
652 RpcSession::join(std::move(session), std::move(setupResult));
653 });
654 joinCv.wait(lock, [&] { return ownershipTransferred; });
655 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700656 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000657}
658
Yifan Hong832521e2021-08-05 14:55:40 -0700659status_t RpcSession::initShutdownTrigger() {
660 // first client connection added, but setForServer not called, so
661 // initializaing for a client.
662 if (mShutdownTrigger == nullptr) {
663 mShutdownTrigger = FdTrigger::make();
664 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
665 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
666 }
667 return OK;
668}
669
Steven Moreland2372f9d2021-08-05 15:42:01 -0700670status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000671 sp<RpcConnection> connection = sp<RpcConnection>::make();
672 {
673 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700674 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000675 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000676 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000677 }
678
Steven Morelandb86e26b2021-06-12 00:35:58 +0000679 status_t status = OK;
680 if (init) {
681 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
682 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000683
684 {
685 std::lock_guard<std::mutex> _l(mMutex);
686 connection->exclusiveTid = std::nullopt;
687 }
688
Steven Moreland2372f9d2021-08-05 15:42:01 -0700689 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000690}
691
Steven Morelanda8b44292021-06-08 01:27:53 +0000692bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000693 const RpcAddress& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000694 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
695 LOG_ALWAYS_FATAL_IF(server == nullptr);
696 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
697 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000698 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000699
700 mShutdownTrigger = FdTrigger::make();
701 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000702
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000703 mId = sessionId;
704 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000705 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000706 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000707}
708
Yifan Hong702115c2021-06-24 15:39:18 -0700709sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
710 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000711 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700712
Steven Moreland132d5bf2021-08-03 16:13:24 -0700713 if (mIncomingConnections.size() >= mMaxThreads) {
714 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
715 mIncomingConnections.size(), mMaxThreads);
716 return nullptr;
717 }
718
Steven Morelanddd67b942021-07-23 17:15:41 -0700719 // Don't accept any more connections, some have shutdown. Usually this
720 // happens when new connections are still being established as part of a
721 // very short-lived session which shuts down after it already started
722 // accepting new connections.
723 if (mIncomingConnections.size() < mMaxIncomingConnections) {
724 return nullptr;
725 }
726
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000727 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700728 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000729 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700730
Steven Moreland19fc9f72021-06-10 03:57:30 +0000731 mIncomingConnections.push_back(session);
Steven Morelanddd67b942021-07-23 17:15:41 -0700732 mMaxIncomingConnections = mIncomingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000733
734 return session;
735}
736
Steven Moreland19fc9f72021-06-10 03:57:30 +0000737bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700738 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000739 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
740 it != mIncomingConnections.end()) {
741 mIncomingConnections.erase(it);
742 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000743 sp<EventListener> listener = mEventListener.promote();
744 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700745 _l.unlock();
746 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000747 }
Steven Morelandee78e762021-05-05 21:12:51 +0000748 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000749 return true;
750 }
751 return false;
752}
753
Steven Moreland195edb82021-06-08 02:44:39 +0000754status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
755 ExclusiveConnection* connection) {
756 connection->mSession = session;
757 connection->mConnection = nullptr;
758 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000759
Steven Moreland195edb82021-06-08 02:44:39 +0000760 pid_t tid = gettid();
761 std::unique_lock<std::mutex> _l(session->mMutex);
762
763 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000764 while (true) {
765 sp<RpcConnection> exclusive;
766 sp<RpcConnection> available;
767
768 // CHECK FOR DEDICATED CLIENT SOCKET
769 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000770 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000771 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
772 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000773
774 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000775 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000776 //
777 // Imagine we have more than one thread in play, and a single thread
778 // sends a synchronous, then an asynchronous command. Imagine the
779 // asynchronous command is sent on the first client connection. Then, if
780 // we naively send a synchronous command to that same connection, the
781 // thread on the far side might be busy processing the asynchronous
782 // command. So, we move to considering the second available thread
783 // for subsequent calls.
784 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000785 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
786 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000787 }
788
Steven Morelandc7d40132021-06-10 03:42:11 +0000789 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000790 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000791 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000792 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000793 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
794 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000795
796 // asynchronous calls cannot be nested, we currently allow ref count
797 // calls to be nested (so that you can use this without having extra
798 // threads). Note 'drainCommands' is used so that these ref counts can't
799 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000800 if (exclusiveIncoming != nullptr) {
801 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000802 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000803 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000804 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
805 // prefer available socket, but if we don't have one, don't
806 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000807 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000808 }
809 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000810 }
811
Steven Moreland85e067b2021-05-26 17:43:53 +0000812 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000813 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000814 connection->mConnection = exclusive;
815 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000816 break;
817 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000818 connection->mConnection = available;
819 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000820 break;
821 }
822
Steven Moreland19fc9f72021-06-10 03:57:30 +0000823 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000824 ALOGE("Session has no client connections. This is required for an RPC server to make "
825 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
826 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000827 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000828 return WOULD_BLOCK;
829 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000830
Steven Moreland85e067b2021-05-26 17:43:53 +0000831 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000832 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000833 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000834 }
Steven Moreland195edb82021-06-08 02:44:39 +0000835 session->mWaitingThreads--;
836
837 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000838}
839
840void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
841 sp<RpcConnection>* available,
842 std::vector<sp<RpcConnection>>& sockets,
843 size_t socketsIndexHint) {
844 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
845 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
846
847 if (*exclusive != nullptr) return; // consistent with break below
848
849 for (size_t i = 0; i < sockets.size(); i++) {
850 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
851
Steven Moreland85e067b2021-05-26 17:43:53 +0000852 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000853 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
854 *available = socket;
855 continue;
856 }
857
Steven Moreland85e067b2021-05-26 17:43:53 +0000858 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000859 // (nested transactions)
860 if (exclusive && socket->exclusiveTid == tid) {
861 *exclusive = socket;
862 break; // consistent with return above
863 }
864 }
865}
866
867RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000868 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000869 // is using this fd, and it retains the right to it. So, we don't give up
870 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000871 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000872 std::unique_lock<std::mutex> _l(mSession->mMutex);
873 mConnection->exclusiveTid = std::nullopt;
874 if (mSession->mWaitingThreads > 0) {
875 _l.unlock();
876 mSession->mAvailableConnectionCv.notify_one();
877 }
878 }
879}
880
881} // namespace android