blob: 41842a7d841705a64a473e5aa9eb56e41ff1013b [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>
Steven Moreland27a8bc72021-09-29 16:07:41 -070031#include <android-base/scopeguard.h>
Steven Moreland4f622fe2021-09-13 17:38:09 -070032#include <binder/BpBinder.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000033#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000034#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070035#include <binder/RpcTransportRaw.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000036#include <binder/Stability.h>
Andrei Homescu1d935e82022-04-25 04:58:23 +000037#include <utils/Compat.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000038#include <utils/String8.h>
39
Yifan Hong8c950422021-08-05 17:13:55 -070040#include "FdTrigger.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000041#include "RpcSocketAddress.h"
42#include "RpcState.h"
43#include "RpcWireFormat.h"
Yifan Hongb675ffe2021-08-05 16:37:17 -070044#include "Utils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000045
Andrei Homescu47f8c4f2022-04-30 01:38:24 +000046#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -070047#include <android_runtime/vm.h>
48#include <jni.h>
49#endif
50
Steven Morelandbdb53ab2021-05-05 17:57:41 +000051namespace android {
52
53using base::unique_fd;
54
Yifan Hongecf937d2021-08-11 17:29:28 -070055RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000056 LOG_RPC_DETAIL("RpcSession created %p", this);
57
Steven Moreland27a8bc72021-09-29 16:07:41 -070058 mRpcBinderState = std::make_unique<RpcState>();
Steven Morelandbdb53ab2021-05-05 17:57:41 +000059}
60RpcSession::~RpcSession() {
61 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
62
63 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070064 LOG_ALWAYS_FATAL_IF(mConnections.mIncoming.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000065 "Should not be able to destroy a session with servers in use.");
66}
67
Yifan Hongecf937d2021-08-11 17:29:28 -070068sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070069 // Default is without TLS.
Yifan Hongfdd9f692021-09-09 15:12:52 -070070 return make(RpcTransportCtxFactoryRaw::make());
Yifan Hongecf937d2021-08-11 17:29:28 -070071}
72
Yifan Hongfdd9f692021-09-09 15:12:52 -070073sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
Yifan Hongecf937d2021-08-11 17:29:28 -070074 auto ctx = rpcTransportCtxFactory->newClientCtx();
75 if (ctx == nullptr) return nullptr;
Yifan Hongecf937d2021-08-11 17:29:28 -070076 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000077}
78
Yifan Hong10423062021-10-08 16:26:32 -070079void RpcSession::setMaxIncomingThreads(size_t threads) {
Steven Moreland103424e2021-06-02 18:16:19 +000080 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070081 LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
Yifan Hong10423062021-10-08 16:26:32 -070082 "Must set max incoming threads before setting up connections, but has %zu "
83 "client(s) and %zu server(s)",
Steven Morelanda59937e2021-10-04 17:42:30 -070084 mConnections.mOutgoing.size(), mConnections.mIncoming.size());
Yifan Hong10423062021-10-08 16:26:32 -070085 mMaxIncomingThreads = threads;
Steven Moreland103424e2021-06-02 18:16:19 +000086}
87
Yifan Hong10423062021-10-08 16:26:32 -070088size_t RpcSession::getMaxIncomingThreads() {
Steven Moreland103424e2021-06-02 18:16:19 +000089 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong10423062021-10-08 16:26:32 -070090 return mMaxIncomingThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000091}
92
Yifan Hong1f44f982021-10-08 17:16:47 -070093void RpcSession::setMaxOutgoingThreads(size_t threads) {
94 std::lock_guard<std::mutex> _l(mMutex);
95 LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
96 "Must set max outgoing threads before setting up connections, but has %zu "
97 "client(s) and %zu server(s)",
98 mConnections.mOutgoing.size(), mConnections.mIncoming.size());
99 mMaxOutgoingThreads = threads;
100}
101
102size_t RpcSession::getMaxOutgoingThreads() {
103 std::lock_guard<std::mutex> _l(mMutex);
104 return mMaxOutgoingThreads;
105}
106
Steven Morelandbf57bce2021-07-26 15:26:12 -0700107bool RpcSession::setProtocolVersion(uint32_t version) {
108 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
109 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
110 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
111 "is %u).",
112 version, RPC_WIRE_PROTOCOL_VERSION);
113 return false;
114 }
115
116 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -0700117 if (mProtocolVersion && version > *mProtocolVersion) {
118 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
119 *mProtocolVersion, version);
120 return false;
121 }
122
Steven Morelandbf57bce2021-07-26 15:26:12 -0700123 mProtocolVersion = version;
124 return true;
125}
126
127std::optional<uint32_t> RpcSession::getProtocolVersion() {
128 std::lock_guard<std::mutex> _l(mMutex);
129 return mProtocolVersion;
130}
131
Frederick Mayle69a0c992022-05-26 20:38:39 +0000132void RpcSession::setFileDescriptorTransportMode(FileDescriptorTransportMode mode) {
133 mFileDescriptorTransportMode = mode;
134}
135
136RpcSession::FileDescriptorTransportMode RpcSession::getFileDescriptorTransportMode() {
137 return mFileDescriptorTransportMode;
138}
139
Steven Moreland2372f9d2021-08-05 15:42:01 -0700140status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000141 return setupSocketClient(UnixSocketAddress(path));
142}
143
Steven Moreland2372f9d2021-08-05 15:42:01 -0700144status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000145 return setupSocketClient(VsockSocketAddress(cid, port));
146}
147
Steven Moreland2372f9d2021-08-05 15:42:01 -0700148status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000149 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700150 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000151 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
152 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700153 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000154 }
155 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 -0700156 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000157}
158
Steven Moreland2372f9d2021-08-05 15:42:01 -0700159status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
Frederick Mayle297c2772022-05-05 01:21:04 +0000160 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700161 if (!fd.ok()) {
162 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700163 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700164 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700165 if (auto res = setNonBlocking(fd); !res.ok()) {
166 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
167 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
168 }
Frederick Mayle297c2772022-05-05 01:21:04 +0000169 status_t status = initAndAddConnection(std::move(fd), sessionId, incoming);
170 fd = unique_fd(); // Explicitly reset after move to avoid analyzer warning.
171 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700172 });
173}
174
Steven Moreland2372f9d2021-08-05 15:42:01 -0700175status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700176 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700177 if (auto status = initShutdownTrigger(); status != OK) return status;
178
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000179 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
180
181 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700182 int savedErrno = errno;
183 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
184 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000185 }
186
Yifan Hongecf937d2021-08-11 17:29:28 -0700187 auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700188 if (server == nullptr) {
189 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700190 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700191 }
192 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000193}
194
195sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000196 ExclusiveConnection connection;
197 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
198 ConnectionUse::CLIENT, &connection);
199 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000200 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000201}
202
Steven Moreland1be91352021-05-11 22:12:15 +0000203status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000204 ExclusiveConnection connection;
205 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
206 ConnectionUse::CLIENT, &connection);
207 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000208 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000209}
210
Steven Morelandc9d7b532021-06-04 20:57:41 +0000211bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000212 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000213 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000214
215 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000216
Steven Morelandc9d7b532021-06-04 20:57:41 +0000217 if (wait) {
218 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700219 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700220
Steven Morelanda59937e2021-10-04 17:42:30 -0700221 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000222 }
223
224 _l.unlock();
Steven Moreland27a8bc72021-09-29 16:07:41 -0700225 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000226
Steven Moreland659416d2021-05-11 00:47:50 +0000227 return true;
228}
229
Steven Morelandf5174272021-05-25 00:39:28 +0000230status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000231 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000232 ExclusiveConnection connection;
233 status_t status =
234 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
235 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
236 : ConnectionUse::CLIENT,
237 &connection);
238 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000239 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000240 sp<RpcSession>::fromExisting(this), reply, flags);
241}
242
Steven Moreland4f622fe2021-09-13 17:38:09 -0700243status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000244 // target is 0 because this is used to free BpBinder objects
245 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700246}
247
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000248status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000249 ExclusiveConnection connection;
250 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
251 ConnectionUse::CLIENT_REFCOUNT, &connection);
252 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000253 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
254 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000255}
256
257status_t RpcSession::readId() {
258 {
259 std::lock_guard<std::mutex> _l(mMutex);
260 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
261 }
262
Steven Moreland195edb82021-06-08 02:44:39 +0000263 ExclusiveConnection connection;
264 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
265 ConnectionUse::CLIENT, &connection);
266 if (status != OK) return status;
267
Steven Moreland826367f2021-09-10 14:05:31 -0700268 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000269 if (status != OK) return status;
270
Steven Moreland826367f2021-09-10 14:05:31 -0700271 LOG_RPC_DETAIL("RpcSession %p has id %s", this,
272 base::HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000273 return OK;
274}
275
Steven Morelanddd67b942021-07-23 17:15:41 -0700276void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000277 const sp<RpcSession>& session) {
278 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000279}
280
Steven Moreland19fc9f72021-06-10 03:57:30 +0000281void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000282 mCv.notify_all();
283}
284
Steven Moreland791e4662021-09-13 15:22:58 -0700285void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock,
286 const sp<RpcSession>& session) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700287 while (session->mConnections.mIncoming.size() > 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000288 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700289 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
290 "still.",
Steven Morelanda59937e2021-10-04 17:42:30 -0700291 session->mConnections.mIncoming.size());
Steven Moreland659416d2021-05-11 00:47:50 +0000292 }
293 }
294}
295
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000296void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000297 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000298
Steven Morelanda63ff932021-05-12 00:03:15 +0000299 {
300 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700301 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000302 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000303}
Steven Morelanda63ff932021-05-12 00:03:15 +0000304
Yifan Hong702115c2021-06-24 15:39:18 -0700305RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
306 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000307 // must be registered to allow arbitrary client code executing commands to
308 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700309 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000310
Steven Morelanddd67b942021-07-23 17:15:41 -0700311 status_t status;
312
313 if (connection == nullptr) {
314 status = DEAD_OBJECT;
315 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700316 status =
317 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700318 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000319
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000320 return PreJoinSetupResult{
321 .connection = std::move(connection),
322 .status = status,
323 };
324}
325
Yifan Hong194acf22021-06-29 18:44:56 -0700326namespace {
Andrei Homescu47f8c4f2022-04-30 01:38:24 +0000327#if !defined(__ANDROID__) || defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -0700328class JavaThreadAttacher {};
329#else
Yifan Hong194acf22021-06-29 18:44:56 -0700330// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
331// Android Runtime doesn't exist, no-op.
332class JavaThreadAttacher {
333public:
334 JavaThreadAttacher() {
335 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
336 // libbinder.
337 auto vm = getJavaVM();
338 if (vm == nullptr) return;
339
340 char threadName[16];
341 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
342 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
343 memcpy(threadName, defaultThreadName,
344 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
345 }
346 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
347 JavaVMAttachArgs args;
348 args.version = JNI_VERSION_1_2;
349 args.name = threadName;
350 args.group = nullptr;
351 JNIEnv* env;
352
353 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
354 "Cannot attach thread %s to JVM", threadName);
355 mAttached = true;
356 }
357 ~JavaThreadAttacher() {
358 if (!mAttached) return;
359 auto vm = getJavaVM();
360 LOG_ALWAYS_FATAL_IF(vm == nullptr,
361 "Unable to detach thread. No JavaVM, but it was present before!");
362
363 LOG_RPC_DETAIL("Detaching current thread from JVM");
364 if (vm->DetachCurrentThread() != JNI_OK) {
365 mAttached = false;
366 } else {
367 ALOGW("Unable to detach current thread from JVM");
368 }
369 }
370
371private:
372 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
373 bool mAttached = false;
374
375 static JavaVM* getJavaVM() {
376 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
377 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
378 if (fn == nullptr) return nullptr;
379 return fn();
380 }
381};
Yifan Hongd258e682021-11-01 18:34:42 -0700382#endif
Yifan Hong194acf22021-06-29 18:44:56 -0700383} // namespace
384
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000385void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
386 sp<RpcConnection>& connection = setupResult.connection;
387
388 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700389 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hongd258e682021-11-01 18:34:42 -0700390 [[maybe_unused]] JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000391 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000392 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000393 RpcState::CommandType::ANY);
394 if (status != OK) {
395 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
396 statusToString(status).c_str());
397 break;
398 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000399 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000400 } else {
401 ALOGE("Connection failed to init, closing with status %s",
402 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000403 }
404
Steven Moreland659416d2021-05-11 00:47:50 +0000405 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000406 {
Steven Moreland659416d2021-05-11 00:47:50 +0000407 std::lock_guard<std::mutex> _l(session->mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700408 auto it = session->mConnections.mThreads.find(std::this_thread::get_id());
409 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000410 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700411 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000412
Steven Moreland659416d2021-05-11 00:47:50 +0000413 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000414 }
415
Steven Morelanddd67b942021-07-23 17:15:41 -0700416 // done after all cleanup, since session shutdown progresses via callbacks here
417 if (connection != nullptr) {
418 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
419 "bad state: connection object guaranteed to be in list");
420 }
421
Steven Moreland659416d2021-05-11 00:47:50 +0000422 session = nullptr;
423
424 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000425 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000426 }
427}
428
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000429sp<RpcServer> RpcSession::server() {
430 RpcServer* unsafeServer = mForServer.unsafe_get();
431 sp<RpcServer> server = mForServer.promote();
432
433 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
434 "wp<> is to avoid strong cycle only");
435 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000436}
437
Steven Moreland826367f2021-09-10 14:05:31 -0700438status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
439 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000440 {
441 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700442 LOG_ALWAYS_FATAL_IF(mConnections.mOutgoing.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000443 "Must only setup session once, but already has %zu clients",
Steven Morelanda59937e2021-10-04 17:42:30 -0700444 mConnections.mOutgoing.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000445 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700446
Yifan Hong832521e2021-08-05 14:55:40 -0700447 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000448
Steven Moreland27a8bc72021-09-29 16:07:41 -0700449 auto oldProtocolVersion = mProtocolVersion;
450 auto cleanup = base::ScopeGuard([&] {
451 // if any threads are started, shut them down
452 (void)shutdownAndWait(true);
453
454 mShutdownListener = nullptr;
455 mEventListener.clear();
456
457 mId.clear();
458
459 mShutdownTrigger = nullptr;
460 mRpcBinderState = std::make_unique<RpcState>();
461
462 // protocol version may have been downgraded - if we reuse this object
463 // to connect to another server, force that server to request a
464 // downgrade again
465 mProtocolVersion = oldProtocolVersion;
466
Steven Morelanda59937e2021-10-04 17:42:30 -0700467 mConnections = {};
Steven Moreland27a8bc72021-09-29 16:07:41 -0700468 });
469
Steven Moreland826367f2021-09-10 14:05:31 -0700470 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000471
Steven Morelandbf57bce2021-07-26 15:26:12 -0700472 {
473 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700474 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
475 ConnectionUse::CLIENT, &connection);
476 status != OK)
477 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700478
479 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700480 if (status_t status =
481 state()->readNewSessionResponse(connection.get(),
482 sp<RpcSession>::fromExisting(this), &version);
483 status != OK)
484 return status;
485 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700486 }
487
Steven Morelanda5036f02021-06-08 02:26:57 +0000488 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000489 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000490 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000491 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700492 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000493 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700494 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000495 }
496
497 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700498 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000499 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700500 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000501 }
502
Yifan Hong1f44f982021-10-08 17:16:47 -0700503 size_t outgoingThreads = std::min(numThreadsAvailable, mMaxOutgoingThreads);
504 ALOGI_IF(outgoingThreads != numThreadsAvailable,
505 "Server hints client to start %zu outgoing threads, but client will only start %zu "
506 "because it is preconfigured to start at most %zu outgoing threads.",
507 numThreadsAvailable, outgoingThreads, mMaxOutgoingThreads);
508
Steven Morelanda5036f02021-06-08 02:26:57 +0000509 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000510 // instead of all at once - the other side should be responsible for setting
511 // up additional connections. We need to create at least one (unless 0 are
512 // requested to be set) in order to allow the other side to reliably make
513 // any requests at all.
514
Steven Moreland4198a122021-08-03 17:37:58 -0700515 // we've already setup one client
Yifan Hong1f44f982021-10-08 17:16:47 -0700516 LOG_RPC_DETAIL("RpcSession::setupClient() instantiating %zu outgoing (server max: %zu) and %zu "
517 "incoming threads",
518 outgoingThreads, numThreadsAvailable, mMaxIncomingThreads);
519 for (size_t i = 0; i + 1 < outgoingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700520 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700521 }
522
Yifan Hong10423062021-10-08 16:26:32 -0700523 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700524 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000525 }
526
Steven Moreland27a8bc72021-09-29 16:07:41 -0700527 cleanup.Disable();
528
Steven Moreland2372f9d2021-08-05 15:42:01 -0700529 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000530}
531
Steven Moreland2372f9d2021-08-05 15:42:01 -0700532status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700533 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700534 return setupOneSocketConnection(addr, sessionId, incoming);
535 });
536}
537
Steven Moreland2372f9d2021-08-05 15:42:01 -0700538status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700539 const std::vector<uint8_t>& sessionId,
540 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000541 for (size_t tries = 0; tries < 5; tries++) {
542 if (tries > 0) usleep(10000);
543
Yifan Hongb675ffe2021-08-05 16:37:17 -0700544 unique_fd serverFd(TEMP_FAILURE_RETRY(
545 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000546 if (serverFd == -1) {
547 int savedErrno = errno;
548 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
549 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700550 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000551 }
552
553 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700554 int connErrno = errno;
555 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
556 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
557 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
558 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
559 if (pollStatus != OK) {
560 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
561 statusToString(pollStatus).c_str());
562 return pollStatus;
563 }
564 // Set connErrno to the errno that connect() would have set if the fd were blocking.
565 socklen_t connErrnoLen = sizeof(connErrno);
566 int ret =
567 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
568 if (ret == -1) {
569 int savedErrno = errno;
570 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
571 "(Original error from connect() is: %s)",
572 strerror(savedErrno), strerror(connErrno));
573 return -savedErrno;
574 }
575 // Retrieved the real connErrno as if connect() was called with a blocking socket
576 // fd. Continue checking connErrno.
577 }
578 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000579 ALOGW("Connection reset on %s", addr.toString().c_str());
580 continue;
581 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700582 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
583 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700584 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700585 strerror(connErrno));
586 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700587 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000588 }
Yifan Hong702115c2021-06-24 15:39:18 -0700589 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
590
Steven Moreland4198a122021-08-03 17:37:58 -0700591 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000592 }
593
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000594 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700595 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000596}
597
Steven Moreland826367f2021-09-10 14:05:31 -0700598status_t RpcSession::initAndAddConnection(unique_fd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700599 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700600 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700601 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700602 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700603 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700604 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700605 }
606
607 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
608
Steven Moreland826367f2021-09-10 14:05:31 -0700609 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
610 ALOGE("Session ID too big %zu", sessionId.size());
611 return BAD_VALUE;
612 }
613
Steven Moreland4198a122021-08-03 17:37:58 -0700614 RpcConnectionHeader header{
615 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
616 .options = 0,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000617 .fileDescriptorTransportMode = static_cast<uint8_t>(mFileDescriptorTransportMode),
Steven Moreland826367f2021-09-10 14:05:31 -0700618 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700619 };
Steven Moreland4198a122021-08-03 17:37:58 -0700620
Steven Moreland826367f2021-09-10 14:05:31 -0700621 if (incoming) {
622 header.options |= RPC_CONNECTION_OPTION_INCOMING;
623 }
Steven Moreland4198a122021-08-03 17:37:58 -0700624
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000625 iovec headerIov{&header, sizeof(header)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000626 auto sendHeaderStatus = server->interruptableWriteFully(mShutdownTrigger.get(), &headerIov, 1,
627 std::nullopt, nullptr);
Yifan Hong8c950422021-08-05 17:13:55 -0700628 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700629 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700630 statusToString(sendHeaderStatus).c_str());
631 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700632 }
633
Steven Moreland826367f2021-09-10 14:05:31 -0700634 if (sessionId.size() > 0) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000635 iovec sessionIov{const_cast<void*>(static_cast<const void*>(sessionId.data())),
636 sessionId.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000637 auto sendSessionIdStatus =
638 server->interruptableWriteFully(mShutdownTrigger.get(), &sessionIov, 1,
639 std::nullopt, nullptr);
Steven Moreland826367f2021-09-10 14:05:31 -0700640 if (sendSessionIdStatus != OK) {
641 ALOGE("Could not write session ID ('%s') to socket: %s",
642 base::HexString(sessionId.data(), sessionId.size()).c_str(),
643 statusToString(sendSessionIdStatus).c_str());
644 return sendSessionIdStatus;
645 }
646 }
647
Steven Moreland4198a122021-08-03 17:37:58 -0700648 LOG_RPC_DETAIL("Socket at client: header sent");
649
650 if (incoming) {
651 return addIncomingConnection(std::move(server));
652 } else {
653 return addOutgoingConnection(std::move(server), true /*init*/);
654 }
655}
656
Steven Moreland2372f9d2021-08-05 15:42:01 -0700657status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000658 std::mutex mutex;
659 std::condition_variable joinCv;
660 std::unique_lock<std::mutex> lock(mutex);
661 std::thread thread;
662 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
663 bool ownershipTransferred = false;
664 thread = std::thread([&]() {
665 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700666 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000667 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
668 sp<RpcSession> session = thiz;
669 session->preJoinThreadOwnership(std::move(thread));
670
671 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700672 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000673
674 ownershipTransferred = true;
675 threadLock.unlock();
676 joinCv.notify_one();
677 // do not use & vars below
678
679 RpcSession::join(std::move(session), std::move(setupResult));
680 });
681 joinCv.wait(lock, [&] { return ownershipTransferred; });
682 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700683 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000684}
685
Yifan Hong832521e2021-08-05 14:55:40 -0700686status_t RpcSession::initShutdownTrigger() {
687 // first client connection added, but setForServer not called, so
688 // initializaing for a client.
689 if (mShutdownTrigger == nullptr) {
690 mShutdownTrigger = FdTrigger::make();
691 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
692 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
693 }
694 return OK;
695}
696
Steven Moreland2372f9d2021-08-05 15:42:01 -0700697status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000698 sp<RpcConnection> connection = sp<RpcConnection>::make();
699 {
700 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700701 connection->rpcTransport = std::move(rpcTransport);
Andrei Homescue922b232022-04-23 03:41:09 +0000702 connection->exclusiveTid = base::GetThreadId();
Steven Morelanda59937e2021-10-04 17:42:30 -0700703 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000704 }
705
Steven Morelandb86e26b2021-06-12 00:35:58 +0000706 status_t status = OK;
707 if (init) {
Steven Morelandfc027e02021-10-25 15:31:31 -0700708 status =
709 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000710 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000711
Andrei Homescuc8490872022-06-23 05:18:51 +0000712 clearConnectionTid(connection);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000713
Steven Moreland2372f9d2021-08-05 15:42:01 -0700714 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000715}
716
Steven Morelanda8b44292021-06-08 01:27:53 +0000717bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland51c44a92021-10-14 16:50:35 -0700718 const std::vector<uint8_t>& sessionId,
719 const sp<IBinder>& sessionSpecificRoot) {
Steven Moreland659416d2021-05-11 00:47:50 +0000720 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
721 LOG_ALWAYS_FATAL_IF(server == nullptr);
722 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
723 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000724 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Andrei Homescu5e301462022-05-12 00:52:34 +0000725 LOG_ALWAYS_FATAL_IF(mCtx != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000726
727 mShutdownTrigger = FdTrigger::make();
728 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000729
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000730 mId = sessionId;
731 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000732 mEventListener = eventListener;
Steven Moreland51c44a92021-10-14 16:50:35 -0700733 mSessionSpecificRootObject = sessionSpecificRoot;
Steven Morelanda8b44292021-06-08 01:27:53 +0000734 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000735}
736
Yifan Hong702115c2021-06-24 15:39:18 -0700737sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
738 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000739 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700740
Yifan Hong10423062021-10-08 16:26:32 -0700741 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700742 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700743 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700744 return nullptr;
745 }
746
Steven Morelanddd67b942021-07-23 17:15:41 -0700747 // Don't accept any more connections, some have shutdown. Usually this
748 // happens when new connections are still being established as part of a
749 // very short-lived session which shuts down after it already started
750 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700751 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700752 return nullptr;
753 }
754
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000755 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700756 session->rpcTransport = std::move(rpcTransport);
Andrei Homescue922b232022-04-23 03:41:09 +0000757 session->exclusiveTid = base::GetThreadId();
Steven Morelanddd67b942021-07-23 17:15:41 -0700758
Steven Morelanda59937e2021-10-04 17:42:30 -0700759 mConnections.mIncoming.push_back(session);
760 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000761
762 return session;
763}
764
Steven Moreland19fc9f72021-06-10 03:57:30 +0000765bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700766 std::unique_lock<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700767 if (auto it =
768 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
769 it != mConnections.mIncoming.end()) {
770 mConnections.mIncoming.erase(it);
771 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000772 sp<EventListener> listener = mEventListener.promote();
773 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700774 _l.unlock();
775 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000776 }
Steven Morelandee78e762021-05-05 21:12:51 +0000777 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000778 return true;
779 }
780 return false;
781}
782
Andrei Homescuc8490872022-06-23 05:18:51 +0000783void RpcSession::clearConnectionTid(const sp<RpcConnection>& connection) {
784 std::unique_lock<std::mutex> _l(mMutex);
785 connection->exclusiveTid = std::nullopt;
786 if (mConnections.mWaitingThreads > 0) {
787 _l.unlock();
788 mAvailableConnectionCv.notify_one();
789 }
790}
791
Yifan Hong9734cfc2021-09-13 16:14:09 -0700792std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700793 return mCtx->getCertificate(format);
794}
795
Steven Moreland195edb82021-06-08 02:44:39 +0000796status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
797 ExclusiveConnection* connection) {
798 connection->mSession = session;
799 connection->mConnection = nullptr;
800 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000801
Andrei Homescue922b232022-04-23 03:41:09 +0000802 uint64_t tid = base::GetThreadId();
Steven Moreland195edb82021-06-08 02:44:39 +0000803 std::unique_lock<std::mutex> _l(session->mMutex);
804
Steven Morelanda59937e2021-10-04 17:42:30 -0700805 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000806 while (true) {
807 sp<RpcConnection> exclusive;
808 sp<RpcConnection> available;
809
810 // CHECK FOR DEDICATED CLIENT SOCKET
811 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000812 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700813 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
814 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000815
816 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700817 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000818 //
819 // Imagine we have more than one thread in play, and a single thread
820 // sends a synchronous, then an asynchronous command. Imagine the
821 // asynchronous command is sent on the first client connection. Then, if
822 // we naively send a synchronous command to that same connection, the
823 // thread on the far side might be busy processing the asynchronous
824 // command. So, we move to considering the second available thread
825 // for subsequent calls.
826 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700827 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
828 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000829 }
830
Steven Morelandc7d40132021-06-10 03:42:11 +0000831 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000832 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000833 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000834 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000835 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700836 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000837
838 // asynchronous calls cannot be nested, we currently allow ref count
839 // calls to be nested (so that you can use this without having extra
840 // threads). Note 'drainCommands' is used so that these ref counts can't
841 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000842 if (exclusiveIncoming != nullptr) {
843 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000844 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000845 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000846 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
847 // prefer available socket, but if we don't have one, don't
848 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000849 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000850 }
851 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000852 }
853
Steven Moreland85e067b2021-05-26 17:43:53 +0000854 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000855 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000856 connection->mConnection = exclusive;
857 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000858 break;
859 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000860 connection->mConnection = available;
861 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000862 break;
863 }
864
Steven Morelanda59937e2021-10-04 17:42:30 -0700865 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland25d9cc52022-03-10 23:11:56 +0000866 ALOGE("Session has no outgoing connections. This is required for an RPC server to make "
867 "any non-nested (e.g. oneway or on another thread) calls. Use code request "
868 "reason: %d. Incoming connections: %zu. %s.",
869 static_cast<int>(use), session->mConnections.mIncoming.size(),
870 (session->server()
871 ? "This is a server session, so see RpcSession::setMaxIncomingThreads "
872 "for the corresponding client"
873 : "This is a client session, so see RpcSession::setMaxOutgoingThreads "
874 "for this client or RpcServer::setMaxThreads for the corresponding "
875 "server"));
Steven Moreland195edb82021-06-08 02:44:39 +0000876 return WOULD_BLOCK;
877 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000878
Steven Moreland85e067b2021-05-26 17:43:53 +0000879 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700880 session->mConnections.mOutgoing.size(),
881 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000882 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000883 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700884 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000885
886 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000887}
888
Andrei Homescue922b232022-04-23 03:41:09 +0000889void RpcSession::ExclusiveConnection::findConnection(uint64_t tid, sp<RpcConnection>* exclusive,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000890 sp<RpcConnection>* available,
891 std::vector<sp<RpcConnection>>& sockets,
892 size_t socketsIndexHint) {
893 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
894 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
895
896 if (*exclusive != nullptr) return; // consistent with break below
897
898 for (size_t i = 0; i < sockets.size(); i++) {
899 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
900
Steven Moreland85e067b2021-05-26 17:43:53 +0000901 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000902 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
903 *available = socket;
904 continue;
905 }
906
Steven Moreland85e067b2021-05-26 17:43:53 +0000907 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000908 // (nested transactions)
909 if (exclusive && socket->exclusiveTid == tid) {
910 *exclusive = socket;
911 break; // consistent with return above
912 }
913 }
914}
915
916RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000917 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000918 // is using this fd, and it retains the right to it. So, we don't give up
919 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000920 if (!mReentrant && mConnection != nullptr) {
Andrei Homescuc8490872022-06-23 05:18:51 +0000921 mSession->clearConnectionTid(mConnection);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000922 }
923}
924
925} // namespace android