blob: 11dc1ab862a990897fe5e12c1df36ce3988cc6a0 [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.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000142 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
143
144 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700145 int savedErrno = errno;
146 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
147 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000148 }
149
Yifan Hong702115c2021-06-24 15:39:18 -0700150 auto ctx = mRpcTransportCtxFactory->newClientCtx();
151 if (ctx == nullptr) {
152 ALOGE("Unable to create RpcTransportCtx for null debugging client");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700153 return NO_MEMORY;
Yifan Hong702115c2021-06-24 15:39:18 -0700154 }
155 auto server = ctx->newTransport(std::move(serverFd));
156 if (server == nullptr) {
157 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700158 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700159 }
160 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000161}
162
163sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000164 ExclusiveConnection connection;
165 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
166 ConnectionUse::CLIENT, &connection);
167 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000168 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000169}
170
Steven Moreland1be91352021-05-11 22:12:15 +0000171status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000172 ExclusiveConnection connection;
173 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
174 ConnectionUse::CLIENT, &connection);
175 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000176 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000177}
178
Steven Morelandc9d7b532021-06-04 20:57:41 +0000179bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000180 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000181 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000182
183 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000184
Steven Morelandc9d7b532021-06-04 20:57:41 +0000185 if (wait) {
186 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
187 mShutdownListener->waitForShutdown(_l);
Steven Morelanddd67b942021-07-23 17:15:41 -0700188
Steven Morelandc9d7b532021-06-04 20:57:41 +0000189 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
190 }
191
192 _l.unlock();
193 mState->clear();
194
Steven Moreland659416d2021-05-11 00:47:50 +0000195 return true;
196}
197
Steven Morelandf5174272021-05-25 00:39:28 +0000198status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000199 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000200 ExclusiveConnection connection;
201 status_t status =
202 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
203 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
204 : ConnectionUse::CLIENT,
205 &connection);
206 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000207 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000208 sp<RpcSession>::fromExisting(this), reply, flags);
209}
210
211status_t RpcSession::sendDecStrong(const RpcAddress& address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000212 ExclusiveConnection connection;
213 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
214 ConnectionUse::CLIENT_REFCOUNT, &connection);
215 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000216 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000217}
218
Steven Morelande47511f2021-05-20 00:07:41 +0000219std::unique_ptr<RpcSession::FdTrigger> RpcSession::FdTrigger::make() {
220 auto ret = std::make_unique<RpcSession::FdTrigger>();
Steven Morelanda8b44292021-06-08 01:27:53 +0000221 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) {
222 ALOGE("Could not create pipe %s", strerror(errno));
223 return nullptr;
224 }
Steven Morelande47511f2021-05-20 00:07:41 +0000225 return ret;
226}
227
228void RpcSession::FdTrigger::trigger() {
229 mWrite.reset();
230}
231
Steven Morelanda8b44292021-06-08 01:27:53 +0000232bool RpcSession::FdTrigger::isTriggered() {
233 return mWrite == -1;
234}
235
Yifan Hong702115c2021-06-24 15:39:18 -0700236status_t RpcSession::FdTrigger::triggerablePoll(RpcTransport* rpcTransport, int16_t event) {
237 return triggerablePoll(rpcTransport->pollSocket(), event);
238}
239
Steven Moreland798e0d12021-07-14 23:19:25 +0000240status_t RpcSession::FdTrigger::triggerablePoll(base::borrowed_fd fd, int16_t event) {
Steven Moreland4ec3c432021-05-20 00:32:47 +0000241 while (true) {
Steven Moreland441bb0e2021-07-21 22:36:32 +0000242 pollfd pfd[]{{.fd = fd.get(), .events = static_cast<int16_t>(event), .revents = 0},
Steven Moreland4ec3c432021-05-20 00:32:47 +0000243 {.fd = mRead.get(), .events = POLLHUP, .revents = 0}};
244 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
245 if (ret < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000246 return -errno;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000247 }
248 if (ret == 0) {
249 continue;
250 }
251 if (pfd[1].revents & POLLHUP) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000252 return -ECANCELED;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000253 }
Steven Moreland798e0d12021-07-14 23:19:25 +0000254 return pfd[0].revents & event ? OK : DEAD_OBJECT;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000255 }
256}
257
Yifan Hong702115c2021-06-24 15:39:18 -0700258status_t RpcSession::FdTrigger::interruptableWriteFully(RpcTransport* rpcTransport,
259 const void* data, size_t size) {
Steven Moreland798e0d12021-07-14 23:19:25 +0000260 const uint8_t* buffer = reinterpret_cast<const uint8_t*>(data);
261 const uint8_t* end = buffer + size;
262
263 MAYBE_WAIT_IN_FLAKE_MODE;
264
265 status_t status;
Yifan Hong702115c2021-06-24 15:39:18 -0700266 while ((status = triggerablePoll(rpcTransport, POLLOUT)) == OK) {
267 auto writeSize = rpcTransport->send(buffer, end - buffer);
268 if (!writeSize.ok()) {
269 LOG_RPC_DETAIL("RpcTransport::send(): %s", writeSize.error().message().c_str());
270 return writeSize.error().code() == 0 ? UNKNOWN_ERROR : -writeSize.error().code();
Steven Moreland798e0d12021-07-14 23:19:25 +0000271 }
Yifan Hong702115c2021-06-24 15:39:18 -0700272
273 if (*writeSize == 0) return DEAD_OBJECT;
274
275 buffer += *writeSize;
Steven Moreland798e0d12021-07-14 23:19:25 +0000276 if (buffer == end) return OK;
277 }
278 return status;
279}
280
Yifan Hong702115c2021-06-24 15:39:18 -0700281status_t RpcSession::FdTrigger::interruptableReadFully(RpcTransport* rpcTransport, void* data,
Steven Moreland2b4f3802021-05-22 01:46:27 +0000282 size_t size) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000283 uint8_t* buffer = reinterpret_cast<uint8_t*>(data);
284 uint8_t* end = buffer + size;
285
Steven Morelandb8176792021-06-22 20:29:21 +0000286 MAYBE_WAIT_IN_FLAKE_MODE;
287
Steven Moreland2b4f3802021-05-22 01:46:27 +0000288 status_t status;
Yifan Hong702115c2021-06-24 15:39:18 -0700289 while ((status = triggerablePoll(rpcTransport, POLLIN)) == OK) {
290 auto readSize = rpcTransport->recv(buffer, end - buffer);
291 if (!readSize.ok()) {
292 LOG_RPC_DETAIL("RpcTransport::recv(): %s", readSize.error().message().c_str());
293 return readSize.error().code() == 0 ? UNKNOWN_ERROR : -readSize.error().code();
Steven Moreland9d11b922021-05-20 01:22:58 +0000294 }
Yifan Hong702115c2021-06-24 15:39:18 -0700295
296 if (*readSize == 0) return DEAD_OBJECT; // EOF
297
298 buffer += *readSize;
Steven Moreland2b4f3802021-05-22 01:46:27 +0000299 if (buffer == end) return OK;
Steven Moreland9d11b922021-05-20 01:22:58 +0000300 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000301 return status;
Steven Moreland9d11b922021-05-20 01:22:58 +0000302}
303
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000304status_t RpcSession::readId() {
305 {
306 std::lock_guard<std::mutex> _l(mMutex);
307 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
308 }
309
Steven Moreland195edb82021-06-08 02:44:39 +0000310 ExclusiveConnection connection;
311 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
312 ConnectionUse::CLIENT, &connection);
313 if (status != OK) return status;
314
Steven Moreland01a6bad2021-06-11 00:59:20 +0000315 mId = RpcAddress::zero();
316 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this),
317 &mId.value());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000318 if (status != OK) return status;
319
Steven Moreland01a6bad2021-06-11 00:59:20 +0000320 LOG_RPC_DETAIL("RpcSession %p has id %s", this, mId->toString().c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000321 return OK;
322}
323
Steven Morelanddd67b942021-07-23 17:15:41 -0700324void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000325 const sp<RpcSession>& session) {
326 (void)session;
327 mShutdown = true;
328}
329
Steven Moreland19fc9f72021-06-10 03:57:30 +0000330void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000331 mCv.notify_all();
332}
333
334void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
335 while (!mShutdown) {
336 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
337 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
338 }
339 }
340}
341
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000342void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000343 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000344
Steven Morelanda63ff932021-05-12 00:03:15 +0000345 {
346 std::lock_guard<std::mutex> _l(mMutex);
347 mThreads[thread.get_id()] = std::move(thread);
348 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000349}
Steven Morelanda63ff932021-05-12 00:03:15 +0000350
Yifan Hong702115c2021-06-24 15:39:18 -0700351RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
352 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000353 // must be registered to allow arbitrary client code executing commands to
354 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700355 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000356
Steven Morelanddd67b942021-07-23 17:15:41 -0700357 status_t status;
358
359 if (connection == nullptr) {
360 status = DEAD_OBJECT;
361 } else {
362 status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
363 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000364
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000365 return PreJoinSetupResult{
366 .connection = std::move(connection),
367 .status = status,
368 };
369}
370
Yifan Hong194acf22021-06-29 18:44:56 -0700371namespace {
372// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
373// Android Runtime doesn't exist, no-op.
374class JavaThreadAttacher {
375public:
376 JavaThreadAttacher() {
377 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
378 // libbinder.
379 auto vm = getJavaVM();
380 if (vm == nullptr) return;
381
382 char threadName[16];
383 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
384 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
385 memcpy(threadName, defaultThreadName,
386 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
387 }
388 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
389 JavaVMAttachArgs args;
390 args.version = JNI_VERSION_1_2;
391 args.name = threadName;
392 args.group = nullptr;
393 JNIEnv* env;
394
395 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
396 "Cannot attach thread %s to JVM", threadName);
397 mAttached = true;
398 }
399 ~JavaThreadAttacher() {
400 if (!mAttached) return;
401 auto vm = getJavaVM();
402 LOG_ALWAYS_FATAL_IF(vm == nullptr,
403 "Unable to detach thread. No JavaVM, but it was present before!");
404
405 LOG_RPC_DETAIL("Detaching current thread from JVM");
406 if (vm->DetachCurrentThread() != JNI_OK) {
407 mAttached = false;
408 } else {
409 ALOGW("Unable to detach current thread from JVM");
410 }
411 }
412
413private:
414 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
415 bool mAttached = false;
416
417 static JavaVM* getJavaVM() {
418 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
419 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
420 if (fn == nullptr) return nullptr;
421 return fn();
422 }
423};
424} // namespace
425
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000426void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
427 sp<RpcConnection>& connection = setupResult.connection;
428
429 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700430 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hong194acf22021-06-29 18:44:56 -0700431 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000432 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000433 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000434 RpcState::CommandType::ANY);
435 if (status != OK) {
436 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
437 statusToString(status).c_str());
438 break;
439 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000440 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000441 } else {
442 ALOGE("Connection failed to init, closing with status %s",
443 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000444 }
445
Steven Moreland659416d2021-05-11 00:47:50 +0000446 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000447 {
Steven Moreland659416d2021-05-11 00:47:50 +0000448 std::lock_guard<std::mutex> _l(session->mMutex);
449 auto it = session->mThreads.find(std::this_thread::get_id());
450 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000451 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000452 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000453
Steven Moreland659416d2021-05-11 00:47:50 +0000454 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000455 }
456
Steven Morelanddd67b942021-07-23 17:15:41 -0700457 // done after all cleanup, since session shutdown progresses via callbacks here
458 if (connection != nullptr) {
459 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
460 "bad state: connection object guaranteed to be in list");
461 }
462
Steven Moreland659416d2021-05-11 00:47:50 +0000463 session = nullptr;
464
465 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000466 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000467 }
468}
469
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000470sp<RpcServer> RpcSession::server() {
471 RpcServer* unsafeServer = mForServer.unsafe_get();
472 sp<RpcServer> server = mForServer.promote();
473
474 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
475 "wp<> is to avoid strong cycle only");
476 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000477}
478
Steven Moreland2372f9d2021-08-05 15:42:01 -0700479status_t RpcSession::setupClient(
480 const std::function<status_t(const RpcAddress& sessionId, bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000481 {
482 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000483 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000484 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000485 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000486 }
487
Steven Moreland2372f9d2021-08-05 15:42:01 -0700488 if (status_t status = connectAndInit(RpcAddress::zero(), false /*incoming*/); status != OK)
489 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000490
Steven Morelandbf57bce2021-07-26 15:26:12 -0700491 {
492 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700493 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
494 ConnectionUse::CLIENT, &connection);
495 status != OK)
496 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700497
498 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700499 if (status_t status =
500 state()->readNewSessionResponse(connection.get(),
501 sp<RpcSession>::fromExisting(this), &version);
502 status != OK)
503 return status;
504 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700505 }
506
Steven Morelanda5036f02021-06-08 02:26:57 +0000507 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000508 // instead of all at once.
509 // TODO(b/186470974): first risk of blocking
510 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000511 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700512 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000513 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700514 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000515 }
516
517 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700518 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000519 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700520 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000521 }
522
Steven Morelanda5036f02021-06-08 02:26:57 +0000523 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000524 // instead of all at once - the other side should be responsible for setting
525 // up additional connections. We need to create at least one (unless 0 are
526 // requested to be set) in order to allow the other side to reliably make
527 // any requests at all.
528
Steven Moreland4198a122021-08-03 17:37:58 -0700529 // we've already setup one client
530 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700531 if (status_t status = connectAndInit(mId.value(), false /*incoming*/); status != OK)
532 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700533 }
534
Steven Moreland103424e2021-06-02 18:16:19 +0000535 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700536 if (status_t status = connectAndInit(mId.value(), true /*incoming*/); status != OK)
537 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000538 }
539
Steven Moreland2372f9d2021-08-05 15:42:01 -0700540 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000541}
542
Steven Moreland2372f9d2021-08-05 15:42:01 -0700543status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700544 return setupClient([&](const RpcAddress& sessionId, bool incoming) {
545 return setupOneSocketConnection(addr, sessionId, incoming);
546 });
547}
548
Steven Moreland2372f9d2021-08-05 15:42:01 -0700549status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
550 const RpcAddress& sessionId, bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000551 for (size_t tries = 0; tries < 5; tries++) {
552 if (tries > 0) usleep(10000);
553
554 unique_fd serverFd(
555 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
556 if (serverFd == -1) {
557 int savedErrno = errno;
558 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
559 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700560 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000561 }
562
563 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
564 if (errno == ECONNRESET) {
565 ALOGW("Connection reset on %s", addr.toString().c_str());
566 continue;
567 }
568 int savedErrno = errno;
569 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
570 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700571 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000572 }
Yifan Hong702115c2021-06-24 15:39:18 -0700573 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
574
Steven Moreland4198a122021-08-03 17:37:58 -0700575 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000576 }
577
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000578 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700579 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000580}
581
Steven Moreland2372f9d2021-08-05 15:42:01 -0700582status_t RpcSession::initAndAddConnection(unique_fd fd, const RpcAddress& sessionId,
583 bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700584 auto ctx = mRpcTransportCtxFactory->newClientCtx();
585 if (ctx == nullptr) {
586 ALOGE("Unable to create client RpcTransportCtx with %s sockets",
587 mRpcTransportCtxFactory->toCString());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700588 return NO_MEMORY;
Steven Moreland4198a122021-08-03 17:37:58 -0700589 }
590 auto server = ctx->newTransport(std::move(fd));
591 if (server == nullptr) {
592 ALOGE("Unable to set up RpcTransport in %s context", mRpcTransportCtxFactory->toCString());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700593 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700594 }
595
596 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
597
598 RpcConnectionHeader header{
599 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
600 .options = 0,
601 };
602 memcpy(&header.sessionId, &sessionId.viewRawEmbedded(), sizeof(RpcWireAddress));
603
604 if (incoming) header.options |= RPC_CONNECTION_OPTION_INCOMING;
605
606 auto sentHeader = server->send(&header, sizeof(header));
607 if (!sentHeader.ok()) {
608 ALOGE("Could not write connection header to socket: %s",
609 sentHeader.error().message().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700610 return -sentHeader.error().code();
Steven Moreland4198a122021-08-03 17:37:58 -0700611 }
612 if (*sentHeader != sizeof(header)) {
613 ALOGE("Could not write connection header to socket: sent %zd bytes, expected %zd",
614 *sentHeader, sizeof(header));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700615 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700616 }
617
618 LOG_RPC_DETAIL("Socket at client: header sent");
619
620 if (incoming) {
621 return addIncomingConnection(std::move(server));
622 } else {
623 return addOutgoingConnection(std::move(server), true /*init*/);
624 }
625}
626
Steven Moreland2372f9d2021-08-05 15:42:01 -0700627status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000628 std::mutex mutex;
629 std::condition_variable joinCv;
630 std::unique_lock<std::mutex> lock(mutex);
631 std::thread thread;
632 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
633 bool ownershipTransferred = false;
634 thread = std::thread([&]() {
635 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700636 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000637 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
638 sp<RpcSession> session = thiz;
639 session->preJoinThreadOwnership(std::move(thread));
640
641 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700642 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000643
644 ownershipTransferred = true;
645 threadLock.unlock();
646 joinCv.notify_one();
647 // do not use & vars below
648
649 RpcSession::join(std::move(session), std::move(setupResult));
650 });
651 joinCv.wait(lock, [&] { return ownershipTransferred; });
652 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700653 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000654}
655
Steven Moreland2372f9d2021-08-05 15:42:01 -0700656status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000657 sp<RpcConnection> connection = sp<RpcConnection>::make();
658 {
659 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000660
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000661 // first client connection added, but setForServer not called, so
662 // initializaing for a client.
663 if (mShutdownTrigger == nullptr) {
664 mShutdownTrigger = FdTrigger::make();
665 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700666 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000667 }
668
Yifan Hong702115c2021-06-24 15:39:18 -0700669 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000670 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000671 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000672 }
673
Steven Morelandb86e26b2021-06-12 00:35:58 +0000674 status_t status = OK;
675 if (init) {
676 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
677 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000678
679 {
680 std::lock_guard<std::mutex> _l(mMutex);
681 connection->exclusiveTid = std::nullopt;
682 }
683
Steven Moreland2372f9d2021-08-05 15:42:01 -0700684 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000685}
686
Steven Morelanda8b44292021-06-08 01:27:53 +0000687bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000688 const RpcAddress& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000689 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
690 LOG_ALWAYS_FATAL_IF(server == nullptr);
691 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
692 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000693 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000694
695 mShutdownTrigger = FdTrigger::make();
696 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000697
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000698 mId = sessionId;
699 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000700 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000701 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000702}
703
Yifan Hong702115c2021-06-24 15:39:18 -0700704sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
705 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000706 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700707
Steven Moreland132d5bf2021-08-03 16:13:24 -0700708 if (mIncomingConnections.size() >= mMaxThreads) {
709 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
710 mIncomingConnections.size(), mMaxThreads);
711 return nullptr;
712 }
713
Steven Morelanddd67b942021-07-23 17:15:41 -0700714 // Don't accept any more connections, some have shutdown. Usually this
715 // happens when new connections are still being established as part of a
716 // very short-lived session which shuts down after it already started
717 // accepting new connections.
718 if (mIncomingConnections.size() < mMaxIncomingConnections) {
719 return nullptr;
720 }
721
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000722 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700723 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000724 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700725
Steven Moreland19fc9f72021-06-10 03:57:30 +0000726 mIncomingConnections.push_back(session);
Steven Morelanddd67b942021-07-23 17:15:41 -0700727 mMaxIncomingConnections = mIncomingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000728
729 return session;
730}
731
Steven Moreland19fc9f72021-06-10 03:57:30 +0000732bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700733 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000734 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
735 it != mIncomingConnections.end()) {
736 mIncomingConnections.erase(it);
737 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000738 sp<EventListener> listener = mEventListener.promote();
739 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700740 _l.unlock();
741 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000742 }
Steven Morelandee78e762021-05-05 21:12:51 +0000743 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000744 return true;
745 }
746 return false;
747}
748
Steven Moreland195edb82021-06-08 02:44:39 +0000749status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
750 ExclusiveConnection* connection) {
751 connection->mSession = session;
752 connection->mConnection = nullptr;
753 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000754
Steven Moreland195edb82021-06-08 02:44:39 +0000755 pid_t tid = gettid();
756 std::unique_lock<std::mutex> _l(session->mMutex);
757
758 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000759 while (true) {
760 sp<RpcConnection> exclusive;
761 sp<RpcConnection> available;
762
763 // CHECK FOR DEDICATED CLIENT SOCKET
764 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000765 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000766 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
767 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000768
769 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000770 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000771 //
772 // Imagine we have more than one thread in play, and a single thread
773 // sends a synchronous, then an asynchronous command. Imagine the
774 // asynchronous command is sent on the first client connection. Then, if
775 // we naively send a synchronous command to that same connection, the
776 // thread on the far side might be busy processing the asynchronous
777 // command. So, we move to considering the second available thread
778 // for subsequent calls.
779 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000780 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
781 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000782 }
783
Steven Morelandc7d40132021-06-10 03:42:11 +0000784 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000785 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000786 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000787 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000788 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
789 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000790
791 // asynchronous calls cannot be nested, we currently allow ref count
792 // calls to be nested (so that you can use this without having extra
793 // threads). Note 'drainCommands' is used so that these ref counts can't
794 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000795 if (exclusiveIncoming != nullptr) {
796 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000797 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000798 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000799 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
800 // prefer available socket, but if we don't have one, don't
801 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000802 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000803 }
804 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000805 }
806
Steven Moreland85e067b2021-05-26 17:43:53 +0000807 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000808 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000809 connection->mConnection = exclusive;
810 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000811 break;
812 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000813 connection->mConnection = available;
814 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000815 break;
816 }
817
Steven Moreland19fc9f72021-06-10 03:57:30 +0000818 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000819 ALOGE("Session has no client connections. This is required for an RPC server to make "
820 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
821 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000822 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000823 return WOULD_BLOCK;
824 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000825
Steven Moreland85e067b2021-05-26 17:43:53 +0000826 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000827 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000828 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000829 }
Steven Moreland195edb82021-06-08 02:44:39 +0000830 session->mWaitingThreads--;
831
832 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000833}
834
835void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
836 sp<RpcConnection>* available,
837 std::vector<sp<RpcConnection>>& sockets,
838 size_t socketsIndexHint) {
839 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
840 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
841
842 if (*exclusive != nullptr) return; // consistent with break below
843
844 for (size_t i = 0; i < sockets.size(); i++) {
845 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
846
Steven Moreland85e067b2021-05-26 17:43:53 +0000847 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000848 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
849 *available = socket;
850 continue;
851 }
852
Steven Moreland85e067b2021-05-26 17:43:53 +0000853 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000854 // (nested transactions)
855 if (exclusive && socket->exclusiveTid == tid) {
856 *exclusive = socket;
857 break; // consistent with return above
858 }
859 }
860}
861
862RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000863 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000864 // is using this fd, and it retains the right to it. So, we don't give up
865 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000866 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000867 std::unique_lock<std::mutex> _l(mSession->mMutex);
868 mConnection->exclusiveTid = std::nullopt;
869 if (mSession->mWaitingThreads > 0) {
870 _l.unlock();
871 mSession->mAvailableConnectionCv.notify_one();
872 }
873 }
874}
875
876} // namespace android